Esempio n. 1
0
extern void popup_all_block(GtkTreeModel *model, GtkTreeIter *iter, int id)
{
	char *name = NULL;
	char title[100];
	ListIterator itr = NULL;
	popup_info_t *popup_win = NULL;
	GError *error = NULL;
	int i=0;

	gtk_tree_model_get(model, iter, SORTID_BLOCK, &name, -1);

	switch(id) {
	case JOB_PAGE:
		snprintf(title, 100, "Jobs(s) in block %s", name);
		break;
	case PART_PAGE:
		snprintf(title, 100, "Partition(s) containing block %s", name);
		break;
	case RESV_PAGE:
		snprintf(title, 100, "Reservations(s) containing block %s",
			 name);
		break;
	case NODE_PAGE:
		snprintf(title, 100, "Base Partition(s) in block %s", name);
		break;
	case SUBMIT_PAGE:
		snprintf(title, 100, "Submit job on %s", name);
		break;
	case INFO_PAGE:
		snprintf(title, 100, "Full info for block %s", name);
		break;
	default:
		g_print("Block got %d\n", id);
	}

	itr = list_iterator_create(popup_list);
	while ((popup_win = list_next(itr))) {
		if (popup_win->spec_info)
			if (!strcmp(popup_win->spec_info->title, title)) {
				break;
			}
	}
	list_iterator_destroy(itr);

	if (!popup_win) {
		if (id == INFO_PAGE)
			popup_win = create_popup_info(id, BLOCK_PAGE, title);
		else
			popup_win = create_popup_info(BLOCK_PAGE, id, title);
	} else {
		g_free(name);
		gtk_window_present(GTK_WINDOW(popup_win->popup));
		return;
	}

	/* Pass the model and the structs from the iter so we can always get
	   the current node_inx.
	*/
	popup_win->model = model;
	popup_win->iter = *iter;
	popup_win->node_inx_id = SORTID_NODE_INX;

	switch(id) {
	case JOB_PAGE:
		popup_win->spec_info->search_info->gchar_data = name;
		break;
	case PART_PAGE:
		g_free(name);
		gtk_tree_model_get(model, iter, SORTID_PARTITION, &name, -1);
		popup_win->spec_info->search_info->gchar_data = name;
		break;
	case RESV_PAGE:
	case NODE_PAGE:
		g_free(name);
		gtk_tree_model_get(model, iter, SORTID_NODELIST, &name, -1);
		gtk_tree_model_get(model, iter, SORTID_SMALL_BLOCK, &i, -1);
		if (i) {
			i=0;
			/* strip off the ionodes part */
			while (name[i]) {
				if (name[i] == '[') {
					name[i] = '\0';
					break;
				}
				i++;
			}
		}
		popup_win->spec_info->search_info->gchar_data = name;
		break;
	case INFO_PAGE:
		popup_win->spec_info->search_info->gchar_data = name;
		break;
	default:
		g_print("block got %d\n", id);
	}


	if (!g_thread_create((gpointer)popup_thr, popup_win, FALSE, &error)) {
		g_printerr ("Failed to create part popup thread: %s\n",
			    error->message);
		return;
	}
}
Esempio n. 2
0
main (int argc, char **argv)
{
  g_thread_init (NULL);
  g_type_init ();

  GAsyncQueue *qu;
  qu = g_async_queue_new ();

  gpointer
  th1_f (gpointer data)
  {
    gpointer wat;

    while (TRUE)
      {
        //wat = g_async_queue_pop (qu);
        wat = g_async_queue_try_pop (qu);
        g_thread_yield ();
      }

    return NULL;
  }

  GThread *th1;
  th1 = g_thread_create (th1_f, NULL, TRUE, NULL);

  g_thread_join (th1);

  return EXIT_SUCCESS;
}
Esempio n. 3
0
callable_obj_t *create_new_call (callable_type_t type, call_state_t state,
                      const gchar* const callID,
                      const gchar* const accountID,
                      const gchar* const peer_name,
                      const gchar* const peer_number)
{
    GError *err1 = NULL ;
    callable_obj_t *obj;

    DEBUG ("CallableObj: Create new call");

    DEBUG ("CallableObj: Account: %s", accountID);

    // Allocate memory
    obj = g_new0 (callable_obj_t, 1);

    obj->_error_dialogs = g_ptr_array_new();

    // Set fields
    obj->_type = type;
    obj->_state = state;
    obj->_state_code = 0;
    obj->_state_code_description = NULL;

    if (g_strcasecmp (callID, "") == 0)
    {
        obj->_callID = g_new0 (gchar, 30);
        if (obj->_callID)
            g_sprintf (obj->_callID, "%d", rand());
    }
    else
        obj->_callID = g_strdup (callID);

    obj->_confID = NULL;
    obj->_historyConfID = NULL;
    obj->_accountID = g_strdup (accountID);

    set_timestamp (& (obj->_time_start));
    set_timestamp (& (obj->_time_current));
    set_timestamp (& (obj->_time_stop));

    obj->_srtp_cipher = NULL;
    obj->_sas = NULL;
    obj->_peer_name = g_strdup (peer_name);
    obj->_peer_number = g_strdup (peer_number);
    obj->_trsft_to = NULL;
    obj->_peer_info = get_peer_info (peer_name, peer_number);
    obj->_audio_codec = NULL;
    obj->_recordfile = NULL;
    obj->_record_is_playing = FALSE;

    obj->clockStarted = 1;

    if (obj->_type == CALL) {
        // pthread_create(&(obj->tid), NULL, threaded_clock_incrementer, obj);
        if ( (obj->tid = g_thread_create ( (GThreadFunc) threaded_clock_incrementer, (void *) obj, TRUE, &err1)) == NULL) {
            DEBUG ("Thread creation failed!");
            g_error_free (err1) ;
        }
    }

    obj->_time_added = 0;

    return obj;
}
int
main (int argc, char **argv)
{
  gint i;
  GArray *test_objects;
  GArray *test_threads;
  const gint n_threads = 5;

  g_thread_init (NULL);
  g_print ("START: %s\n", argv[0]);
  g_log_set_always_fatal (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | g_log_set_always_fatal (G_LOG_FATAL_MASK));
  g_type_init ();

  test_objects = g_array_new (FALSE, FALSE, sizeof (GTest *));

  for (i = 0; i < n_threads; i++) {
    GTest *test;
    
    test = g_object_new (G_TYPE_TEST, NULL);
    g_array_append_val (test_objects, test);

    g_assert (test->count == test->dummy);
    g_signal_connect (test, "notify::dummy", G_CALLBACK (dummy_notify), NULL);
  }
    
  test_threads = g_array_new (FALSE, FALSE, sizeof (GThread *));

  stopping = FALSE;

  for (i = 0; i < n_threads; i++) {
    GThread *thread;
    GTest *test;

    test = g_array_index (test_objects, GTest *, i);

    thread = g_thread_create ((GThreadFunc) run_thread, test, TRUE, NULL);
    g_array_append_val (test_threads, thread);
  }
  g_usleep (3000000);

  stopping = TRUE;
  g_print ("\nstopping\n");

  /* join all threads */
  for (i = 0; i < n_threads; i++) {
    GThread *thread;

    thread = g_array_index (test_threads, GThread *, i);
    g_thread_join (thread);
  }

  g_print ("stopped\n");

  for (i = 0; i < n_threads; i++) {
    GTest *test;

    test = g_array_index (test_objects, GTest *, i);

    g_assert (test->count == test->dummy);
  }

  return 0;
}
Esempio n. 5
0
int
main (int   argc,
      char *argv[])
{
  guint seed32, *seedp = NULL;
  gboolean ccounters = FALSE, use_memchunks = FALSE;
  guint n_threads = 1;
  const gchar *mode = "slab allocator + magazine cache", *emode = " ";
  if (argc > 1)
    n_threads = g_ascii_strtoull (argv[1], NULL, 10);
  if (argc > 2)
    {
      guint i, l = strlen (argv[2]);
      for (i = 0; i < l; i++)
        switch (argv[2][i])
          {
          case 'G': /* GLib mode */
            g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, FALSE);
            g_slice_set_config (G_SLICE_CONFIG_BYPASS_MAGAZINES, FALSE);
            mode = "slab allocator + magazine cache";
            break;
          case 'S': /* slab mode */
            g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, FALSE);
            g_slice_set_config (G_SLICE_CONFIG_BYPASS_MAGAZINES, TRUE);
            mode = "slab allocator";
            break;
          case 'M': /* malloc mode */
            g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, TRUE);
            mode = "system malloc";
            break;
          case 'O': /* old memchunks */
            use_memchunks = TRUE;
            mode = "old memchunks";
            break;
          case 'f': /* eager freeing */
            g_slice_set_config (G_SLICE_CONFIG_WORKING_SET_MSECS, 0);
            clean_memchunks = TRUE;
            emode = " with eager freeing";
            break;
          case 'c': /* print contention counters */
            ccounters = TRUE;
            break;
          case '~':
            want_corruption = TRUE; /* force occasional corruption */
            break;
          default:
            usage();
            return 1;
          }
    }
  if (argc > 3)
    prime_size = g_ascii_strtoull (argv[3], NULL, 10);
  if (argc > 4)
    {
      seed32 = g_ascii_strtoull (argv[4], NULL, 10);
      seedp = &seed32;
    }

  g_thread_init (NULL);

  if (argc <= 1)
    usage();

  {
    gchar strseed[64] = "<random>";
    GThread **threads;
    guint i;
    
    if (seedp)
      g_snprintf (strseed, 64, "%u", *seedp);
    g_print ("Starting %d threads allocating random blocks <= %u bytes with seed=%s using %s%s\n", n_threads, prime_size, strseed, mode, emode);
  
    threads = g_alloca (sizeof(GThread*) * n_threads);
    if (!use_memchunks)
      for (i = 0; i < n_threads; i++)
        threads[i] = g_thread_create (test_sliced_mem_thread, seedp, TRUE, NULL);
    else
      {
        for (i = 0; i < n_threads; i++)
          threads[i] = g_thread_create (test_memchunk_thread, seedp, TRUE, NULL);
      }
    for (i = 0; i < n_threads; i++)
      g_thread_join (threads[i]);
  
    if (ccounters)
      {
        guint n, n_chunks = g_slice_get_config (G_SLICE_CONFIG_CHUNK_SIZES);
        g_print ("    ChunkSize | MagazineSize | Contention\n");
        for (i = 0; i < n_chunks; i++)
          {
            gint64 *vals = g_slice_get_config_state (G_SLICE_CONFIG_CONTENTION_COUNTER, i, &n);
            g_print ("  %9" G_GINT64_FORMAT "   |  %9" G_GINT64_FORMAT "   |  %9" G_GINT64_FORMAT "\n", vals[0], vals[2], vals[1]);
            g_free (vals);
          }
      }
    else
      g_print ("Done.\n");
    return 0;
  }
}
void
read_function_cb(gpointer data, gint source, PurpleInputCondition cond)
{
	int len;
	gchar response[3096];
	static GString *response_string = NULL;
	gchar *reply;
	gchar **reply_pieces;
	int i;

	len = read(source, response, sizeof(response)-1);
	if (len < 0)
	{
		if (errno != EAGAIN && errno != EWOULDBLOCK)
		{
			skype_disconnect();
		}
		return;
	}
	
	if (len == sizeof(response)-1)
	{
		if (response_string == NULL)
			response_string = g_string_new_len(response, len);
		else
			response_string = g_string_append_len(response_string, response, len);
	}
	else
	{
		if (response_string)
		{
			if (len > 0)
				response_string = g_string_append_len(response_string, response, len);
			reply = g_string_free(response_string, FALSE);
			response_string = NULL;
		}
		else if (len)
			reply = g_strndup(response, len);
		else
			return;
		reply = g_strstrip(reply);
		reply_pieces = g_strsplit(reply, etb_string, -1);
		g_free(reply);
		for (i=0; reply_pieces[i+1]; i++)
		{
			reply = reply_pieces[i];
			if (g_str_equal(reply, "LOGIN"))
			{
				connected = TRUE;
				in_progress = FALSE;
				skype_debug_info("skype", "Received: LOGIN\n");
			} else {
				g_thread_create((GThreadFunc)skype_message_received, g_strdup(reply), FALSE, NULL);
			}
		}
		//check that we received part of a message
		if (strlen(reply_pieces[i]))
		{
			skype_debug_info("skype", "Last piece: '%s'\n", reply_pieces[i]);
			response_string = g_string_new(reply_pieces[i]);
		}
		g_strfreev(reply_pieces);
	}
}
Esempio n. 7
0
static void play_file(InputPlayback *ipb)
{
	char *filename = ipb->filename;
	int channelcnt = 1;
	FILE *f;
	struct xmp_options *opt;
	int lret;
	GtkTextIter start, end;
	
	opt = xmp_get_options(ctx);

	/* Sorry, no VFS support */
	if (memcmp(filename, "file://", 7) == 0)	/* Audacious 1.4.0 */
		filename += 7;

	_D("play_file: %s", filename);

	stop(ipb);	/* sanity check */

	if ((f = fopen(filename,"rb")) == 0) {
		ipb->playing = 0;
		return;
	}
	fclose(f);

	gtk_text_buffer_get_start_iter(text1b, &start);
	gtk_text_buffer_get_end_iter(text1b, &end);
	gtk_text_buffer_delete(text1b, &start, &end);

	xmp_plugin_audio_error = FALSE;
	ipb->playing = 1;

	opt->resol = 8;
	opt->verbosity = 3;
	opt->drv_id = "callback";

	switch (xmp_cfg.mixing_freq) {
	case 1:
		opt->freq = 22050;	/* 1:2 mixing freq */
		break;
	case 2:
		opt->freq = 11025;	/* 1:4 mixing freq */
		break;
	default:
		opt->freq = 44100;	/* standard mixing freq */
		break;
	}

	if (xmp_cfg.force8bit == 0)
		opt->resol = 16;

	if (xmp_cfg.force_mono == 0) {
		channelcnt = 2;
		opt->outfmt &= ~XMP_FMT_MONO;
	} else {
		opt->outfmt |= XMP_FMT_MONO;
	}

	if (xmp_cfg.interpolation == 1)
		opt->flags |= XMP_CTL_ITPT;
	else
		opt->flags &= ~XMP_CTL_ITPT;

	if (xmp_cfg.filter == 1)
		opt->flags |= XMP_CTL_FILTER;
	else
		opt->flags &= ~XMP_CTL_FILTER;

	opt->mix = xmp_cfg.pan_amplitude;

	play_data.ipb = ipb;
	play_data.fmt = opt->resol == 16 ? FMT_S16_NE : FMT_U8;
	play_data.nch = opt->outfmt & XMP_FMT_MONO ? 1 : 2;
	
	if (audio_open)
	    ipb->output->close_audio();
	
	if (!ipb->output->open_audio(play_data.fmt, opt->freq, play_data.nch)) {
	    ipb->error = TRUE;
	    xmp_plugin_audio_error = TRUE;
	    return;
	}
	
	audio_open = TRUE;

	xmp_open_audio(ctx);

	pipe(fd_info);
	fd_old2 = dup (fileno (stderr));
	dup2(fd_info[1], fileno (stderr));
	fflush(stderr);
	catch_thread = g_thread_create(catch_info, NULL, TRUE, NULL);

	_D("*** loading: %s", filename);
	g_static_mutex_lock(&load_mutex);
	lret =  xmp_load_module(ctx, filename);
	g_static_mutex_unlock(&load_mutex);

	if (lret < 0) {
		xmp_ip.set_info_text("Error loading mod");
		ipb->playing = 0;
		return;
	}

	_D("joining catch thread");
	g_thread_join(catch_thread);
	_D("joined");
	dup2(fileno(stderr), fd_old2);

	gtk_adjustment_set_value(GTK_TEXT_VIEW(text1)->vadjustment, 0.0);

	close(fd_info[0]);
	close(fd_info[1]);

	_D ("before panel update");

	xmp_cfg.time = lret; //xmpi_scan_module((struct xmp_context *)ctx);
	xmp_get_module_info(ctx, &ii->mi);
	strcpy(ii->filename, "");

	new_module = 1;

	_D("after panel update");

	memcpy(&xmp_cfg.mod_info, &ii->mi, sizeof (ii->mi));

#if __AUDACIOUS_PLUGIN_API__ >= 2
	ipb->set_params(ipb, ii->mi.name, lret, 0, opt->freq, channelcnt);
	ipb->playing = 1;
	ipb->eof = 0;
	ipb->error = FALSE;

	decode_thread = g_thread_self();
	ipb->set_pb_ready(ipb);
	play_loop(ipb);
#else
	xmp_ip.set_info(ii->mi.name, lret, 0, opt->freq, channelcnt);
	decode_thread = g_thread_create(play_loop, ipb, TRUE, NULL);
#endif
}
Esempio n. 8
0
int
main (int argc, char *argv[])
{
	signal_user_data_t *ud;
	GValue *preset;
	GError *error = NULL;
	GOptionContext *context;

#ifdef ENABLE_NLS
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	if (!g_thread_supported())
		g_thread_init(NULL);
	context = g_option_context_new ("- Rip and encode DVD or MPEG file");
	g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
	g_option_context_add_group (context, gtk_get_option_group (TRUE));
#if !defined(_WIN32)
	g_option_context_add_group (context, gst_init_get_option_group ());
#endif
	g_option_context_parse (context, &argc, &argv, &error);
	g_option_context_free(context);

	if (argc > 1 && dvd_device == NULL && argv[1][0] != '-')
	{
		dvd_device = argv[1];
	}
	
	gtk_set_locale ();
	gtk_init (&argc, &argv);
	gtk_rc_parse_string(hud_rcstyle);
	g_type_class_unref(g_type_class_ref(GTK_TYPE_BUTTON));
	g_object_set(gtk_settings_get_default(), "gtk-button-images", TRUE, NULL);
#if !defined(_WIN32)
	notify_init("HandBrake");
#endif
	ghb_register_transforms();
	ghb_resource_init();
	ghb_load_icons();

#if !defined(_WIN32)
	dbus_g_thread_init();
#endif
	ghb_udev_init();

	ghb_write_pid_file();
	ud = g_malloc0(sizeof(signal_user_data_t));
	ud->debug = ghb_debug;
	g_log_set_handler (NULL, G_LOG_LEVEL_DEBUG, debug_log_handler, ud);
	g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, warn_log_handler, ud);
	//g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL, warn_log_handler, ud);
	ud->settings = ghb_settings_new();
	ud->builder = create_builder_or_die (BUILDER_NAME);
	// Enable events that alert us to media change events
	watch_volumes (ud);

	//GtkWidget *widget = GHB_WIDGET(ud->builder, "PictureDetelecineCustom");
	//gtk_entry_set_inner_border(widget, 2);

	// Since GtkBuilder no longer assigns object ids to widget names
	// Assign a few that are necessary for style overrides to work
	GtkWidget *widget;
#if defined(_NO_UPDATE_CHECK)
	widget = GHB_WIDGET(ud->builder, "check_updates_box");
	gtk_widget_hide(widget);
#endif

	widget = GHB_WIDGET(ud->builder, "preview_hud");
	gtk_widget_set_name(widget, "preview_hud");
	widget = GHB_WIDGET(ud->builder, "preview_window");
	gtk_widget_set_name(widget, "preview_window");

	// Set up the "hud" control overlay for the preview window
	GtkWidget *draw, *hud, *blender, *align;

	align = GHB_WIDGET(ud->builder, "preview_window_alignment");
	draw = GHB_WIDGET(ud->builder, "preview_image_align");
	hud = GHB_WIDGET(ud->builder, "preview_hud");

	// Set up compositing for hud
	blender = ghb_compositor_new();

	gtk_container_add(GTK_CONTAINER(align), blender);
	ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), draw, 1, 1);
	ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), hud, 2, .85);
	gtk_widget_show(blender);

	// Redirect stderr to the activity window
	ghb_preview_init(ud);
	IoRedirect(ud);
	ghb_log( "%s - %s - %s",
		HB_PROJECT_TITLE, HB_PROJECT_BUILD_TITLE, HB_PROJECT_URL_WEBSITE );
	ghb_init_dep_map();

	// Need to connect x264_options textview buffer to the changed signal
	// since it can't be done automatically
	GtkTextView *textview;
	GtkTextBuffer *buffer;
	textview = GTK_TEXT_VIEW(GHB_WIDGET (ud->builder, "x264Option"));
	buffer = gtk_text_view_get_buffer (textview);
	g_signal_connect(buffer, "changed", (GCallback)x264_entry_changed_cb, ud);

	ghb_combo_init(ud);

	g_debug("ud %p\n", ud);
	g_debug("ud->builder %p\n", ud->builder);

	bind_audio_tree_model(ud);
	bind_subtitle_tree_model(ud);
	bind_presets_tree_model(ud);
	bind_queue_tree_model(ud);
	bind_chapter_tree_model(ud);
	// Connect up the signals to their callbacks
	// I wrote my own connector so that I could pass user data
	// to the callbacks.  Builder's standard autoconnect doesn't all this.
	gtk_builder_connect_signals_full (ud->builder, MyConnect, ud);

	// Load all internal settings
	ghb_settings_init(ud);
	// Load the presets files
	ghb_presets_load(ud);
	ghb_prefs_load(ud);

	ghb_prefs_to_ui(ud);

	gint logLevel;
	logLevel = ghb_settings_get_int(ud->settings, "LoggingLevel");
	ghb_backend_init(logLevel);

	if (ghb_settings_get_boolean(ud->settings, "hbfd"))
	{
		ghb_hbfd(ud, TRUE);
	}
	gchar *source = ghb_settings_get_string(ud->settings, "default_source");
	ghb_dvd_set_current(source, ud);
	g_free(source);

	// Parsing x264 options "" initializes x264 widgets to proper defaults
	ghb_x264_parse_options(ud, "");

	// Populate the presets tree view
	ghb_presets_list_init(ud, NULL, 0);
	// Get the first preset name
	if (arg_preset != NULL)
	{
		preset = ghb_parse_preset_path(arg_preset);
		if (preset)
		{
			ghb_select_preset(ud->builder, preset);
			ghb_value_free(preset);
		}
	}
	else
	{
		ghb_select_default_preset(ud->builder);
	}

	// Grey out widgets that are dependent on a disabled feature
	ghb_check_all_depencencies (ud);

	if (dvd_device != NULL)
	{
		// Source overridden from command line option
		ghb_settings_set_string(ud->settings, "scan_source", dvd_device);
		g_idle_add((GSourceFunc)ghb_idle_scan, ud);
	}
	// Reload and check status of the last saved queue
	g_idle_add((GSourceFunc)ghb_reload_queue, ud);

	// Start timer for monitoring libhb status, 500ms
	g_timeout_add (500, ghb_timer_cb, (gpointer)ud);

	// Add dvd devices to File menu
	ghb_volname_cache_init();
	g_thread_create((GThreadFunc)ghb_cache_volnames, ud, FALSE, NULL);

	GtkStatusIcon *si;
	si = GTK_STATUS_ICON(GHB_OBJECT(ud->builder, "hb_status"));

	gtk_status_icon_set_visible(si,
			ghb_settings_get_boolean(ud->settings, "show_status"));

#if GTK_CHECK_VERSION(2, 16, 0)
	gtk_status_icon_set_has_tooltip(si, TRUE);
	g_signal_connect(si, "query-tooltip", 
					status_icon_query_tooltip_cb, ud);
#else
	gtk_status_icon_set_tooltip(si, "HandBrake");
#endif

	// Ugly hack to keep subtitle table from bouncing around as I change
	// which set of controls are visible
	GtkRequisition req;
	gint height;
	
	widget = GHB_WIDGET(ud->builder, "SrtCodeset");
	gtk_widget_size_request( widget, &req );
	height = req.height;
	widget = GHB_WIDGET(ud->builder, "srt_code_label");
	gtk_widget_size_request( widget, &req );
	height += req.height;
	widget = GHB_WIDGET(ud->builder, "subtitle_table");
	gtk_widget_set_size_request(widget, -1, height);
	
	// Everything should be go-to-go.  Lets rock!

	gtk_main ();
	gtk_status_icon_set_visible(si, FALSE);
	ghb_backend_close();
	if (ud->queue)
		ghb_value_free(ud->queue);
	ghb_value_free(ud->settings);
	g_io_channel_unref(ud->activity_log);
	ghb_settings_close();
#if !defined(_WIN32)
	notify_uninit();
#endif
	g_free(ud);

	return 0;
}
Esempio n. 9
0
int main(void){
	
	GThread *theThread;
	GtkWidget *window;
	GtkWidget *save;
	GtkWidget *hbox;
	GtkWidget *theTable;
	GtkWidget *eBox, *eBox2;
	GtkWidget *lsh,*lsl,*lvh,*lvl;
	
	gtk_init(0,NULL);
	
	loadVars("segVals.dat",theVars);
	//int index=getIndex();
	
	window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
	hbox=gtk_hbox_new(FALSE,2);
	image=gtk_image_new();
	gseg=gtk_image_new();
	eBox=gtk_event_box_new();
	eBox2=gtk_event_box_new();
	theTable=gtk_table_new(5,2,TRUE);
  save = gtk_button_new_with_label("Save!");
	spinvh=gtk_spin_button_new_with_range(0,255,1);
	spinvl=gtk_spin_button_new_with_range(0,255,1);
	spinsh=gtk_spin_button_new_with_range(0,255,1);
	spinsl=gtk_spin_button_new_with_range(0,255,1);
	lsh=gtk_label_new_with_mnemonic("sh");
	lsl=gtk_label_new_with_mnemonic("sl");
	lvh=gtk_label_new_with_mnemonic("vh");
	lvl=gtk_label_new_with_mnemonic("vl");
	hval=gtk_label_new_with_mnemonic("Hue=0");
	
	gtk_window_set_title(GTK_WINDOW(window),"gtk application");
	
	g_signal_connect(window,"delete_event",G_CALLBACK(kill_window),NULL);
	g_signal_connect(eBox,"button_press_event",G_CALLBACK(pressed),image);
	g_signal_connect(eBox2,"button_press_event",G_CALLBACK(pressed),image);
	g_signal_connect(save,"button_press_event",G_CALLBACK(theSaver),NULL);
	g_signal_connect(spinsh,"changed",G_CALLBACK(updateValue), (gpointer)1);
	g_signal_connect(spinsl,"changed",G_CALLBACK(updateValue),(gpointer)2);
	g_signal_connect(spinvh,"changed",G_CALLBACK(updateValue),(gpointer)3);
	g_signal_connect(spinvl,"changed",G_CALLBACK(updateValue),(gpointer)4);//*/
	
	gtk_table_attach_defaults(GTK_TABLE(theTable),spinsh,0,1,0,1);
	gtk_table_attach_defaults(GTK_TABLE(theTable),spinsl,0,1,1,2);
	gtk_table_attach_defaults(GTK_TABLE(theTable),spinvh,0,1,2,3);
	gtk_table_attach_defaults(GTK_TABLE(theTable),spinvl,0,1,3,4);
	gtk_table_attach_defaults(GTK_TABLE(theTable),lsh,1,2,0,1);
	gtk_table_attach_defaults(GTK_TABLE(theTable),lsl,1,2,1,2);
	gtk_table_attach_defaults(GTK_TABLE(theTable),lvh,1,2,2,3);
	gtk_table_attach_defaults(GTK_TABLE(theTable),lvl,1,2,3,4);
	gtk_table_attach_defaults(GTK_TABLE(theTable),hval,0,2,4,5);
	
				updateLimits();
				/*gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinsh),theVars[7+theIndex*2].theInt);
				gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinsl),theVars[6+theIndex*2].theInt);
				gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinvh),theVars[13+theIndex*2].theInt);
				gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinvl),theVars[12+theIndex*2].theInt);//*/
	
	gtk_container_add(GTK_CONTAINER(eBox),image);
	gtk_container_add(GTK_CONTAINER(eBox2),gseg);
	//gtk_box_pack_start(GTK_BOX(hbox),gseg,FALSE,FALSE,2);
	gtk_box_pack_start(GTK_BOX(hbox),eBox2,FALSE,FALSE,2);
	gtk_box_pack_start(GTK_BOX(hbox),eBox,FALSE,FALSE,2);
	gtk_box_pack_start(GTK_BOX(hbox),theTable,FALSE,FALSE,2);
	gtk_box_pack_start(GTK_BOX(hbox),save,TRUE,TRUE,2);
	//gtk_box_pack_start(GTK_BOX(hbox),save,FALSE,FALSE,2);
	gtk_container_add(GTK_CONTAINER(window),hbox);
	
	  if( g_thread_supported() )
  {
     g_thread_init(NULL);
     gdk_threads_init();                   // Called to initialize internal mutex "gdk_threads_mutex".
     printf("g_thread supported\n");
  }
  else
  {
     printf("g_thread NOT supported\n");
     exit(0);
  }
  theThread = g_thread_create((GThreadFunc)ocvThread, NULL, TRUE, NULL);
  assert(theThread!=NULL);
  
	gtk_widget_show_all(window);
	
	gtk_main();
	
	return 0;
}	
Esempio n. 10
0
/**
 * @brief Runs the given command in a seperate thread
 * @sa exec_run_cmd for sync processes
 */
void exec_run (Exec *ex)
{
	ExecState state = RUNNING;
	GList *piped = NULL;
	GList *cmd = ex->cmds;

	exec_cmd_list = g_list_append(exec_cmd_list, ex);

	for (; cmd != NULL && ((state != CANCELLED) && (state != FAILED)); cmd = cmd->next) {
		ExecCmd *e = (ExecCmd*) cmd->data;
		if (e->piped) {
			piped = g_list_append(piped, e);
			piped = g_list_first(piped);
			continue;
		}

		if (e->pre_proc)
			e->pre_proc(e, NULL);

		state = exec_cmd_get_state(e);
		if (state == SKIPPED)
			continue;
		else if (state == CANCELLED)
			break;

		GThread *thread = NULL;
		if (e->lib_proc != NULL)
			e->lib_proc(e, NULL);
		else if (piped != NULL) {
			pipe(child_child_pipe);
			thread = g_thread_create(exec_run_remainder, (gpointer) piped, TRUE, NULL);
			exec_spawn_process(e, exec_stdin_setup_func);
			close(child_child_pipe[0]);
			close(child_child_pipe[1]);
		} else
			exec_spawn_process(e, exec_working_dir_setup_func);

		state = exec_cmd_get_state(e);
		/* If we have spawned off a bunch of children and something went wrong in the
		 * target process, we update the spawned children to failed so they stop. If
		 * cancel was clicked we will already have updated all of the children. */
		if ((/*(state == CANCELLED) || */(state == FAILED)) && (piped != NULL)) {
			GList *cmd = ex->cmds;
			for (; cmd != NULL; cmd = cmd->next)
				exec_cmd_set_state((ExecCmd*) cmd->data, FAILED);
		}

		if (e->post_proc)
			e->post_proc(e, NULL);

		if (thread != NULL)
			g_thread_join(thread);

		g_list_free(piped);
		piped = NULL;
	}

	exec_cmd_list = g_list_remove(exec_cmd_list, ex);
	g_list_free(piped);
	exec_set_outcome(ex);
	sidebar::JobInfo::Instance().update();
}
Esempio n. 11
0
int main(int argc, char *argv[]) {
	struct configuration conf= { NULL, NULL, NULL, 0 };

	GError *error= NULL;
	GOptionContext *context;

	g_thread_init(NULL);

	init_mutex= g_mutex_new();

	if(db == NULL && source_db != NULL){
		db = g_strdup(source_db);
	}

	context= g_option_context_new("multi-threaded MySQL loader");
	GOptionGroup *main_group= g_option_group_new("main", "Main Options", "Main Options", NULL, NULL);
	g_option_group_add_entries(main_group, entries);
	g_option_group_add_entries(main_group, common_entries);
	g_option_context_set_main_group(context, main_group);
	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("option parsing failed: %s, try --help\n", error->message);
		exit(EXIT_FAILURE);
	}
	g_option_context_free(context);

	if (program_version) {
		g_print("myloader %s, built against MySQL %s\n", VERSION, MYSQL_SERVER_VERSION);
		exit(EXIT_SUCCESS);
	}

	set_verbose(verbose);

	if (!directory) {
		g_critical("a directory needs to be specified, see --help\n");
		exit(EXIT_FAILURE);
	} else {
		char *p= g_strdup_printf("%s/metadata", directory);
		if (!g_file_test(p, G_FILE_TEST_EXISTS)) {
			g_critical("the specified directory is not a mydumper backup\n");
			exit(EXIT_FAILURE);
		}
	}

	MYSQL *conn;
	conn= mysql_init(NULL);

	if (defaults_file != NULL) {
		mysql_options(conn,MYSQL_READ_DEFAULT_FILE,defaults_file);
	}
	mysql_options(conn, MYSQL_READ_DEFAULT_GROUP, "myloader");

	if (!mysql_real_connect(conn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Error connection to database: %s", mysql_error(conn));
		exit(EXIT_FAILURE);
	}

	if (mysql_query(conn, "SET SESSION wait_timeout = 2147483")){
		g_warning("Failed to increase wait_timeout: %s", mysql_error(conn));
	}

	if (!enable_binlog)
		mysql_query(conn, "SET SQL_LOG_BIN=0");

	mysql_query(conn, "/*!40014 SET FOREIGN_KEY_CHECKS=0*/");
	conf.queue= g_async_queue_new();
	conf.ready= g_async_queue_new();

	guint n;
	GThread **threads= g_new(GThread*, num_threads);
	struct thread_data *td= g_new(struct thread_data, num_threads);
	for (n= 0; n < num_threads; n++) {
		td[n].conf= &conf;
		td[n].thread_id= n+1;
		threads[n]= g_thread_create((GThreadFunc)process_queue, &td[n], TRUE, NULL);
		g_async_queue_pop(conf.ready);
	}
	g_async_queue_unref(conf.ready);

	g_message("%d threads created", num_threads);

	restore_databases(&conf, conn);

	for (n= 0; n < num_threads; n++) {
		struct job *j= g_new0(struct job, 1);
		j->type = JOB_SHUTDOWN;
		g_async_queue_push(conf.queue, j);
	}

	for (n= 0; n < num_threads; n++) {
		g_thread_join(threads[n]);
	}

	restore_schema_post(conn);

	restore_schema_view(conn);

	restore_schema_triggers(conn);

	g_async_queue_unref(conf.queue);
	mysql_close(conn);
	mysql_thread_end();
	mysql_library_end();
	g_free(directory);
	g_free(td);
	g_free(threads);

	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
}
Esempio n. 12
0
GThread* start_playback(struct musicobject *mobj, struct con_win *cwin)
{
	GThread *thread = NULL;
	GError *error = NULL;

	if (!mobj) {
		g_critical("Dangling entry in current playlist");
		return NULL;
	}

	if (!cwin->cstate->audio_init) {
		g_idle_add(dialog_audio_init, cwin);
		return NULL;
	}

	if ((cwin->cstate->state == ST_PLAYING) ||
	    (cwin->cstate->state == ST_PAUSED)) {
		stop_playback(cwin);
	}

	cwin->cstate->curr_mobj = mobj;
	cwin->cstate->cmd = 0;
	cwin->cstate->curr_mobj_clear = FALSE;

	switch(mobj->file_type) {
	case FILE_WAV:
		thread = g_thread_create(play_thread_wav, cwin, TRUE, &error);
		break;
	case FILE_MP3:
		thread = g_thread_create(play_thread_mp3, cwin, TRUE, &error);
		break;
	case FILE_FLAC:
		thread = g_thread_create(play_thread_flac, cwin, TRUE, &error);
		break;
	case FILE_OGGVORBIS:
		thread = g_thread_create(play_thread_oggvorbis, cwin, TRUE, &error);
		break;
	case FILE_MODPLUG:
		thread = g_thread_create(play_thread_modplug, cwin, TRUE, &error);
		break;
	case FILE_CDDA:
		thread = g_thread_create(play_thread_cdda, cwin, TRUE, &error);
		break;
	default:
		g_warning("Unknown file type");
	}

	if (error) {
		g_critical("Unable to create playback thread : %s",
			   error->message);
		return NULL;
	}
	else {
		cwin->cstate->state = ST_PLAYING;
		play_button_toggle_state(cwin);
		#ifdef HAVE_LIBGLYR
		update_related_state(cwin);
		#endif

		CDEBUG(DBG_INFO, "Starting playback");

		return thread;
	}
}
Esempio n. 13
0
void startRomThread(char *ROMFilepath)
{
    romThread = g_thread_create( (GThreadFunc)playRomThread, ROMFilepath, FALSE, NULL );
}
Esempio n. 14
0
      return NULL;
    }

    info->func = func;
    info->data = data;
    info->prio_level = prio_level;
#if NEW_GLIB_THREAD_API
    thread = g_thread_try_new (name, fluid_thread_high_prio, info, &err);
#else
    thread = g_thread_create (fluid_thread_high_prio, info, detach == FALSE, &err);
#endif
  }
#if NEW_GLIB_THREAD_API
  else thread = g_thread_try_new (name, (GThreadFunc)func, data, &err);
#else
  else thread = g_thread_create ((GThreadFunc)func, data, detach == FALSE, &err);
#endif

  if (!thread)
  {
    FLUID_LOG(FLUID_ERR, "Failed to create the thread: %s",
              fluid_gerror_message (err));
    g_clear_error (&err);
    return NULL;
  }

#if NEW_GLIB_THREAD_API
  if (detach) g_thread_unref (thread);  // Release thread reference, if caller wants to detach
#endif

  return thread;
Esempio n. 15
0
static RSFilterResponse *
get_image(RSFilter *filter, const RSFilterRequest *request)
{
	RSDcp *dcp = RS_DCP(filter);
	RSDcpClass *klass = RS_DCP_GET_CLASS(dcp);
	GdkRectangle *roi;
	RSFilterResponse *previous_response;
	RSFilterResponse *response;
	RS_IMAGE16 *input;
	RS_IMAGE16 *output;
	RS_IMAGE16 *tmp;

	gint j;

	RSFilterRequest *request_clone = rs_filter_request_clone(request);

	if (!dcp->use_profile)
	{
		gfloat premul[4] = {dcp->pre_mul.x, dcp->pre_mul.y, dcp->pre_mul.z, 1.0};
		rs_filter_param_set_float4(RS_FILTER_PARAM(request_clone), "premul", premul);
	}

	rs_filter_param_set_object(RS_FILTER_PARAM(request_clone), "colorspace", klass->prophoto);
	previous_response = rs_filter_get_image(filter->previous, request_clone);
	g_object_unref(request_clone);

	if (!RS_IS_FILTER(filter->previous))
		return previous_response;

	input = rs_filter_response_get_image(previous_response);
	if (!input) return previous_response;
	response = rs_filter_response_clone(previous_response);

	/* We always deliver in ProPhoto */
	rs_filter_param_set_object(RS_FILTER_PARAM(response), "colorspace", klass->prophoto);
	g_object_unref(previous_response);

	if ((roi = rs_filter_request_get_roi(request)))
	{
		/* Align so we start at even pixel counts */
		roi->width += (roi->x&1);
		roi->x -= (roi->x&1);
		roi->width = MIN(input->w - roi->x, roi->width);
		output = rs_image16_copy(input, FALSE);
		tmp = rs_image16_new_subframe(output, roi);
		bit_blt((char*)GET_PIXEL(tmp,0,0), tmp->rowstride * 2, 
			(const char*)GET_PIXEL(input,roi->x,roi->y), input->rowstride * 2, tmp->w * tmp->pixelsize * 2, tmp->h);
	}
	else
	{
		output = rs_image16_copy(input, TRUE);
		tmp = g_object_ref(output);
	}
	g_object_unref(input);
	rs_filter_response_set_image(response, output);
	g_object_unref(output);

	g_static_rec_mutex_lock(&dcp_mutex);
	init_exposure(dcp);

	guint i, y_offset, y_per_thread, threaded_h;
	guint threads = rs_get_number_of_processor_cores();
	if (tmp->h * tmp->w < 200*200)
		threads = 1;

	ThreadInfo *t = g_new(ThreadInfo, threads);

	threaded_h = tmp->h;
	y_per_thread = (threaded_h + threads-1)/threads;
	y_offset = 0;

	for (i = 0; i < threads; i++)
	{
		t[i].tmp = tmp;
		t[i].start_y = y_offset;
		t[i].start_x = 0;
		t[i].dcp = dcp;
		y_offset += y_per_thread;
		y_offset = MIN(tmp->h, y_offset);
		t[i].end_y = y_offset;
		for(j = 0; j < 256; j++)
			t[i].curve_input_values[j] = 0;
		t[i].single_thread = (threads == 1);
		if (threads == 1)
			start_single_dcp_thread(&t[0]);
		else	
			t[i].threadid = g_thread_create(start_single_dcp_thread, &t[i], TRUE, NULL);
	}

	/* Wait for threads to finish */
	for(i = 0; threads > 1 && i < threads; i++)
		g_thread_join(t[i].threadid);

	/* Settings can change now */
	g_static_rec_mutex_unlock(&dcp_mutex);

	/* If we must deliver histogram data, do it now */
	if (dcp->read_out_curve)
	{
		gint *values = g_malloc0(256*sizeof(gint));
		for(i = 0; i < threads; i++)
			for(j = 0; j < 256; j++)
				values[j] += t[i].curve_input_values[j];
		rs_curve_set_histogram_data(RS_CURVE_WIDGET(dcp->read_out_curve), values);
		g_free(values);
	}
	g_free(t);
	g_object_unref(tmp);

	return response;
}
Esempio n. 16
0
static void
receive_message_loop(void)
{
	XEvent e;
	GString *msg = NULL;
	char msg_temp[21];
	size_t len;

	skype_debug_info("skype_x11", "receive_message_loop started\n");
	
	msg_temp[20] = '\0';
	XSetErrorHandler(x11_error_handler);
	while(run_loop)
	{
		if (!disp)
		{
			skype_debug_error("skype_x11", "display has disappeared\n");
			g_thread_create((GThreadFunc)skype_message_received, g_strdup("CONNSTATUS LOGGEDOUT"), FALSE, NULL);
			break;
		}
		
		Bool event_bool;
		g_static_mutex_lock(&x11_mutex);
		event_bool = XCheckTypedEvent(disp, ClientMessage, &e);
		g_static_mutex_unlock(&x11_mutex);
		if (!event_bool)
		{
			g_thread_yield();
			usleep(1000);
			//XPeekEvent(disp, &e);
			//sleep(1);
			continue;
		}/*
		XNextEvent(disp, &e);
		printf("skype event: %d  (clientmessage: %d)\n", e.type, ClientMessage);
		if (e.type != ClientMessage)
			continue;*/
		
		strncpy(msg_temp, e.xclient.data.b, 20);
		len = strlen(msg_temp);
		if (e.xclient.message_type == message_start)
			msg = g_string_new_len(msg_temp, len);
		else if (e.xclient.message_type == message_continue)
			msg = g_string_append_len(msg, msg_temp, len);
		else
		{
			skype_debug_info("skype_x11", "unknown message type: %d\n", e.xclient.message_type);
			if (disp)
			{
				g_static_mutex_lock(&x11_mutex);
				XFlush(disp);
				g_static_mutex_unlock(&x11_mutex);
			}
			continue;
		}
		if (len < 20)
		{
			g_thread_create((GThreadFunc)skype_message_received, (void *)g_string_free(msg, FALSE), FALSE, NULL);
			if (disp)
			{
				g_static_mutex_lock(&x11_mutex);
				XFlush(disp);
				g_static_mutex_unlock(&x11_mutex);
			}
		}
	}
}
int main(int argc, char** argv)
{
	char strOpt[255];
	int ret;
	char str[STR_MAX];
	GError *gerr = NULL;

	// If application is executed by AUL, this is not needed.
	g_setenv("PKG_NAME", "com.samsung.location-api-test", 1);

	g_type_init();

#if !GLIB_CHECK_VERSION (2, 31, 0)
	if( !g_thread_supported() )
	{
		g_thread_init(NULL);
	}
#endif

	GThread *g_main;
	g_main = g_thread_create(GmainThread, NULL, TRUE, &gerr);
	if (!g_main) {
		g_printf("Error create gmain thread: Err domain[%d] Err code[%d] Err msg[%s]",
			gerr->domain, gerr->code, gerr->message);
		g_error_free(gerr);
		return 0;
	}

	json_util_init(LOCATION_API_TEST_JSON_FILE);
	g_printf("--- Start LBS Test App ---\n");
	while(1)
	{
		print_menu();
		g_printf("Select option: ");
		SelectOpt(strOpt);
		g_printf("======================================================================================\n");
		if (0 == g_strcmp0 ("x", strOpt)) {

		}
		else if (0 == g_strcmp0("1",strOpt)) {
			ret = location_init();
			GetLocationError(str, ret);
			g_printf("location_init: returned value [%s]\n", str);
		} else if (0 == g_strcmp0("2",strOpt)) {
			if (location_obj) {
				g_printf("Location object already existed: [0x%x]", (unsigned int)location_obj);
				continue;
			}
			g_printf("LOCATION_METHOD_HYBRID[0] LOCATION_METHOD_GPS[1] LOCATION_METHOD_WPS[2] LOCATION_METHOD_CPS[3]\n");
			g_printf("Select Location Method: ");
			LocationMethod method = PromptInt();
			location_obj = location_new(method);
			if(location_obj) g_printf("Success\n");
			else             g_printf("Failed\n");
		} else if (0 == g_strcmp0("3",strOpt)) {
			ret = location_free (location_obj);
			location_obj = NULL;

			g_sig_enable = 0;
			g_sig_disable = 0;
			g_sig_update = 0;
			g_sig_zonein = 0;
			g_sig_zoneout = 0;
			GetLocationError(str, ret);
			g_printf("location_free: returned value [%s]\n", str);
		} else if (0 == g_strcmp0("4",strOpt)) {
			ret = location_start(location_obj);
			GetLocationError(str, ret);
			g_printf("location_start: returned value [%s]\n", str);
		} else if (0 == g_strcmp0("5",strOpt)) {
			ret = location_stop(location_obj);
			GetLocationError(str, ret);
			g_printf("location_stop: returned value [%s]\n", str);
		} else if (0 == g_strcmp0("6",strOpt)) {
			LocationPosition *pos = NULL;
			LocationAccuracy *acc = NULL;
			ret = location_get_position(location_obj, &pos, &acc);
			GetLocationError(str, ret);
			g_printf("location_get_position: returned value [%s]\n", str);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf("time: [%d], latitude: [%f], longitude: [%f], altitude: [%f], status: [%d]\n", pos->timestamp, pos->latitude, pos->longitude, pos->altitude, pos->status);
				GetAccuracyLevel(str, acc->level);
				g_printf("level: [%s], horizontal_accuracy: [%f], vertical_accuracy: [%f]\n", str, acc->horizontal_accuracy, acc->vertical_accuracy);
			}
			if(pos) location_position_free(pos);
			if(acc) location_accuracy_free(acc);
		} else if (0 == g_strcmp0("6a",strOpt)) {
			LocationPosition *last_pos;
			LocationAccuracy *last_acc;
			int ret = 0;

			ret = location_get_last_position (location_obj, &last_pos, &last_acc);
			GetLocationError(str, ret);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf ("SYNC>> Last position> time: %d, lat: %f, long: %f, alt: %f, status: %d",
					last_pos->timestamp, last_pos->latitude, last_pos->longitude, last_pos->altitude, last_pos->status);
				g_printf ("\tAccuracy level %d (%.0f meters %.0f meters)",
					last_acc->level, last_acc->horizontal_accuracy, last_acc->vertical_accuracy);
				location_position_free(last_pos);
				location_accuracy_free(last_acc);
			} else g_warning ("SYNC>> Last position> failed. Error[%s]",str);

		}else if(0 == g_strcmp0("7",strOpt) ){
			LocationVelocity *vel = NULL;
			LocationAccuracy *acc = NULL;
			ret = location_get_velocity(location_obj, &vel, &acc);
			g_printf("location_get_velocity: returned value [%s]\n", str);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf("time: [%d], speed: [%f], direction: [%f], climb: [%f]\n", vel->timestamp, vel->speed, vel->direction, vel->climb);
				GetAccuracyLevel(str, acc->level);
				g_printf("level: [%s], horizontal_accuracy: [%f], vertical_accuracy: [%f]\n", str, acc->horizontal_accuracy, acc->vertical_accuracy);
			}
			else {
				GetLocationError(str, ret);
				g_warning ("SYNC>> velocity> failed. Error[%s]", str);
			}
			if(vel) location_velocity_free(vel);
			if(acc) location_accuracy_free(acc);
		}else if(0 == g_strcmp0("7a",strOpt) ){
			LocationVelocity *last_vel = NULL;
			LocationAccuracy *last_acc = NULL;
			ret = location_get_last_velocity (location_obj, &last_vel, &last_acc);
			GetLocationError(str, ret);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf ("SYNC>> Last velocity> time: %d, speed: %f, direction:%f, climb:%f",
					last_vel->timestamp, last_vel->speed, last_vel->direction, last_vel->climb);
				g_printf ("\tAccuracy level %d (%.0f meters %.0f meters)",
					last_acc->level, last_acc->horizontal_accuracy, last_acc->vertical_accuracy);
				location_velocity_free(last_vel);
				location_accuracy_free(last_acc);
			} else g_warning ("SYNC>> Last velocity> failed. Error[%s]", str);
		}else if(0 == g_strcmp0("8",strOpt) ){
			int ret = 0, idx = 0;
			LocationSatellite *sat = NULL;
			guint prn;
			gboolean used;
			guint elevation;
			guint azimuth;
			gint snr;

			ret =  location_get_satellite (location_obj, &sat);
			GetLocationError(str, ret);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf ("SYNC>> Current Sattelite> time = %d, satellite in view = %d, satellite in used = %d", sat->timestamp, sat->num_of_sat_inview, sat->num_of_sat_used);
				g_printf ("\tinview satellite information = ");
				for (idx=0; idx<sat->num_of_sat_inview; idx++) {
					location_satellite_get_satellite_details(sat, idx, &prn, &used, &elevation, &azimuth, &snr);
					g_printf ("\t\t[%02d] used: %d, prn: %d, elevation: %d, azimuth: %d, snr: %d", idx, used, prn, elevation, azimuth, snr);
				}
				location_satellite_free (sat);
			} else g_warning ("SYNC>> Current satellite> failed. Error[%s]", str);
		}else if(0 == g_strcmp0("8a",strOpt) ){
			int ret = 0, idx = 0;
			LocationSatellite *last_sat = NULL;
			guint prn;
			gboolean used;
			guint elevation;
			guint azimuth;
			gint snr;

			ret = location_get_last_satellite (location_obj, &last_sat);
			GetLocationError(str, ret);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf ("SYNC>> Last Sattelite> time = %d, satellite in view = %d, satellite in used = %d", last_sat->timestamp, last_sat->num_of_sat_inview, last_sat->num_of_sat_used);
				g_printf ("\tinview satellite information = ");
				for (idx=0; idx<last_sat->num_of_sat_inview; idx++) {
					location_satellite_get_satellite_details(last_sat, idx, &prn, &used, &elevation, &azimuth, &snr);
					g_printf ("\t\t[%02d] used: %d, prn: %d, elevation: %d, azimuth: %d, snr: %d", idx, used, prn, elevation, azimuth, snr);
				}
				location_satellite_free (last_sat);
			} else g_warning ("SYNC>> Last satellite> failed. Error[%s]", str);
		}else if(0 == g_strcmp0("9",strOpt) ) {

			gulong distance;
			int ret = 0;
			char str[STR_MAX];
			LocationPosition pos1, pos2;

			pos1.latitude = 50.0663222;
			pos1.longitude = -5.71475;

			pos2.latitude = 58.6441;
			pos2.longitude = -3.070094;

			ret = location_get_distance(&pos1, &pos2, &distance);
			GetLocationError(str, ret);
			if(ret != LOCATION_ERROR_NONE) {
					g_printf("Fail to get position. Error[%s]\n", str);
			}
			else {
					g_printf("The approximate distance is [%lu]\n", distance);
					g_printf("cf.) It is approximately 969954.114 meter\n");
			}
		}else if(0 == g_strcmp0("10", strOpt)) {
			int method;
			char method_str[STR_MAX] = {0, };
			char input[8] = {0, };
			gboolean is_supported = FALSE;

			g_printf("0.Hybrid 1.GPS 2.WPS 3.CPS\n");
			g_printf("Select Method :");
			fgets(input, 8, stdin);
			method = atoi(input);
			switch(method) {
				case LOCATION_METHOD_HYBRID:
					is_supported = location_is_supported_method(LOCATION_METHOD_HYBRID);
					break;

				case LOCATION_METHOD_GPS:
					is_supported = location_is_supported_method(LOCATION_METHOD_GPS);
					break;

				case LOCATION_METHOD_WPS:
					is_supported = location_is_supported_method(LOCATION_METHOD_WPS);
					break;

				case LOCATION_METHOD_CPS:
					is_supported = location_is_supported_method(LOCATION_METHOD_CPS);
					break;

				default:
					break;

			}
			GetMethod(method_str, method);

			g_printf("Method[%s] is %s.", method_str, is_supported ? "supported" : "not supported");

		}else if(0 == g_strcmp0("11", strOpt)) {
			gboolean is_enabled = FALSE;
			is_enabled = location_is_enabled_gps(location_obj);
			if(is_enabled == TRUE) g_printf("GPS is turned on");
			else g_printf("GPS is turned off");
		}else if(0 == g_strcmp0("99", strOpt)) {
			int ret = 0;
			const *str = "command";
			ret = location_send_command(str);
			if(ret == 0)
				g_printf("Success to send command[%s]", str);
		}else if(0 == g_strcmp0("a1",strOpt)){
			if(location_obj && !g_sig_enable) {
				g_sig_enable = g_signal_connect (location_obj, "service-enabled", G_CALLBACK(cb_service_enabled), location_obj);
			}
		}else if(0 == g_strcmp0("a2",strOpt)){
			if(location_obj && !g_sig_disable){
				g_sig_disable = g_signal_connect (location_obj, "service-disabled", G_CALLBACK(cb_service_disabled), location_obj);
			}
		}else if(0 == g_strcmp0("a3",strOpt)){
			if(location_obj && !g_sig_update){
				g_sig_update = g_signal_connect (location_obj, "service-updated", G_CALLBACK(cb_service_updated), location_obj);
			}
		}else if(0 == g_strcmp0("a4",strOpt)){
			if(location_obj && !g_sig_zonein){
				g_sig_zonein = g_signal_connect (location_obj, "zone-in", G_CALLBACK(cb_zone_in), location_obj);
			}
		}else if(0 == g_strcmp0("a5",strOpt)){
			if(location_obj && !g_sig_zoneout){
				g_sig_zoneout = g_signal_connect (location_obj, "zone-out", G_CALLBACK(cb_zone_out), location_obj);
			}
		}else if(0 == g_strcmp0("b1",strOpt)){
			if(location_obj && g_sig_enable) {
				g_signal_handler_disconnect (location_obj, g_sig_enable);
				g_sig_enable = 0;
			}
		}else if(0 == g_strcmp0("b2",strOpt)){
			if(location_obj && g_sig_disable){
				g_signal_handler_disconnect (location_obj, g_sig_disable);
				g_sig_disable = 0;
			}
		}else if(0 == g_strcmp0("b3",strOpt)){
			if(location_obj && g_sig_update){
				g_signal_handler_disconnect (location_obj, g_sig_update);
				g_sig_update = 0;
			}
		}else if(0 == g_strcmp0("b4",strOpt)){
			if(location_obj && g_sig_zonein){
				g_signal_handler_disconnect (location_obj, g_sig_zonein);
				g_sig_zonein = 0;
			}
		}else if(0 == g_strcmp0("b5",strOpt)){
			if(location_obj && g_sig_zoneout){
				g_signal_handler_disconnect (location_obj, g_sig_zoneout);
				g_sig_zoneout = 0;
			}
		}else if(0 == g_strcmp0("c1",strOpt)){
			LocationBoundary* bound = NULL;
			int i = 0;
			int polygon_count = json_util_get_polygon_count();

			g_printf("[0].San jose(Rect) [1].Suwon HQ(Rect) [2].Seoul City(circle) ");
			for(i = 0; i < polygon_count; i++)
				g_printf("[%d].%s ", i + 3, json_util_get_polygon_name(i));

			g_printf("\nSelect Boundary: ");
			int opt = PromptInt();
			if (opt == 0) {
				LocationPosition* rb = location_position_new (0, 37.300, -121.86, 0, LOCATION_STATUS_2D_FIX);
				LocationPosition* lt = location_position_new (0, 37.360, -121.92, 0, LOCATION_STATUS_2D_FIX);
				bound = location_boundary_new_for_rect (lt, rb);
				location_position_free(rb);
				location_position_free(lt);

				location_boundary_add(location_obj, bound);

			} else if(opt == 1) {
				LocationPosition* rb = location_position_new (0, 37.255, 127.058, 0, LOCATION_STATUS_2D_FIX);
				LocationPosition* lt = location_position_new (0, 37.260, 127.045, 0, LOCATION_STATUS_2D_FIX);
				bound = location_boundary_new_for_rect (lt, rb);
				location_position_free(rb);
				location_position_free(lt);

				location_boundary_add(location_obj, bound);
			} else if(opt == 2) {
				LocationPosition *center = location_position_new(0, 37.566535, 126.977969, 0.0, LOCATION_STATUS_2D_FIX);
				double radius = 10.0;
				bound = location_boundary_new_for_circle(center, radius);

				location_boundary_add(location_obj, bound);
			} else if (opt > 2 && opt < 3 + polygon_count) {
				int index;
				int polygon_index = opt - 3;
				bound = json_util_get_polygon_boundary(polygon_index);
				location_boundary_add(location_obj, bound);

				LocationPosition * check_pos = NULL;
				gboolean ret = FALSE;
				int count = json_util_get_marker_position_count(polygon_index);
				for(index = 0; index < count; index++) {
					check_pos = json_util_get_marker_position(polygon_index, index);

					ret = location_boundary_if_inside(bound, check_pos);
					g_printf("[%s] is [%s] and the test result is [%s]\n", json_util_get_marker_name(polygon_index, index), json_util_result_zone_test(polygon_index, index), ret == TRUE? "inside": "outside");
					location_position_free(check_pos);
				}
			} else {
				g_printf("boundary is not set\n");
			}
			location_boundary_free(bound);

		}else if(0 == g_strcmp0("c2",strOpt)){
			g_printf("Get Boundary\n");
			location_boundary_foreach(location_obj, PrintBoundary, NULL);

		}else if(0 == g_strcmp0("c3",strOpt)){
			g_printf("Remove Boundary\n");
			LocationBoundary* bound = NULL;

			int i = 0;
			int polygon_count = json_util_get_polygon_count();

			g_printf("[0].San jose(Rect) [1].Suwon HQ(Rect) [2].Seoul City(circle) ");
			for(i = 0; i < polygon_count; i++)
				g_printf("[%d].%s ", i + 3, json_util_get_polygon_name(i));

			g_printf("\nSelect Boundary: ");
			int opt = PromptInt();
			if (opt == 0) {
				LocationPosition* rb = location_position_new (0, 37.300, -121.86, 0, LOCATION_STATUS_2D_FIX);
				LocationPosition* lt = location_position_new (0, 37.360, -121.92, 0, LOCATION_STATUS_2D_FIX);
				bound = location_boundary_new_for_rect (lt, rb);
				location_position_free(rb);
				location_position_free(lt);

			} else if(opt == 1) {
				LocationPosition* rb = location_position_new (0, 37.255, 127.058, 0, LOCATION_STATUS_2D_FIX);
				LocationPosition* lt = location_position_new (0, 37.260, 127.045, 0, LOCATION_STATUS_2D_FIX);
				bound = location_boundary_new_for_rect (lt, rb);
				location_position_free(rb);
				location_position_free(lt);

			} else if(opt == 2) {
				LocationPosition *center = location_position_new(0, 37.566535, 126.977969, 0.0, LOCATION_STATUS_2D_FIX);
				double radius = 10.0;
				bound = location_boundary_new_for_circle(center, radius);
				location_position_free(center);

			} else if (opt > 2 && opt < 3 + polygon_count) {
				int polygon_index = opt - 3;
				bound = json_util_get_polygon_boundary(polygon_index);
			} else {
				g_printf("Invalid value\n");
			}

			if(bound != NULL) location_boundary_remove(location_obj, bound);

		}else if(0 == g_strcmp0("c4",strOpt)){
			location_boundary_foreach(location_obj, RemoveBoundary, location_obj);
		}else if(0 == g_strcmp0("c5",strOpt)){
			char buf[255];
			g_printf("Input device name: ");
			fgets(buf, 255, stdin);
			buf[strlen(buf)-1]='\0';
			g_object_set(location_obj, "dev-name", buf, NULL);
		} else if (0 == g_strcmp0("c6", strOpt)) {
			guint interval = 1;
			g_printf("Input interval[1~120]:");
			scanf("%u", &interval);
			g_printf("changed interval to [%u]\n", interval);
			g_object_set(location_obj, "pos-interval", interval, NULL);
		} else if (0 == g_strcmp0("c7", strOpt)) {
			guint interval = 1;
			g_printf("Input interval[1~120]:");
			scanf("%u", &interval);
			g_printf("changed interval to [%u]\n", interval);
			g_object_set(location_obj, "vel-interval", interval, NULL);
		} else if (0 == g_strcmp0("c8", strOpt)) {
			guint interval = 1;
			g_printf("Input interval[1~120]:");
			scanf("%u", &interval);
			g_printf("changed interval to [%u]\n", interval);
			g_object_set(location_obj, "sat-interval", interval, NULL);
		}else if(0 == g_strcmp0("q",strOpt) ){
			g_main_loop_quit(g_mainloop);
			break;
		}
	}
	g_thread_join(g_main);
	g_printf("\n--- Exit LBS Test App ---\n");
	return 1;
}
Esempio n. 18
0
static gboolean
skype_connect()
{
	Window root;
	Atom skype_inst;
	Atom type_ret;
	int format_ret;
	unsigned long nitems_ret;
	unsigned long bytes_after_ret;
	unsigned char *prop;
	int status;
	
	x11_error_code = 0;
	XSetErrorHandler(x11_error_handler);
	skype_debug_info("skype_x11", "Set the XErrorHandler\n");
#ifdef USE_XVFB_SERVER	
	if (!getenv("SKYPEDISPLAY"))
		setenv("SKYPEDISPLAY", ":25", 0);
#endif
	if (getenv("SKYPEDISPLAY"))
		disp = XOpenDisplay(getenv("SKYPEDISPLAY"));
	else
		disp = XOpenDisplay(getenv("DISPLAY"));
	if (disp == NULL)
	{
		skype_debug_info("skype_x11", "Couldn't open display\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Opened display\n");
	message_start = XInternAtom( disp, "SKYPECONTROLAPI_MESSAGE_BEGIN", False );
	message_continue = XInternAtom( disp, "SKYPECONTROLAPI_MESSAGE", False );
	root = DefaultRootWindow( disp );
	win = XCreateSimpleWindow( disp, root, 0, 0, 1, 1,
		0, BlackPixel( disp, DefaultScreen( disp ) ),
		BlackPixel( disp, DefaultScreen( disp ) ));
	XFlush(disp);
	if (win == -1)
	{
		XCloseDisplay(disp);
		skype_debug_info("skype_x11", "Could not create X11 messaging window\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Created X11 messaging window\n");
	skype_inst = XInternAtom(disp, "_SKYPE_INSTANCE", True);
	if (skype_inst == None)
	{
		XDestroyWindow(disp, win);
		XCloseDisplay(disp);
		win = (Window)-1;
		skype_win = (Window)-1;
		skype_debug_info("skype_x11", "Could not create skype Atom\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Created skype Atom\n");
	status = XGetWindowProperty(disp, root, skype_inst, 0, 1, False, XA_WINDOW, &type_ret, &format_ret, &nitems_ret, &bytes_after_ret, &prop);
	if(status != Success || format_ret != 32 || nitems_ret < 1)
	{
		XDestroyWindow(disp, win);
		XCloseDisplay(disp);
		win = (Window)-1;
		XFree(prop);
		skype_win = (Window)-1;
		skype_debug_info("skype", "Skype instance not found\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Skype instance found\n");
	skype_win = * (const unsigned long *) prop & 0xffffffff;
	XFree(prop);
	run_loop = TRUE;
	
	skype_debug_info("skype_x11", "Charging lasers...\n");
	receiving_thread = g_thread_create((GThreadFunc)receive_message_loop, NULL, FALSE, NULL);
	
	return TRUE;
}
Esempio n. 19
0
void
fill_tiles_pixel(	int pixel_x,
			int pixel_y,
			int zoom)
{
	int i,j, tile_count_x, tile_count_y;
	gboolean success = FALSE;
	GError **error = NULL;
//		if (gpsdata!=NULL)
//		{
//			printf("time=%f\n",gpsdata->fix.time);
//			global_time = gpsdata->fix.time;
//		}
//		else	
//		
	
	printf("*** %s(): xyz %d %d %d, time=%d\n",__PRETTY_FUNCTION__,global_x,global_y,global_zoom,global_time);
	
	if (showed_tiles)
	{
		while(g_slist_length(showed_tiles))
		{
			showed_tiles=g_slist_delete_link(showed_tiles,showed_tiles);
			printf("Длина списка - %d\n",g_slist_length(showed_tiles));
		}
	}
	
	tile_count_x = map_drawable->allocation.width / TILESIZE + 2;
	tile_count_y = map_drawable->allocation.height / TILESIZE + 2;
	
	for (i=0; i<tile_count_x;i++)
	{
		for (j=0;  j<tile_count_y; j++)
		{
				key = g_strdup_printf("%s/%d/%d/%d", curr_trf->dir, zoom, i, j);
				gchar* found=g_hash_table_lookup(ht,key);
				printf("found = %s\n",found);
//			if (!found)
				{
					g_hash_table_replace(ht,key,"load_tile()");
//-------------------create thread_data------------------
//					tile_threads *thread_data = g_new0(tile_threads, 1);
					data_of_thread *thread_data = g_new0(data_of_thread, 1);
					thread_data->i = i;
					thread_data->j = j;
//-------------------create thread_data------------------

					if (!g_thread_create(&view_tile, thread_data, FALSE, NULL) != 0)
					{	
						g_warning("can't create VIEW TILE thread");
					}
				}
		}
	}
	
/*	
	
		if (offset_x > 0) offset_x -= 256;
		if (offset_y > 0) offset_y -= 256;
		global_x = pixel_x;
		global_y = pixel_y;
		global_zoom = zoom;
	
		offset_xn = offset_x; 
		offset_yn = offset_y;
	
		width  = map_drawable->allocation.width;
		height = map_drawable->allocation.height;

		tiles_nx = floor((width  - offset_x) / TILESIZE) + 1;
		tiles_ny = floor((height - offset_y) / TILESIZE) + 1;
	
	   	if (strcasestr(curr_trf->name,"Yandex")!=NULL)
		{
			tile_x0 =  floor((float)(pixel_x + merkator_offset_x) / (float)TILESIZE);
			tile_y0 =  floor((float)(pixel_y + merkator_offset_y) / (float)TILESIZE);
		}
		else
		{
			tile_x0 =  floor((float)(pixel_x) / (float)TILESIZE);
			tile_y0 =  floor((float)(pixel_y) / (float)TILESIZE);
		}

		for (i=tile_x0; i<(tile_x0+tiles_nx);i++)
		{
			for (j=tile_y0;  j<(tile_y0+tiles_ny); j++)
			{
				printf("---i,j,x,y,offsetx,y: %d,%d -- %d,%d -- %d,%d\n",i,j,pixel_x,pixel_y,offset_x,offset_y);

				key = g_strdup_printf("%s/%d/%d/%d", curr_trf->dir, zoom, i, j);
				gchar* found=g_hash_table_lookup(ht,key);
				printf("found = %s\n",found);
	
//--------------------create thread_data--------------------
	tile_threads *thread_data = g_new0(tile_threads, 1);
	thread_data->x = i;
	thread_data->y = j;
	thread_data->offset_x = offset_xn;
	thread_data->offset_y = offset_yn;
//--------------------create thread_data--------------------

//		if (!g_thread_create(&load_trf, thread_data, FALSE, NULL) != 0)
//		{	
//			g_warning("can't create DL thread");
//		}
		
//						load_trf(thread_data);
				offset_yn += TILESIZE;
			}
			offset_xn += TILESIZE;
			offset_yn = offset_y;
		}	

//		if (trf_old) traffic_old_factor++;
		if (global_trf_auto)
		{
			printf ("До загрузки пробок осталось %d секунд\n", (traffic_time + 250 +240 - global_time));
			g_timeout_add_seconds ((traffic_time + 250 - global_time), auto_load_trf_timer, NULL);
		}
	}	
*/
//----------Trafic visualization---------------

	success = gconf_client_set_int(
				global_gconfclient, 
				GCONF"/global_x",
				global_x,
				error);
	success = gconf_client_set_int(
				global_gconfclient, 
				GCONF"/global_y",
				global_y,
				error);
	success = gconf_client_set_int(
				global_gconfclient, 
				GCONF"/global_zoom",
				global_zoom,
				error);

}
Esempio n. 20
0
int main(int argc, char *argv[])
{
#ifndef WIN32
    setlinebuf (stdout);
#endif

    char logpath[PATH_MAX];
    memset (logpath, 0, sizeof (logpath));

    logger_t logger;
    memset (&logger, 0, sizeof (logger));

    // set some defaults
    logger.force_overwrite = 0;
    logger.auto_increment = 0;
    logger.use_strftime = 0;
    char *chan_regex = strdup(".*");
    double max_write_queue_size_mb = DEFAULT_MAX_WRITE_QUEUE_SIZE_MB;
    logger.invert_channels = 0;
    logger.fflush_interval_ms = 100;

    char *lcmurl = NULL;
    char *optstring = "a:fic:shm:vu:";
    int c;
    struct option long_opts[] = {
        { "auto-split-hours", required_argument, 0, 'a' },
        { "auto-split-mb", required_argument, 0, 'b' },
        { "channel", required_argument, 0, 'c' },
        { "force", no_argument, 0, 'f' },
        { "increment", required_argument, 0, 'i' },
        { "lcm-url", required_argument, 0, 'l' },
        { "max-unwritten-mb", required_argument, 0, 'm' },
        { "strftime", required_argument, 0, 's' },
        { "invert-channels", no_argument, 0, 'v' },
        { "flush-interval", required_argument, 0,'u'},
        { 0, 0, 0, 0 }
    };

    while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0)
    {
        switch (c) {
            case 'a':
                logger.auto_split_hours = strtod(optarg, NULL);
                logger.auto_increment = 1;
                if(logger.auto_split_hours <= 0) {
                    usage();
                    return 1;
                }
                break;
            case 'b':
                logger.auto_split_mb = strtod(optarg, NULL);
                logger.auto_increment = 1;
                if(logger.auto_split_mb <= 0) {
                    usage();
                    return 1;
                }
                break;
            case 'f':
                logger.force_overwrite = 1;
                break;
            case 'c':
                free(chan_regex);
                chan_regex = strdup(optarg);
                break;
            case 'i':
                logger.auto_increment = 1;
                break;
            case 's':
                logger.use_strftime = 1;
                break;
            case 'l':
                free(lcmurl);
                lcmurl = strdup(optarg);
                break;
            case 'v':
                logger.invert_channels = 1;
                break;
            case 'm':
                max_write_queue_size_mb = strtod(optarg, NULL);
                if(max_write_queue_size_mb <= 0) {
                    usage();
                    return 1;
                }
                break;
            case 'u':
              logger.fflush_interval_ms = atol(optarg);
              if(logger.fflush_interval_ms <= 0) {
                  usage();
                  return 1;
              }
              break;
            case 'h':
            default:
                usage();
                return 1;
        };
    }

    if (optind == argc) {
        strcpy (logger.input_fname, "lcmlog-%Y-%m-%d");
        logger.auto_increment = 1;
        logger.use_strftime = 1;
    } else if (optind == argc - 1) {
        strncpy (logger.input_fname, argv[optind], sizeof (logger.input_fname));
    } else if (optind < argc-1) {
        usage ();
        return 1;
    }

    // initialize GLib threading
    g_thread_init(NULL);

    logger.time0 = timestamp_now();
    logger.max_write_queue_size = (int64_t)(max_write_queue_size_mb * (1 << 20));

    if(0 != open_logfile(&logger))
        return 1;

    // create write thread
    logger.write_thread_exit_flag = 0;
    logger.mutex = g_mutex_new();
    logger.write_queue_size = 0;
    logger.write_queue = g_async_queue_new();
    logger.write_thread = g_thread_create(write_thread, &logger, TRUE, NULL);

    // begin logging
    logger.lcm = lcm_create (lcmurl);
    free(lcmurl);
    if (!logger.lcm) {
        fprintf (stderr, "Couldn't initialize LCM!");
        return 1;
    }

    if(logger.invert_channels) {
        // if inverting the channels, subscribe to everything and invert on the
        // callback
        lcm_subscribe(logger.lcm, ".*", message_handler, &logger);
        char *regexbuf = g_strdup_printf("^%s$", chan_regex);
#ifdef USE_GREGEX
        GError *rerr = NULL;
        logger.regex = g_regex_new(regexbuf, (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, &rerr);
        if(rerr) {
            fprintf(stderr, "%s\n", rerr->message);
            g_free(regexbuf);
            return 1;
        }
#else
        if (0 != regcomp (&logger.preg, regexbuf, REG_NOSUB | REG_EXTENDED)) {
            fprintf(stderr, "bad regex!\n");
            g_free(regexbuf);
            return 1;
        }
#endif
        g_free(regexbuf);
    } else {
        // otherwise, let LCM handle the regex
        lcm_subscribe(logger.lcm, chan_regex, message_handler, &logger);
    }

    free(chan_regex);

    _mainloop = g_main_loop_new (NULL, FALSE);
    signal_pipe_glib_quit_on_kill ();
    glib_mainloop_attach_lcm (logger.lcm);

#ifdef USE_SIGHUP
    signal(SIGHUP, sighup_handler);
#endif

    // main loop
    g_main_loop_run (_mainloop);

    fprintf(stderr, "Logger exiting\n");

    // stop the write thread
    g_mutex_lock(logger.mutex);
    logger.write_thread_exit_flag = 1;
    g_mutex_unlock(logger.mutex);
    g_async_queue_push(logger.write_queue, &logger.write_thread_exit_flag);
    g_thread_join(logger.write_thread);
    g_mutex_free(logger.mutex);

    // cleanup.  This isn't strictly necessary, do it to be pedantic and so that
    // leak checkers don't complain
    glib_mainloop_detach_lcm (logger.lcm);
    lcm_destroy (logger.lcm);
    lcm_eventlog_destroy (logger.log);

    for(void *msg = g_async_queue_try_pop(logger.write_queue); msg;
            msg=g_async_queue_try_pop(logger.write_queue)) {
        if(msg == &logger.write_thread_exit_flag)
            continue;
        free(msg);
    }
    g_async_queue_unref(logger.write_queue);

    if(logger.invert_channels) {
#ifdef USE_GREGEX
        g_regex_unref(logger.regex);
#else
        regfree(&logger.preg);
#endif
    }

    return 0;
}
Esempio n. 21
0
int
ndma_daemon_session (struct ndm_session *sess, int port, int is_test_daemon)
{
	int			listen_sock;
	int			conn_sock, rc;
	socklen_t		len;
	struct sockaddr		sa;

	listen_sock = socket (AF_INET, SOCK_STREAM, 0);
	if (listen_sock < 0) {
		perror ("socket");
		return 1;
	}

	ndmos_condition_listen_socket (sess, listen_sock);

	NDMOS_MACRO_SET_SOCKADDR(&sa, 0, port);

	if (bind (listen_sock, &sa, sizeof sa) < 0) {
		perror ("bind");
		close(listen_sock);
		return 2;
	}

	if (listen (listen_sock, 1) < 0) {
		perror ("listen");
		close(listen_sock);
		return 3;
	}

	if (is_test_daemon) {
	    /* the listen socket is running, so tell our invoker */
	    printf("READY\n");
	    fflush(stdout);

	    /* and exit when our stdin goes away */
	    g_debug("will exit on EOF from stdin");
	    g_thread_init(NULL);
	    g_thread_create(exit_on_stdin_eof_thread, NULL, FALSE, NULL);
	}

	for (;;) {
		len = sizeof sa;
		conn_sock = accept (listen_sock, &sa, &len);
		if (conn_sock < 0) {
			perror ("accept");
			close(listen_sock);
			return 4;
		}

		rc = fork();
		if (rc < 0) {
			perror ("fork");
			close(listen_sock);
			close(conn_sock);
			return 5;
		}

		if (rc == 0) {
			close (listen_sock);
			ndma_server_session (sess, conn_sock);
			exit (0);
		}
		close (conn_sock);
	}

	return 0;
}
Esempio n. 22
0
static void
cb_gimmix_covers_plugin_set_cover_from_file (void)
{
	GtkWidget	*dialog;
	GtkFileFilter	*filter = NULL;
	GtkImage	*preview;
	mpd_Song	*song = NULL;
	gchar		*artist = NULL;
	gchar		*album = NULL;
	
	if (!(song=mpd_playlist_get_current_song(gmo)))
		return;
	
	artist = (song->artist != NULL) ? g_strdup (song->artist) : NULL;
	album = (song->album != NULL) ? g_strdup (song->album) : NULL;
	dialog = gtk_file_chooser_dialog_new ("Open File",
					GTK_WINDOW(main_window),
					GTK_FILE_CHOOSER_ACTION_OPEN,
					GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
					GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
					NULL);
	preview = (GtkImage*)gtk_image_new ();
	gtk_file_chooser_set_preview_widget (GTK_FILE_CHOOSER(dialog), GTK_WIDGET(preview));
	g_signal_connect (GTK_FILE_CHOOSER(dialog), "update-preview", G_CALLBACK (cb_gimmix_covers_plugin_cover_file_preview), preview);
	filter = gtk_file_filter_new ();
	gtk_file_filter_set_name (filter, "Images (.jpg)");
	gtk_file_filter_add_pattern (filter, "*.jpg");
	gtk_file_chooser_add_filter (GTK_FILE_CHOOSER(dialog), filter);
	if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
	{
		char	*filename = NULL;
		gchar	*contents = NULL;
		gsize	len = 0;
		filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
		if (g_file_get_contents(filename, &contents, &len, NULL))
		{
			gchar	*temp = NULL;
			char	*p = cfg_get_path_to_config_file (COVERS_DIR);
			temp = g_strdup_printf ("%s/temp.jpg", p);
			g_free (p);
			if (g_file_set_contents (temp, contents, len, NULL))
			{
				if (artist!=NULL && album!=NULL)
				{
					gimmix_cover_plugin_save_cover (artist, album);
					g_thread_create ((GThreadFunc)gimmix_covers_plugin_update_cover,
							FALSE,
							FALSE,
							NULL);
					g_free (artist);
					g_free (album);
				}
			}
			else
			{
				gimmix_error ("There was an error while setting the album cover. Please try using a different image.");
			}
			g_free (temp);
		}
		g_free (filename);
	}
	gtk_widget_destroy (dialog);
	
	return;
}
Esempio n. 23
0
int
main (int argc,
      char *argv[])
{
  GSocket *socket;
  GSocketAddress *src_address;
  GSocketAddress *address;
  GSocketType socket_type;
  GSocketFamily socket_family;
  GError *error = NULL;
  GOptionContext *context;
  GCancellable *cancellable;
  GSocketAddressEnumerator *enumerator;
  GSocketConnectable *connectable;

  g_thread_init (NULL);

  g_type_init ();

  context = g_option_context_new (" <hostname>[:port] - Test GSocket client stuff");
  g_option_context_add_main_entries (context, cmd_entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (argc != 2)
    {
      g_printerr ("%s: %s\n", argv[0], "Need to specify hostname / unix socket name");
      return 1;
    }

  if (cancel_timeout)
    {
      cancellable = g_cancellable_new ();
      g_thread_create (cancel_thread, cancellable, FALSE, NULL);
    }
  else
    {
      cancellable = NULL;
    }

  loop = g_main_loop_new (NULL, FALSE);

  if (use_udp)
    socket_type = G_SOCKET_TYPE_DATAGRAM;
  else
    socket_type = G_SOCKET_TYPE_STREAM;

  if (unix_socket)
    socket_family = G_SOCKET_FAMILY_UNIX;
  else
    socket_family = G_SOCKET_FAMILY_IPV4;

  socket = g_socket_new (socket_family, socket_type, 0, &error);
  if (socket == NULL)
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (read_timeout)
    g_socket_set_timeout (socket, read_timeout);

  if (unix_socket)
    {
      GSocketAddress *addr;

      addr = socket_address_from_string (argv[1]);
      if (addr == NULL)
	{
	  g_printerr ("%s: Could not parse '%s' as unix socket name\n", argv[0], argv[1]);
	  return 1;
	}
      connectable = G_SOCKET_CONNECTABLE (addr);
    }
  else
    {
      connectable = g_network_address_parse (argv[1], 7777, &error);
      if (connectable == NULL)
	{
	  g_printerr ("%s: %s\n", argv[0], error->message);
	  return 1;
	}
    }

  enumerator = g_socket_connectable_enumerate (connectable);
  while (TRUE)
    {
      address = g_socket_address_enumerator_next (enumerator, cancellable, &error);
      if (address == NULL)
	{
	  if (error == NULL)
	    g_printerr ("%s: No more addresses to try\n", argv[0]);
	  else
	    g_printerr ("%s: %s\n", argv[0], error->message);
	  return 1;
	}

      if (g_socket_connect (socket, address, cancellable, &error))
	break;
      g_printerr ("%s: Connection to %s failed: %s, trying next\n", argv[0], socket_address_to_string (address), error->message);
      g_error_free (error);
      error = NULL;

      g_object_unref (address);
    }
  g_object_unref (enumerator);
  g_object_unref (connectable);

  g_print ("Connected to %s\n",
	   socket_address_to_string (address));

  /* TODO: Test non-blocking connect */
  if (non_blocking)
    g_socket_set_blocking (socket, FALSE);

  src_address = g_socket_get_local_address (socket, &error);
  if (!src_address)
    {
      g_printerr ("Error getting local address: %s\n",
		  error->message);
      return 1;
    }
  g_print ("local address: %s\n",
	   socket_address_to_string (src_address));
  g_object_unref (src_address);

  while (TRUE)
    {
      gchar buffer[4096];
      gssize size;
      gsize to_send;

      if (fgets (buffer, sizeof buffer, stdin) == NULL)
	break;

      to_send = strlen (buffer);
      while (to_send > 0)
	{
	  ensure_condition (socket, "send", cancellable, G_IO_OUT);
	  if (use_udp)
	    size = g_socket_send_to (socket, address,
				     buffer, to_send,
				     cancellable, &error);
	  else
	    size = g_socket_send (socket, buffer, to_send,
				  cancellable, &error);

	  if (size < 0)
	    {
	      if (g_error_matches (error,
				   G_IO_ERROR,
				   G_IO_ERROR_WOULD_BLOCK))
		{
		  g_print ("socket send would block, handling\n");
		  g_error_free (error);
		  error = NULL;
		  continue;
		}
	      else
		{
		  g_printerr ("Error sending to socket: %s\n",
			      error->message);
		  return 1;
		}
	    }

	  g_print ("sent %" G_GSSIZE_FORMAT " bytes of data\n", size);

	  if (size == 0)
	    {
	      g_printerr ("Unexpected short write\n");
	      return 1;
	    }

	  to_send -= size;
	}

      ensure_condition (socket, "receive", cancellable, G_IO_IN);
      if (use_udp)
	size = g_socket_receive_from (socket, &src_address,
				      buffer, sizeof buffer,
				      cancellable, &error);
      else
	size = g_socket_receive (socket, buffer, sizeof buffer,
				 cancellable, &error);

      if (size < 0)
	{
	  g_printerr ("Error receiving from socket: %s\n",
		      error->message);
	  return 1;
	}

      if (size == 0)
	break;

      g_print ("received %" G_GSSIZE_FORMAT " bytes of data", size);
      if (use_udp)
	g_print (" from %s", socket_address_to_string (src_address));
      g_print ("\n");

      if (verbose)
	g_print ("-------------------------\n"
		 "%.*s"
		 "-------------------------\n",
		 (int)size, buffer);

    }

  g_print ("closing socket\n");

  if (!g_socket_close (socket, &error))
    {
      g_printerr ("Error closing master socket: %s\n",
		  error->message);
      return 1;
    }

  g_object_unref (G_OBJECT (socket));
  g_object_unref (G_OBJECT (address));

  return 0;
}
Esempio n. 24
0
File: lcm_file.c Progetto: ahans/lcm
static lcm_provider_t *
lcm_logprov_create (lcm_t * parent, const char *target, const GHashTable *args)
{
    if (!target || !strlen (target)) {
        fprintf (stderr, "Error: Missing filename\n");
        return NULL;
    }

    lcm_logprov_t * lr = (lcm_logprov_t *) calloc (1, sizeof (lcm_logprov_t));
    lr->lcm = parent;
    lr->filename = strdup(target);
    lr->speed = 1;
    lr->next_clock_time = -1;
    lr->start_timestamp = -1;

    g_hash_table_foreach ((GHashTable*) args, new_argument, lr);

    dbg (DBG_LCM, "Initializing LCM log provider context...\n");
    dbg (DBG_LCM, "Filename %s\n", lr->filename);

    if(lcm_internal_pipe_create(lr->notify_pipe) != 0) {
        perror(__FILE__ " - pipe (notify)");
        lcm_logprov_destroy (lr);
        return NULL;
    }
    if(lcm_internal_pipe_create(lr->timer_pipe) != 0) {
        perror(__FILE__ " - pipe (timer)");
        lcm_logprov_destroy (lr);
        return NULL;
    }
    //fcntl (lcm->notify_pipe[1], F_SETFL, O_NONBLOCK);

    if (!lr->writer) {
        lr->log = lcm_eventlog_create (lr->filename, "r");
    } else {
        lr->log = lcm_eventlog_create (lr->filename, "w");
    }

    if (!lr->log) {
        fprintf (stderr, "Error: Failed to open %s: %s\n", lr->filename,
                strerror (errno));
        lcm_logprov_destroy (lr);
        return NULL;
    }

    // only start the reader thread if not in write mode
    if (!lr->writer){
        if (load_next_event (lr) < 0) {
            fprintf (stderr, "Error: Failed to read first event from log\n");
            lcm_logprov_destroy (lr);
            return NULL;
        }

        /* Start the reader thread */
        lr->timer_thread = g_thread_create (timer_thread, lr, TRUE, NULL);
        if (!lr->timer_thread) {
            fprintf (stderr, "Error: LCM failed to start timer thread\n");
            lcm_logprov_destroy (lr);
            return NULL;
        }
        lr->thread_created = 1;

        if(lcm_internal_pipe_write(lr->notify_pipe[1], "+", 1) < 0) {
            perror(__FILE__ " - write (reader create)");
        }

        if(lr->start_timestamp > 0){
            dbg (DBG_LCM, "Seeking to timestamp: %lld\n", (long long)lr->start_timestamp);
            lcm_eventlog_seek_to_timestamp(lr->log, lr->start_timestamp);
        }
    }

    return lr;
}
Esempio n. 25
0
GtkWidget* file_properties_dlg_new( GtkWindow* parent,
                                    const char* dir_path,
                                    GList* sel_files, int page )
{
    GtkBuilder* builder = _gtk_builder_new_from_file( PACKAGE_UI_DIR "/file_properties.ui", NULL );

    GtkWidget * dlg = (GtkWidget*)gtk_builder_get_object( builder, "dlg" );
    GtkNotebook* notebook = (GtkNotebook*)gtk_builder_get_object( builder, "notebook" );
    xset_set_window_icon( GTK_WINDOW( dlg ) );

    FilePropertiesDialogData* data;
    gboolean need_calc_size = TRUE;

    VFSFileInfo *file, *file2;
    VFSMimeType* mime;

    const char* multiple_files = _( "( multiple files )" );
    const char* calculating;
    GtkWidget* name = (GtkWidget*)gtk_builder_get_object( builder, "file_name" );
    GtkWidget* label_name = (GtkWidget*)gtk_builder_get_object( builder, "label_filename" );
    GtkWidget* location = (GtkWidget*)gtk_builder_get_object( builder, "location" );
    gtk_editable_set_editable ( GTK_EDITABLE( location ), FALSE );
    GtkWidget* target = (GtkWidget*)gtk_builder_get_object( builder, "target" );
    GtkWidget* label_target = (GtkWidget*)gtk_builder_get_object( builder, "label_target" );
    gtk_editable_set_editable ( GTK_EDITABLE( target ), FALSE );
    GtkWidget* mime_type = (GtkWidget*)gtk_builder_get_object( builder, "mime_type" );
    GtkWidget* open_with = (GtkWidget*)gtk_builder_get_object( builder, "open_with" );

    char buf[ 64 ];
    char buf2[ 32 ];
    const char* time_format = "%Y-%m-%d %H:%M:%S";

    gchar* disp_path;
    gchar* file_type;

    int i;
    GList* l;
    gboolean same_type = TRUE;
    gboolean is_dirs = FALSE;
    char *owner_group, *tmp;

    gtk_dialog_set_alternative_button_order( GTK_DIALOG(dlg), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1 );
    ptk_dialog_fit_small_screen( GTK_DIALOG(dlg) );

    int width = xset_get_int( "app_dlg", "s" );
    int height = xset_get_int( "app_dlg", "z" );
    if ( width && height )
        gtk_window_set_default_size( GTK_WINDOW( dlg ), width, -1 );

    data = g_slice_new0( FilePropertiesDialogData );
    /* FIXME: When will the data be freed??? */
    g_object_set_data( G_OBJECT( dlg ), "DialogData", data );
    data->file_list = sel_files;
    data->dlg = dlg;

    data->dir_path = g_strdup( dir_path );
    disp_path = g_filename_display_name( dir_path );
    //gtk_label_set_text( GTK_LABEL( location ), disp_path );
    gtk_entry_set_text( GTK_ENTRY( location ), disp_path );
    g_free( disp_path );

    data->total_size_label = GTK_LABEL( (GtkWidget*)gtk_builder_get_object( builder, "total_size" ) );
    data->size_on_disk_label = GTK_LABEL( (GtkWidget*)gtk_builder_get_object( builder, "size_on_disk" ) );
    data->count_label = GTK_LABEL( (GtkWidget*)gtk_builder_get_object( builder, "count" ) );
    data->owner = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "owner" ) );
    data->group = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "group" ) );
    data->mtime = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "mtime" ) );
    data->atime = GTK_ENTRY( (GtkWidget*)gtk_builder_get_object( builder, "atime" ) );

    for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
    {
        data->chmod_btns[ i ] = GTK_TOGGLE_BUTTON( (GtkWidget*)gtk_builder_get_object( builder, chmod_names[ i ] ) );
    }

    //MOD
    VFSMimeType* type; 
    VFSMimeType* type2 = NULL;
    for ( l = sel_files; l ; l = l->next )
    {
        file = ( VFSFileInfo* ) l->data;
        type = vfs_file_info_get_mime_type( file );
        if ( !type2 )
            type2 = vfs_file_info_get_mime_type( file );
        if ( vfs_file_info_is_dir( file ) )
            is_dirs = TRUE;
        if ( type != type2 )
            same_type = FALSE;
        vfs_mime_type_unref( type );
        if ( is_dirs && !same_type )
            break;
    }
    if ( type2 )
        vfs_mime_type_unref( type2 );

    data->recurse = (GtkWidget*)gtk_builder_get_object( builder, "recursive" );
    gtk_widget_set_sensitive( data->recurse, is_dirs );

/*  //MOD
    for ( l = sel_files; l && l->next; l = l->next )
    {
        VFSMimeType *type, *type2;
        file = ( VFSFileInfo* ) l->data;
        file2 = ( VFSFileInfo* ) l->next->data;
        type = vfs_file_info_get_mime_type( file );
        type2 = vfs_file_info_get_mime_type( file2 );
        if ( type != type2 )
        {
            vfs_mime_type_unref( type );
            vfs_mime_type_unref( type2 );
            same_type = FALSE;
            break;
        }
        vfs_mime_type_unref( type );
        vfs_mime_type_unref( type2 );
    }
*/

    file = ( VFSFileInfo* ) sel_files->data;
    if ( same_type )
    {
        mime = vfs_file_info_get_mime_type( file );
        file_type = g_strdup_printf( "%s\n%s",
                                     vfs_mime_type_get_description( mime ),
                                     vfs_mime_type_get_type( mime ) );
        gtk_label_set_text( GTK_LABEL( mime_type ), file_type );
        g_free( file_type );
        vfs_mime_type_unref( mime );
    }
    else
    {
        gtk_label_set_text( GTK_LABEL( mime_type ), _( "( multiple types )" ) );
    }

    /* Open with...
     * Don't show this option menu if files of different types are selected,
     * ,the selected file is a folder, or its type is unknown.
     */
    if( ! same_type ||
          vfs_file_info_is_desktop_entry( file ) ||
        /*  vfs_file_info_is_unknown_type( file ) || */
          vfs_file_info_is_executable( file, NULL ) )
    {
        /* if open with shouldn't show, destroy it. */
        gtk_widget_destroy( open_with );
        open_with = NULL;
        gtk_widget_destroy( (GtkWidget*)gtk_builder_get_object( builder, "open_with_label" ) );
    }
    else /* Add available actions to the option menu */
    {
        GtkTreeIter it;
        char **action, **actions;

        mime = vfs_file_info_get_mime_type( file );
        actions = vfs_mime_type_get_actions( mime );
        GtkCellRenderer* renderer;
        GtkListStore* model;
        gtk_cell_layout_clear( GTK_CELL_LAYOUT(open_with) );
        renderer = gtk_cell_renderer_pixbuf_new();
        gtk_cell_layout_pack_start( GTK_CELL_LAYOUT(open_with), renderer, FALSE);
        gtk_cell_layout_set_attributes( GTK_CELL_LAYOUT(open_with), renderer,
                                        "pixbuf", 0, NULL );
        renderer = gtk_cell_renderer_text_new();
        gtk_cell_layout_pack_start( GTK_CELL_LAYOUT(open_with), renderer, TRUE);
        gtk_cell_layout_set_attributes( GTK_CELL_LAYOUT(open_with),renderer,
                                        "text", 1, NULL );
        model = gtk_list_store_new( 3, GDK_TYPE_PIXBUF,
                                    G_TYPE_STRING,
                                    G_TYPE_STRING,
                                    G_TYPE_STRING );
        if( actions )
        {
            for( action = actions; *action; ++action )
            {
                VFSAppDesktop* desktop;
                GdkPixbuf* icon;
                desktop = vfs_app_desktop_new( *action );
                gtk_list_store_append( model, &it );
                icon = vfs_app_desktop_get_icon(desktop, 20, TRUE);
                gtk_list_store_set( model, &it,
                                    0, icon,
                                    1, vfs_app_desktop_get_disp_name(desktop),
                                    2, *action, -1 );
                if( icon )
                    g_object_unref( icon );
                vfs_app_desktop_unref( desktop );
            }
        }
        else
        {
            g_object_set_data( G_OBJECT(open_with), "prev_sel", GINT_TO_POINTER(-1) );
        }

        /* separator */
        gtk_list_store_append( model, &it );

        gtk_list_store_append( model, &it );
        gtk_list_store_set( model, &it,
                            0, NULL,
                            1, _("Choose..."), -1 );
        gtk_combo_box_set_model( GTK_COMBO_BOX(open_with),
                                 GTK_TREE_MODEL(model) );
        gtk_combo_box_set_row_separator_func(
                GTK_COMBO_BOX(open_with), combo_sep,
                NULL, NULL );
        gtk_combo_box_set_active(GTK_COMBO_BOX(open_with), 0);
        g_signal_connect( open_with, "changed",
                          G_CALLBACK(on_combo_change), mime );

        /* vfs_mime_type_unref( mime ); */
        /* We can unref mime when combo box gets destroyed */
        g_object_weak_ref( G_OBJECT(open_with),
                           (GWeakNotify)vfs_mime_type_unref, mime );
    }
    g_object_set_data( G_OBJECT(dlg), "open_with", open_with );

    /* Multiple files are selected */
    if ( sel_files && sel_files->next )
    {
        gtk_widget_set_sensitive( name, FALSE );
        gtk_entry_set_text( GTK_ENTRY( name ), multiple_files );

        data->orig_mtime = NULL;
        data->orig_atime = NULL;
        
        for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
        {
            gtk_toggle_button_set_inconsistent ( data->chmod_btns[ i ], TRUE );
            data->chmod_states[ i ] = 2; /* Don't touch this bit */
            g_signal_connect( G_OBJECT( data->chmod_btns[ i ] ), "toggled",
                              G_CALLBACK( on_chmod_btn_toggled ), data );
        }
    }
    else
    {
        /* special processing for files with special display names */
        if( vfs_file_info_is_desktop_entry( file ) )
        {
            char* disp_name = g_filename_display_name( file->name );
            gtk_entry_set_text( GTK_ENTRY( name ),
                                disp_name );
            g_free( disp_name );
        }
        else
        {
            if ( vfs_file_info_is_dir( file ) && 
                                            !vfs_file_info_is_symlink( file ) )
                gtk_label_set_markup_with_mnemonic( GTK_LABEL( label_name ),
                                                    _("<b>Folder _Name:</b>") );
            gtk_entry_set_text( GTK_ENTRY( name ),
                                vfs_file_info_get_disp_name( file ) );
        }
        
        gtk_editable_set_editable ( GTK_EDITABLE( name ), FALSE );

        if ( ! vfs_file_info_is_dir( file ) )
        {
            /* Only single "file" is selected, so we don't need to
                caculate total file size */
            need_calc_size = FALSE;

            sprintf( buf, _("%s  ( %lu bytes )"),
                     vfs_file_info_get_disp_size( file ),
                     ( guint64 ) vfs_file_info_get_size( file ) );
            gtk_label_set_text( data->total_size_label, buf );

            vfs_file_size_to_string( buf2,
                                 vfs_file_info_get_blocks( file ) * 512 );
            sprintf( buf, _("%s  ( %lu bytes )"), buf2,
                     ( guint64 ) vfs_file_info_get_blocks( file ) * 512 );
            gtk_label_set_text( data->size_on_disk_label, buf );
            
            gtk_label_set_text( data->count_label, _("1 file") );
        }
        
        // Modified / Accessed
        //gtk_entry_set_text( GTK_ENTRY( mtime ),
        //                    vfs_file_info_get_disp_mtime( file ) );
        strftime( buf, sizeof( buf ),
                  time_format, localtime( vfs_file_info_get_mtime( file ) ) );
        gtk_entry_set_text( GTK_ENTRY( data->mtime ), buf );
        data->orig_mtime = g_strdup( buf );

        strftime( buf, sizeof( buf ),
                  time_format, localtime( vfs_file_info_get_atime( file ) ) );
        gtk_entry_set_text( GTK_ENTRY( data->atime ), buf );
        data->orig_atime = g_strdup( buf );

        // Permissions
        owner_group = (char *) vfs_file_info_get_disp_owner( file );
        tmp = strchr( owner_group, ':' );
        data->owner_name = g_strndup( owner_group, tmp - owner_group );
        gtk_entry_set_text( GTK_ENTRY( data->owner ), data->owner_name );
        data->group_name = g_strdup( tmp + 1 );
        gtk_entry_set_text( GTK_ENTRY( data->group ), data->group_name );

        for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
        {
            if ( data->chmod_states[ i ] != 2 ) /* allow to touch this bit */
            {
                data->chmod_states[ i ] = ( vfs_file_info_get_mode( file ) & chmod_flags[ i ] ? 1 : 0 );
                gtk_toggle_button_set_active( data->chmod_btns[ i ], data->chmod_states[ i ] );
            }
        }
        
        // target
        if ( vfs_file_info_is_symlink( file ) )
        {
            gtk_label_set_markup_with_mnemonic( GTK_LABEL( label_name ),
                                                    _("<b>Link _Name:</b>") );
            disp_path = g_build_filename( dir_path, file->name, NULL );
            char* target_path = g_file_read_link( disp_path, NULL );
            if ( target_path )
            {
                gtk_entry_set_text( GTK_ENTRY( target ), target_path );
                if ( target_path[0] && target_path[0] != '/' )
                {
                    // relative link to absolute
                    char* str = target_path;
                    target_path = g_build_filename( dir_path, str, NULL );
                    g_free( str );
                }
                if ( !g_file_test( target_path, G_FILE_TEST_EXISTS ) )
                    gtk_label_set_text( GTK_LABEL( mime_type ),
                                                    _("( broken link )") );
                g_free( target_path );
            }
            else
                gtk_entry_set_text( GTK_ENTRY( target ), _("( read link error )") );
            g_free( disp_path );
            gtk_widget_show( target );
            gtk_widget_show( label_target );
        }
    }

    if ( need_calc_size )
    {
        /* The total file size displayed in "File Properties" is not
           completely calculated yet. So "Calculating..." is displayed. */
        calculating = _( "Calculating..." );
        gtk_label_set_text( data->total_size_label, calculating );
        gtk_label_set_text( data->size_on_disk_label, calculating );

        g_object_set_data( G_OBJECT( dlg ), "calc_size", data );
        data->calc_size_thread = g_thread_create ( ( GThreadFunc ) calc_size,
                                                   data, TRUE, NULL );
        data->update_label_timer = g_timeout_add( 250,
                                                  ( GSourceFunc ) on_update_labels,
                                                  data );
    }

    g_signal_connect( dlg, "response",
                        G_CALLBACK(on_dlg_response), dlg );
    g_signal_connect_swapped( gtk_builder_get_object(builder, "ok_button"),
                        "clicked",
                        G_CALLBACK(gtk_widget_destroy), dlg );
    g_signal_connect_swapped( gtk_builder_get_object(builder, "cancel_button"),
                        "clicked",
                        G_CALLBACK(gtk_widget_destroy), dlg );
    
    g_object_unref( builder );

    gtk_notebook_set_current_page( notebook, page );

    gtk_window_set_transient_for( GTK_WINDOW( dlg ), parent );
    return dlg;
}
Esempio n. 26
0
void jabber_change_status(GGaduStatusPrototype *sp, gboolean keep_desc)
{
	enum states status;
	LmMessage *m = NULL;
	gchar *show = NULL;
	gchar *show_away = "away";
	gchar *show_xa = "xa";
	gchar *show_dnd = "dnd";
	gchar *show_chat = "chat";
	
	print_debug("jabber_change_status start");
	
	if (!sp)
	    return;
	
	status = sp->status;
	
	/* Just a simple esthetic functionality */
	if((jabber_data.status == JABBER_STATUS_UNAVAILABLE) && sp->status == JABBER_STATUS_UNAVAILABLE)
	{
		GGaduStatusPrototype *sp_temp = ggadu_find_status_prototype(p, jabber_data.status);

		sp_temp->status = JABBER_STATUS_UNAVAILABLE;
		if(sp_temp->status_description)
		{
		    g_free(sp_temp->status_description);
		    sp_temp->status_description = NULL;
		}

		signal_emit("jabber", "gui status changed", sp_temp, "main-gui");
		GGaduStatusPrototype_free(sp_temp);
		return;
	}

	if (status == JABBER_STATUS_UNAVAILABLE)
	{
		lm_connection_close(jabber_data.connection, NULL);
		return;
	}

	/* connect if switched to any other than unavailable */	
	if ((jabber_data.status == JABBER_STATUS_UNAVAILABLE) && (status != JABBER_STATUS_UNAVAILABLE) &&
	    (!jabber_data.connection || !lm_connection_is_open(jabber_data.connection) ||
	     !lm_connection_is_authenticated(jabber_data.connection)))
	{
		g_thread_create(jabber_login_connect, (gpointer) status, FALSE, NULL);
		return;
	}

	
	if (jabber_data.connection && !lm_connection_is_authenticated(jabber_data.connection))
	{
		print_debug("You are not yet authenticated!");
		return;
	}
	
	m = lm_message_new_with_sub_type(NULL, LM_MESSAGE_TYPE_PRESENCE,
					 (status == JABBER_STATUS_UNAVAILABLE) ? 
					 LM_MESSAGE_SUB_TYPE_UNAVAILABLE : LM_MESSAGE_SUB_TYPE_AVAILABLE);

	/* switch (status == JABBER_STATUS_DESCR ? jabber_data.status : status) */
	switch (status)
	{
	case JABBER_STATUS_AWAY:
		show = show_away;
		break;
	case JABBER_STATUS_XA:
		show = show_xa;
		break;
	case JABBER_STATUS_DND:
		show = show_dnd;
		break;
	case JABBER_STATUS_CHAT:
		show = show_chat;
		break;
	case JABBER_STATUS_AVAILABLE:
		show = NULL;
		break;
	default:
		break;
	}

	if (show)
		lm_message_node_add_child(m->node, "show", show);

	if(keep_desc)
	{
	    if(sp->status_description) g_free(sp->status_description);
	    sp->status_description = g_strdup(jabber_data.description);
	}

	if(jabber_data.description)
	{
	    g_free(jabber_data.description);
	    jabber_data.description = NULL;
	}

	if (sp->status_description)
	{
		print_debug("jabber: status description %s %s",sp->status_description,show);
		lm_message_node_add_child(m->node, "status", sp->status_description);
		jabber_data.description = g_strdup(sp->status_description);
	}

	print_debug(lm_message_node_to_string(m->node));

	if (!lm_connection_send(jabber_data.connection, m, NULL))
	{
		print_debug("jabber: Couldn't change status!\n");
	}
	else
	{
		jabber_data.status = status;
		signal_emit("jabber", "gui status changed", sp, "main-gui");
	}
	lm_message_unref(m);
	print_debug("jabber_change_status end");
}
Esempio n. 27
0
static int
_setup_recv_thread (lcm_udpm_t *lcm)
{
    assert (!lcm->thread_created);
    dbg (DBG_LCM, "allocating resources for receiving messages\n");

    // allocate multicast socket
    lcm->recvfd = socket (AF_INET, SOCK_DGRAM, 0);
    if (lcm->recvfd < 0) {
        perror ("allocating LCM recv socket");
        _destroy_recv_parts (lcm);
        return -1;
    }

    struct sockaddr_in addr;
    memset (&addr, 0, sizeof (addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = lcm->params.mc_port;

    // allow other applications on the local machine to also bind to this
    // multicast address and port
    int opt=1;
    dbg (DBG_LCM, "LCM: setting SO_REUSEADDR\n");
    if (setsockopt (lcm->recvfd, SOL_SOCKET, SO_REUSEADDR, 
            (char*)&opt, sizeof (opt)) < 0) {
        perror ("setsockopt (SOL_SOCKET, SO_REUSEADDR)");
        _destroy_recv_parts (lcm);
        return -1;
    }

#ifdef USE_REUSEPORT
    /* Mac OS and FreeBSD require the REUSEPORT option in addition
     * to REUSEADDR or it won't let multiple processes bind to the
     * same port, even if they are using multicast. */
    dbg (DBG_LCM, "LCM: setting SO_REUSEPORT\n");
    if (setsockopt (lcm->recvfd, SOL_SOCKET, SO_REUSEPORT, 
            (char*)&opt, sizeof (opt)) < 0) {
        perror ("setsockopt (SOL_SOCKET, SO_REUSEPORT)");
        _destroy_recv_parts (lcm);
        return -1;
    }
#endif

#if 0
    // set loopback option so that packets sent out on the multicast socket
    // are also delivered to it
    unsigned char lo_opt = 1;
    dbg (DBG_LCM, "LCM: setting multicast loopback option\n");
    status = setsockopt (lcm->recvfd, IPPROTO_IP, IP_MULTICAST_LOOP, 
            &lo_opt, sizeof (lo_opt));
    if (status < 0) {
        perror ("setting multicast loopback");
        return -1;
    }
#endif

#ifdef WIN32
    // Windows has small (8k) buffer by default
    // Increase it to a default reasonable amount
    int recv_buf_size = 2048 * 1024;
    setsockopt(lcm->recvfd, SOL_SOCKET, SO_RCVBUF, 
            (char*)&recv_buf_size, sizeof(recv_buf_size));
#endif

    // debugging... how big is the receive buffer?
    unsigned int retsize = sizeof (int);
    getsockopt (lcm->recvfd, SOL_SOCKET, SO_RCVBUF, 
            (char*)&lcm->kernel_rbuf_sz, (socklen_t *) &retsize);
    dbg (DBG_LCM, "LCM: receive buffer is %d bytes\n", lcm->kernel_rbuf_sz);
    if (lcm->params.recv_buf_size) {
        if (setsockopt (lcm->recvfd, SOL_SOCKET, SO_RCVBUF,
                (char *) &lcm->params.recv_buf_size, 
                sizeof (lcm->params.recv_buf_size)) < 0) {
            perror ("setsockopt(SOL_SOCKET, SO_RCVBUF)");
            fprintf (stderr, "Warning: Unable to set recv buffer size\n");
        }
        getsockopt (lcm->recvfd, SOL_SOCKET, SO_RCVBUF, 
                (char*)&lcm->kernel_rbuf_sz, (socklen_t *) &retsize);
        dbg (DBG_LCM, "LCM: receive buffer is %d bytes\n", lcm->kernel_rbuf_sz);

        if (lcm->params.recv_buf_size > lcm->kernel_rbuf_sz) {
            g_warning ("LCM UDP receive buffer size (%d) \n"
                    "       is smaller than reqested (%d). "
                    "For more info:\n"
                    "       http://lcm.googlecode.com/svn/www/reference/lcm/multicast-setup.html\n", 
                    lcm->kernel_rbuf_sz, lcm->params.recv_buf_size);
        }
    }

    /* Enable per-packet timestamping by the kernel, if available */
#ifdef SO_TIMESTAMP
    opt = 1;
    setsockopt (lcm->recvfd, SOL_SOCKET, SO_TIMESTAMP, &opt, sizeof (opt));
#endif

    if (bind (lcm->recvfd, (struct sockaddr*)&addr, sizeof (addr)) < 0) {
        perror ("bind");
        _destroy_recv_parts (lcm);
        return -1;
    }

    struct ip_mreq mreq;
    mreq.imr_multiaddr = lcm->params.mc_addr;
    mreq.imr_interface.s_addr = INADDR_ANY;
    // join the multicast group
    dbg (DBG_LCM, "LCM: joining multicast group\n");
    if (setsockopt (lcm->recvfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
            (char*)&mreq, sizeof (mreq)) < 0) {
        perror ("setsockopt (IPPROTO_IP, IP_ADD_MEMBERSHIP)");
        _destroy_recv_parts (lcm);
        return -1;
    }

    lcm->inbufs_empty = lcm_buf_queue_new ();
    lcm->inbufs_filled = lcm_buf_queue_new ();
    lcm->ringbuf = lcm_ringbuf_new (LCM_RINGBUF_SIZE);

    int i;
    for (i = 0; i < LCM_DEFAULT_RECV_BUFS; i++) {
        /* We don't set the receive buffer's data pointer yet because it
         * will be taken from the ringbuffer at receive time. */
        lcm_buf_t * lcmb = (lcm_buf_t *) calloc (1, sizeof (lcm_buf_t));
        lcm_buf_enqueue (lcm->inbufs_empty, lcmb);
    }

    // setup a pipe for notifying the reader thread when to quit
    if(0 != lcm_internal_pipe_create(lcm->thread_msg_pipe)) {
        perror(__FILE__ " pipe(setup)");
        _destroy_recv_parts (lcm);
        return -1;
    }
    fcntl (lcm->thread_msg_pipe[1], F_SETFL, O_NONBLOCK);

    /* Start the reader thread */
    lcm->read_thread = g_thread_create (recv_thread, lcm, TRUE, NULL);
    if (!lcm->read_thread) {
        fprintf (stderr, "Error: LCM failed to start reader thread\n");
        _destroy_recv_parts (lcm);
        return -1;
    }
    lcm->thread_created = 1;

    dbg (DBG_LCM, "LCM: conducting self test\n");
    if (udpm_self_test (lcm) < 0) {
        fprintf (stderr, "LCM self test failed!!\n"
                "Check your routing tables and firewall settings\n");
        _destroy_recv_parts (lcm);
        return -1;
    }
    dbg (DBG_LCM, "LCM: self test successful\n");
    return 0;
}
Esempio n. 28
0
int main(void)
{
  NiceAgent *lagent = NULL, *ragent = NULL;
  GThread *stun_thread = NULL;
  NiceAddress baseaddr;

  g_type_init();

  global_mainloop = g_main_loop_new (NULL, FALSE);

#if !GLIB_CHECK_VERSION(2,31,8)
  g_thread_init (NULL);
  stun_thread = g_thread_create (stun_thread_func,
                                 global_mainloop,
                                 TRUE, NULL);
 stun_mutex_ptr = g_mutex_new ();
 stun_signal_ptr = g_cond_new ();
#else
  stun_thread = g_thread_new ("listen for STUN requests",
                              stun_thread_func, NULL);
#endif

  lagent = nice_agent_new (g_main_loop_get_context (global_mainloop),
      NICE_COMPATIBILITY_RFC5245);
  ragent = nice_agent_new (g_main_loop_get_context (global_mainloop),
      NICE_COMPATIBILITY_RFC5245);

  g_object_set (G_OBJECT (lagent), "controlling-mode", TRUE, NULL);
  g_object_set (G_OBJECT (ragent), "controlling-mode", FALSE, NULL);

  g_object_set (G_OBJECT (lagent), "upnp", USE_UPNP, NULL);
  g_object_set (G_OBJECT (ragent), "upnp", USE_UPNP, NULL);

  g_object_set (G_OBJECT (lagent), "stun-server", "127.0.0.1", NULL);
  g_object_set (G_OBJECT (lagent), "stun-server-port", IPPORT_STUN, NULL);

  g_object_set_data (G_OBJECT (lagent), "other-agent", ragent);
  g_object_set_data (G_OBJECT (ragent), "other-agent", lagent);

  g_assert (nice_address_set_from_string (&baseaddr, "127.0.0.1"));
  nice_agent_add_local_address (lagent, &baseaddr);
  nice_agent_add_local_address (ragent, &baseaddr);

  g_signal_connect(G_OBJECT(lagent), "candidate-gathering-done",
                   G_CALLBACK(cb_candidate_gathering_done), LEFT_AGENT);
  g_signal_connect(G_OBJECT(ragent), "candidate-gathering-done",
                   G_CALLBACK(cb_candidate_gathering_done), RIGHT_AGENT);
  g_signal_connect(G_OBJECT(lagent), "component-state-changed",
                   G_CALLBACK(cb_component_state_changed), LEFT_AGENT);
  g_signal_connect(G_OBJECT(ragent), "component-state-changed",
                   G_CALLBACK(cb_component_state_changed), RIGHT_AGENT);

  standard_test (lagent, ragent);
  bad_credentials_test (lagent, ragent);
  bad_candidate_test (lagent, ragent);
  new_candidate_test (lagent, ragent);

  // Do this to make sure the STUN thread exits
  exit_stun_thread = TRUE;
  drop_stun_packets = TRUE;
  send_dummy_data ();

  g_object_unref (lagent);
  g_object_unref (ragent);

  g_thread_join (stun_thread);
#if !GLIB_CHECK_VERSION(2,31,8)
  g_mutex_free (stun_mutex_ptr);
  g_cond_free (stun_signal_ptr);
#endif
  g_main_loop_unref (global_mainloop);

  return 0;
}
G_GNUC_INTERNAL
gboolean
_mdw_default_player_display_init(MdwDefaultPlayerDisplay** p_display, GError** error)
{
    g_assert(p_display != NULL && *p_display == NULL);
    g_assert(error == NULL || *error == NULL);

    DFBResult err;
    
    MdwDefaultPlayerDisplay* display = g_new0(MdwDefaultPlayerDisplay, 1);

    DEBUG_INFO("Initing DirectFB by DirectFBInit");
    if (G_UNLIKELY((err = DirectFBInit(NULL, NULL)) != DFB_OK)) {
        _mdw_default_player_display_finalize(&display);
        g_assert(display == NULL);
        MDW_DEFAULT_PLAYER_RAISE_ERROR_DISPLAY(error, 
            "DirectFBInit failed:%s", DirectFBErrorString(err));
    }

    DEBUG_INFO("Creating DirectFB super interface");
    if (G_UNLIKELY((err = DirectFBCreate(&display->dfb)) != DFB_OK)) {
        _mdw_default_player_display_finalize(&display);
        g_assert(display == NULL);
        MDW_DEFAULT_PLAYER_RAISE_ERROR_DISPLAY(error, 
            "DirectFBCreate failed:%s", DirectFBErrorString(err));
    }
    
    DEBUG_INFO("Getting DirectFB layer number: %u", VIDEO_LAYER);
    if (G_UNLIKELY((err = display->dfb->GetDisplayLayer(display->dfb, DLID_PRIMARY, &display->layer)) != DFB_OK)) {
        _mdw_default_player_display_finalize(&display);
        g_assert(display == 0);
        MDW_DEFAULT_PLAYER_RAISE_ERROR_DISPLAY(error, 
            "GetDisplayLayer failed:%s", DirectFBErrorString(err));
    }

    DEBUG_INFO("Getting the configuration of video layer");
    DFBDisplayLayerConfig config;
    if (G_UNLIKELY((err = display->layer->GetConfiguration(display->layer, &config)) != DFB_OK)) {
        _mdw_default_player_display_finalize(&display);
        g_assert(display == NULL);
        MDW_DEFAULT_PLAYER_RAISE_ERROR_DISPLAY(error, 
            "GetConfiguration failed:%s", DirectFBErrorString(err));
    }

    DEBUG_INFO("Maximum width %d, Maximum height: %d", config.width, config.height);
    display->max_w = config.width;
    display->max_h = config.height;

    DEBUG_INFO("Creating a window");

    DFBWindowDescription wdesc;
    wdesc.flags = DWDESC_WIDTH | DWDESC_HEIGHT | DWDESC_POSX | DWDESC_POSY | DWDESC_CAPS | DWDESC_PIXELFORMAT;
    wdesc.width = display->max_w;
    wdesc.height = display->max_h;
    wdesc.posx = 0;
    wdesc.posy = 0;
    wdesc.caps = DWCAPS_NODECORATION;
    wdesc.pixelformat = DSPF_RGB32;

    if (G_UNLIKELY((err = display->layer->CreateWindow(display->layer, &wdesc, &display->window)) != DFB_OK)) {
        _mdw_default_player_display_finalize(&display);
        g_assert(display == NULL);
        MDW_DEFAULT_PLAYER_RAISE_ERROR_DISPLAY(error, 
            "CreateWindow failed:%s", DirectFBErrorString(err));
    }
    display->window->SetOpacity(display->window, 0xFF);
    display->w = wdesc.width;
    display->h = wdesc.height;
    display->x = wdesc.posx;
    display->y = wdesc.posy;

    DEBUG_INFO("Getting the surface associated with my window");
    if (G_UNLIKELY((err = display->window->GetSurface(display->window, &display->surface)) != DFB_OK)) {
        _mdw_default_player_display_finalize(&display);
        g_assert(display == NULL);
        MDW_DEFAULT_PLAYER_RAISE_ERROR_DISPLAY(error, 
            "GetSurface failed:%s", DirectFBErrorString(err));
    }
    
    display->surface->Clear(display->surface, 0x30, 0x80, 0x30, 0xFF);
    display->surface->Flip(display->surface, NULL, 0);

    DEBUG_INFO("DirectFB full inited");
    *p_display = display;

    display->main_queue = g_async_queue_new();
    display->directfb_queue = g_async_queue_new();

    DEBUG_INFO("Initing display thread");

    display->directfb_thread = g_thread_create(_do_display, display, FALSE, error);

    if (G_UNLIKELY(display->directfb_thread == NULL)) {
        g_assert (error == NULL || *error != NULL);  
        _mdw_default_player_display_finalize(&display);
        g_assert(display == NULL);
        /*MDW_DEFAULT_PLAYER_RAISE_ERROR_DISPLAY(error, 
            "g_thread_create failed");*/
        return FALSE;
    }

    /* wait for thread init */
    /* TODO: implement like mdw_default_player_decoder_ffmpeg.c to handler thread errors while initing */
    MdwMessage* message;
    message = mdw_message_get(display->main_queue, TRUE);
    if (message->type != MDW_MESSAGE_TYPE_READY) {
        mdw_message_free(message, TRUE);
        _mdw_default_player_display_finalize(&display);
        g_assert(display == NULL);
        MDW_DEFAULT_PLAYER_RAISE_ERROR_DISPLAY(error, 
            "failed to init directfb thread");
    }
    mdw_message_free(message, TRUE);
    g_assert(g_async_queue_length(display->main_queue) == 0);

    return TRUE;
}
Esempio n. 30
0
File: server.c Progetto: GNOME/gnio
int
main (int argc,
      char *argv[])
{
  GSocket *socket, *new_socket, *recv_socket;
  GSocketAddress *src_address;
  GSocketAddress *address;
  GSocketType socket_type;
  GError *error = NULL;
  GOptionContext *context;
  GCancellable *cancellable;

  g_thread_init (NULL);

  g_type_init ();

  context = g_option_context_new (" - Test GSocket server stuff");
  g_option_context_add_main_entries (context, cmd_entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (cancel_timeout)
    {
      cancellable = g_cancellable_new ();
      g_thread_create (cancel_thread, cancellable, FALSE, NULL);
    }
  else
    {
      cancellable = NULL;
    }

  loop = g_main_loop_new (NULL, FALSE);

  if (use_udp)
    socket_type = G_SOCKET_TYPE_DATAGRAM;
  else
    socket_type = G_SOCKET_TYPE_STREAM;

  socket = g_socket_new (G_SOCKET_FAMILY_IPV4, socket_type, 0, &error);

  if (socket == NULL)
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (non_blocking)
    g_socket_set_blocking (socket, FALSE);

  src_address = g_inet_socket_address_new (g_inet_address_new_any (G_SOCKET_FAMILY_IPV4), port);
  if (!g_socket_bind (socket, src_address, !dont_reuse_address, &error))
    {
      g_printerr ("Can't bind socket: %s\n", error->message);
      return 1;
    }

  if (!use_udp)
    {
      if (!g_socket_listen (socket, &error))
	{
	  g_printerr ("Can't listen on socket: %s\n", error->message);
	  return 1;
	}

      g_print ("listening on port %d...\n", port);

      ensure_condition (socket, "accept", cancellable, G_IO_IN);
      new_socket = g_socket_accept (socket, &error);
      if (!new_socket)
	{
	  g_printerr ("Error accepting socket: %s\n",
		      error->message);
	  return 1;
	}

      if (non_blocking)
	g_socket_set_blocking (new_socket, FALSE);

      address = g_socket_get_remote_address (new_socket, &error);
      if (!address)
	{
	  g_printerr ("Error getting remote address: %s\n",
		      error->message);
	  return 1;
	}

      g_print ("got a new connection from %s (blocking: %d)\n",
	       socket_address_to_string (address),
	       g_socket_get_blocking (new_socket));

      recv_socket = new_socket;
    }
  else
    {
      recv_socket = socket;
      new_socket = NULL;
    }


  while (TRUE)
    {
      gchar buffer[4096] = { };
      gssize size;
      gsize to_send;

      ensure_condition (recv_socket, "receive", cancellable, G_IO_IN);
      if (use_udp)
	size = g_socket_receive_from (recv_socket, &address,
				      buffer, sizeof buffer, &error);
      else
	size = g_socket_receive (recv_socket, buffer, sizeof buffer, &error);

      if (size < 0)
	{
	  g_printerr ("Error receiving from socket: %s\n",
		      error->message);
	  return 1;
	}

      if (size == 0)
	break;

      g_print ("received %" G_GSSIZE_FORMAT " bytes of data", size);
      if (use_udp)
	g_print (" from %s", socket_address_to_string (address));
      g_print ("\n");

      if (verbose)
	g_print ("-------------------------\n"
		 "%.*s\n"
		 "-------------------------\n",
		 (int)size, buffer);

      to_send = size;

      while (to_send > 0)
	{
	  ensure_condition (recv_socket, "send", cancellable, G_IO_OUT);
	  if (use_udp)
	    size = g_socket_send_to (recv_socket, address,
				     buffer, to_send, &error);
	  else
	    size = g_socket_send (recv_socket, buffer, to_send, &error);

	  if (size < 0)
	    {
	      if (g_error_matches (error,
				   G_IO_ERROR,
				   G_IO_ERROR_WOULD_BLOCK))
		{
		  g_print ("socket send would block, handling\n");
		  g_error_free (error);
		  error = NULL;
		  continue;
		}
	      else
		{
		  g_printerr ("Error sending to socket: %s\n",
			      error->message);
		  return 1;
		}
	    }

	  g_print ("sent %" G_GSSIZE_FORMAT " bytes of data\n", size);

	  if (size == 0)
	    {
	      g_printerr ("Unexpected short write\n");
	      return 1;
	    }

	  to_send -= size;
	}
    }

  g_print ("connection closed\n");

  if (new_socket)
    {
      if (!g_socket_close (new_socket, &error))
	{
	  g_printerr ("Error closing connection socket: %s\n",
		      error->message);
	  return 1;
	}

      g_object_unref (G_OBJECT (new_socket));
    }

  if (!g_socket_close (socket, &error))
    {
      g_printerr ("Error closing master socket: %s\n",
		  error->message);
      return 1;
    }

  g_object_unref (G_OBJECT (socket));

  return 0;
}