Esempio n. 1
0
int main(int argc, char *argv[]){

	GMainLoop *loop;
	GstElement *pipeline, *source, *demuxer, *decoder, *conv, *sink;
	GstBus *bus;
	guint bus_watch_id;
	
	/* Inicializa librerias */
	gst_init (&argc, &argv);
	loop = g_main_loop_new (NULL, FALSE);

	/* Comprueba argumentos */
	if (argc != 2) {
		g_printerr ("Uso: %s <Ogg/Vorbis filename>\n", argv[0]);
		return -1;
	}
	
	/* Create gstreamer elements */
	pipeline = gst_pipeline_new ("audio-player");
	source = gst_element_factory_make ("filesrc", "file-source");
	demuxer = gst_element_factory_make ("oggdemux", "ogg-demuxer");
	decoder = gst_element_factory_make ("theoradec", "theoradec-decoder");
	conv = gst_element_factory_make ("videoconvert", "converter");
	sink = gst_element_factory_make ("ximagesink", "video_out");
	if (!pipeline || !source || !demuxer || !decoder || !conv || !sink) {
		g_printerr ("Error al crear algun elemento. Saliendo.\n");
		return -1;
	}

	/* Set up the pipeline */
	/* we set the input filename to the source element */
	g_object_set (G_OBJECT (source), "location", argv[1], NULL);

	/* we add a message handler */
	bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
	bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
	gst_object_unref (bus);

	/* we add all elements into the pipeline */
	/* file-source | ogg-demuxer | vorbis-decoder | converter | video-output */
	gst_bin_add_many (GST_BIN (pipeline), source, demuxer, decoder, conv, sink, NULL);

	/* we link the elements together */
	/* file-source -> ogg-demuxer ~> vorbis-decoder -> converter -> alsa-output */
	gst_element_link (source, demuxer);
	gst_element_link_many (decoder, conv, sink, NULL);

	g_signal_connect (demuxer, "pad-added", G_CALLBACK (on_pad_added), decoder);
	/* note that the demuxer will be linked to the decoder dynamically.
	The reason is that Ogg may contain various streams (for example
	audio and video). The source pad(s) will be created at run time,
	by the demuxer when it detects the amount and nature of streams.
	Therefore we connect a callback function which will be executed
	when the "pad-added" is emitted.*/

	/* Set the pipeline to "playing" state*/
	g_print ("Now playing: %s\n", argv[1]);
	gst_element_set_state (pipeline, GST_STATE_PLAYING);
	
	/* Iterate */
	g_print ("Running...\n");
	g_main_loop_run (loop);
	
	/* Out of the main loop, clean up nicely */
	g_print ("Returned, stopping playback\n");
	gst_element_set_state (pipeline, GST_STATE_NULL);
	g_print ("Deleting pipeline\n");
	gst_object_unref (GST_OBJECT (pipeline));
	g_source_remove (bus_watch_id);
	g_main_loop_unref (loop);

return 0;
}
Esempio n. 2
0
int
main (int argc, char **argv)
{
	gchar *log_filename;
	GMainLoop *loop;
	GOptionContext *context;
	TrackerMinerRSS *miner;
	GError *error = NULL;
	const gchar *error_message;

	g_type_init();

	setlocale (LC_ALL, "");

	bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
	tzset ();

	/* Translators: this messagge will apper immediately after the
	 * usage string - Usage: COMMAND <THIS_MESSAGE>
	 */
	context = g_option_context_new (_("- start the feeds indexer"));
	g_option_context_add_main_entries (context, entries, NULL);
	g_option_context_parse (context, &argc, &argv, NULL);

	if ((add_feed && !title) || (!add_feed && title)) {
		error_message = _("Adding a feed requires --add-feed and --title");
	} else {
		error_message = NULL;
	}

	if (error_message) {
		gchar *help;

		g_printerr ("%s\n\n", error_message);

		help = g_option_context_get_help (context, TRUE, NULL);
		g_option_context_free (context);
		g_printerr ("%s", help);
		g_free (help);

		return EXIT_FAILURE;
	}

	g_option_context_free (context);

	/* Command line stuff doesn't use logging, so we're using g_print*() */
	if (add_feed && title) {
		TrackerSparqlConnection *connection;
		const gchar *query;

		g_print ("Adding feed:\n"
		         "  title:'%s'\n"
		         "  url:'%s'\n",
		         title,
		         add_feed);

		connection = tracker_sparql_connection_get (NULL, &error);

		if (!connection) {
			g_printerr ("%s: %s\n",
			            _("Could not establish a connection to Tracker"),
			            error ? error->message : _("No error given"));
			g_clear_error (&error);
			return EXIT_FAILURE;
		}

		/* FIXME: Make interval configurable */
		query = g_strdup_printf ("INSERT {"
		                         "  _:FeedSettings a mfo:FeedSettings ;"
		                         "                   mfo:updateInterval 20 ."
		                         "  _:Feed a nie:DataObject, mfo:FeedChannel ;"
		                         "           mfo:feedSettings _:FeedSettings ;"
		                         "           nie:url \"%s\" ;"
		                         "           nie:title \"%s\" . "
		                         "}",
		                         add_feed,
		                         title);

		tracker_sparql_connection_update (connection,
		                                  query,
		                                  G_PRIORITY_DEFAULT,
		                                  NULL,
		                                  &error);

		if (error) {
			g_printerr ("%s, %s\n",
			            _("Could not add feed"),
			            error->message);
			g_error_free (error);
			g_object_unref (connection);

			return EXIT_FAILURE;
		}

		g_print ("Done\n");

		return EXIT_SUCCESS;
	}

	tracker_log_init (verbosity, &log_filename);
	if (log_filename != NULL) {
		g_message ("Using log file:'%s'", log_filename);
		g_free (log_filename);
	}

	miner = tracker_miner_rss_new (&error);
	if (!miner) {
		g_critical ("Could not create new RSS miner: '%s', exiting...\n",
		            error ? error->message : "unknown error");
		return EXIT_FAILURE;
	}

	tracker_miner_start (TRACKER_MINER (miner));

	loop = g_main_loop_new (NULL, FALSE);
	g_main_loop_run (loop);

	tracker_log_shutdown ();
	g_main_loop_unref (loop);
	g_object_unref (miner);

	return EXIT_SUCCESS;
}
Esempio n. 3
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GOptionGroup *gatt_group, *params_group, *char_rw_group;
	GError *gerr = NULL;
	GAttrib *attrib;
	GIOChannel *chan;
	GSourceFunc callback;

	opt_sec_level = g_strdup("low");

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	/* GATT commands */
	gatt_group = g_option_group_new("gatt", "GATT commands",
					"Show all GATT commands", NULL, NULL);
	g_option_context_add_group(context, gatt_group);
	g_option_group_add_entries(gatt_group, gatt_options);

	/* Primary Services and Characteristics arguments */
	params_group = g_option_group_new("params",
			"Primary Services/Characteristics arguments",
			"Show all Primary Services/Characteristics arguments",
			NULL, NULL);
	g_option_context_add_group(context, params_group);
	g_option_group_add_entries(params_group, primary_char_options);

	/* Characteristics value/descriptor read/write arguments */
	char_rw_group = g_option_group_new("char-read-write",
		"Characteristics Value/Descriptor Read/Write arguments",
		"Show all Characteristics Value/Descriptor Read/Write "
		"arguments",
		NULL, NULL);
	g_option_context_add_group(context, char_rw_group);
	g_option_group_add_entries(char_rw_group, char_rw_options);

	if (g_option_context_parse(context, &argc, &argv, &gerr) == FALSE) {
		g_printerr("%s\n", gerr->message);
		g_error_free(gerr);
	}

	if (opt_interactive) {
		interactive(opt_src, opt_dst, opt_psm);
		goto done;
	}

	if (opt_primary)
		callback = primary;
	else if (opt_characteristics)
		callback = characteristics;
	else if (opt_char_read)
		callback = characteristics_read;
	else if (opt_char_write)
		callback = characteristics_write;
	else if (opt_char_write_req)
		callback = characteristics_write_req;
	else if (opt_char_desc)
		callback = characteristics_desc;
	else {
		gchar *help = g_option_context_get_help(context, TRUE, NULL);
		g_print("%s\n", help);
		g_free(help);
		got_error = TRUE;
		goto done;
	}

	chan = gatt_connect(opt_src, opt_dst, opt_sec_level,
					opt_psm, opt_mtu, connect_cb);
	if (chan == NULL) {
		got_error = TRUE;
		goto done;
	}

	attrib = g_attrib_new(chan);
	g_io_channel_unref(chan);

	event_loop = g_main_loop_new(NULL, FALSE);

	if (opt_listen)
		g_idle_add(listen_start, attrib);

	g_idle_add(callback, attrib);

	g_main_loop_run(event_loop);

	g_attrib_unregister_all(attrib);

	g_main_loop_unref(event_loop);

	g_attrib_unref(attrib);

done:
	g_option_context_free(context);
	g_free(opt_src);
	g_free(opt_dst);
	g_free(opt_uuid);
	g_free(opt_sec_level);

	if (got_error)
		exit(EXIT_FAILURE);
	else
		exit(EXIT_SUCCESS);
}
static void
test_time_zones_sync (gconstpointer user_data)
{
	gboolean retval = FALSE;
	gint i;
	GError *error = NULL;
	UhmServer *local_server;
	EwsTestData *etd = (gpointer) user_data;
	EwsCalendarConvertData convert_data;
	EwsFolderId *calendar_fid;
	gboolean includes_last_folder = FALSE;
	gchar *old_sync_state = NULL;
	gchar **tokens;
	GSList *zone_location_errors = NULL;

	local_server = ews_test_get_mock_server ();

	ews_test_server_set_trace_directory (local_server, etd->version, "calendar/timezones");
	ews_test_server_start_trace (local_server, etd, "get_server_time_zones_sync", &error);
	if (error != NULL) {
		g_printerr ("\n%s\n", error->message);
		goto exit;
	}

	while (!includes_last_folder) {
		GSList *folders_created = NULL;
		GSList *folders_updated = NULL;
		GSList *folders_deleted = NULL;
		GSList *l;
		gchar *new_sync_state = NULL;
		gboolean found = FALSE;

		old_sync_state = new_sync_state;

		e_ews_connection_sync_folder_hierarchy_sync (
			etd->connection,
			EWS_PRIORITY_MEDIUM,
			old_sync_state,
			&new_sync_state,
			&includes_last_folder,
			&folders_created,
			&folders_updated,
			&folders_deleted,
			NULL,
			&error);

		if (error != NULL) {
			g_free (old_sync_state);
			g_printerr ("\n%s\n", error->message);
			goto exit;
		}

		for (l = folders_created; l != NULL; l = l->next) {
			EEwsFolder *folder = l->data;

			if (e_ews_folder_get_folder_type (folder) == E_EWS_FOLDER_TYPE_CALENDAR) {
				const EwsFolderId *fid;

				fid = e_ews_folder_get_id (folder);

				calendar_fid = g_new0 (EwsFolderId, 1);
				calendar_fid->id = g_strdup (fid->id);
				calendar_fid->change_key = g_strdup (fid->change_key);

				found = TRUE;
				break;
			}
		}

		g_slist_free_full (folders_created, g_object_unref);
		g_slist_free_full (folders_updated, g_object_unref);
		g_slist_free_full (folders_deleted, g_free);

		g_free (old_sync_state);
		old_sync_state = NULL;

		if (found) {
			g_free (new_sync_state);
			break;
		}
	}

	convert_data.connection = etd->connection;
	convert_data.default_zone = icaltimezone_get_utc_timezone ();

	tokens = g_strsplit (str_comp, "ICAL_TIMEZONE", 0);

	for (i = 0; i < builtin_timezones->num_elements; i++) {
		GSList *ll;
		GSList *ids = NULL;
		icaltimezone *zone;
		ECalComponent *comp;
		const gchar *zone_location;
		gchar *str;

		zone = icalarray_element_at (builtin_timezones, i);
		zone_location = icaltimezone_get_location (zone);

		if (is_a_known_unknown_timezone (zone_location))
			continue;

		str = g_strdup_printf ("%s%s%s%s%s", tokens[0], zone_location, tokens[1], zone_location, tokens[2]);
		comp = e_cal_component_new_from_string (str);
		g_free (str);

		convert_data.icalcomp = e_cal_component_get_icalcomponent (comp);

		e_ews_connection_create_items_sync (
			etd->connection,
			EWS_PRIORITY_MEDIUM,
			"SaveOnly",
			"SendToNone",
			calendar_fid,
			convert_calcomp_to_xml,
			&convert_data,
			&ids,
			NULL,
			&error);

		g_object_unref (comp);

		if (error != NULL) {
			g_printerr ("\n%s\n", error->message);
			g_clear_error (&error);

			zone_location_errors = g_slist_append (zone_location_errors, g_strdup (zone_location));
			continue;
		}

		for (ll = ids; ll != NULL; ll = ll->next) {
			EEwsItem *item = ll->data;

			if (e_ews_item_get_item_type (item) == E_EWS_ITEM_TYPE_ERROR) {
				const GError *item_error = e_ews_item_get_error (item);
				g_printerr ("\n%s\n", item_error->message);
				g_clear_error (&error);

				zone_location_errors = g_slist_append (zone_location_errors, g_strdup (zone_location));
				continue;
			}
		}

		g_slist_free_full (ids, g_object_unref);
	}

	retval = zone_location_errors == NULL;

 exit:
	if (zone_location_errors != NULL) {
		GSList *l;

		g_printerr ("Errors found in: \n");
		for (l = zone_location_errors; l != NULL; l = l->next)
			g_printerr (" - %s\n", (gchar *) l->data);

		g_slist_free_full (zone_location_errors, g_free);
	}

	uhm_server_end_trace (local_server);
	g_clear_error (&error);

	g_assert (retval == TRUE);
}
Esempio n. 5
0
static void
error_fn(png_structp png_ptr, png_const_charp msg)
{
  g_printerr("LIBPNG ERROR: %s", msg);
}
int main (int argc, char **argv)
{
    GtkWidget *dialog;
    XfpmUnique *unique;

    GError *error = NULL;
    DBusGConnection *bus;
    GHashTable *config_hash;
    
    gboolean has_battery;
    gboolean auth_suspend;
    gboolean auth_hibernate;
    gboolean can_suspend;
    gboolean can_hibernate;
    gboolean can_shutdown;
    gboolean has_lcd_brightness;
    gboolean has_sleep_button;
    gboolean has_hibernate_button;
    gboolean has_power_button;
    gboolean has_lid;
    gboolean start_xfpm_if_not_running;
    gboolean debug = FALSE;

    GdkNativeWindow socket_id = 0;
    gchar *device_id = NULL;

    XfconfChannel *channel;
    DBusGProxy *proxy;
    
    GOptionEntry option_entries[] = 
    {
	{ "socket-id", 's', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_INT, &socket_id, N_("Settings manager socket"), N_("SOCKET ID") },
	{ "device-id", 'd', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_STRING, &device_id, N_("Display a specific device by UpDevice object path"), N_("UpDevice object path") },
	{ "debug",    '\0', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, &debug, N_("Enable debugging"), NULL },
	{ NULL, },
    };

    xfce_textdomain(GETTEXT_PACKAGE, LOCALEDIR, "UTF-8");
    
    if( !gtk_init_with_args (&argc, &argv, (gchar *)"", option_entries, (gchar *)PACKAGE, &error)) 
    {
        if( error) 
        {
            g_printerr("%s: %s.\n", G_LOG_DOMAIN, error->message);
            g_printerr(_("Type '%s --help' for usage."), G_LOG_DOMAIN);
            g_printerr("\n");
            g_error_free(error);
        }
        else
        {
            g_error("Unable to open display.");
	}
        return EXIT_FAILURE;
    }
    
    bus = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
    
    if ( error )
    {
	g_error ("%s\n",error->message);
    }

    while ( !xfpm_dbus_name_has_owner (dbus_g_connection_get_connection(bus), "org.xfce.PowerManager") )
    {
	g_print(_("Xfce power manager is not running"));
	g_print("\n");
	start_xfpm_if_not_running =
	    xfce_dialog_confirm (NULL, 
				 GTK_STOCK_EXECUTE,
				 _("Run"), NULL,
				 _("Xfce4 Power Manager is not running, do you want to launch it now?"));

	if ( start_xfpm_if_not_running ) 
	{
	    g_spawn_command_line_async("xfce4-power-manager",NULL);
	    /* wait 2 seconds for xfpm to startup */
	    g_usleep ( 2 * 1000000 );
	}
	else
	{
	    /* continue without starting xfpm, this will probably error out */
	    break;
	}
    }

    unique = xfpm_unique_new ("org.xfce.PowerManager.Config");

    if ( !xfpm_unique_app_is_running (unique) )
    {
	if ( !xfconf_init(&error) )
	{
	    g_critical("xfconf init failed: %s using default settings\n", error->message);
	    xfce_dialog_show_warning (NULL,
				      _("Xfce Power Manager"),
				      "%s",
				      _("Failed to load power manager configuration, using defaults"));
	    g_error_free (error);
	    error = NULL;
	    return EXIT_FAILURE;
	}

#if !GLIB_CHECK_VERSION (2, 32, 0)
    if ( !g_thread_supported () )
        g_thread_init (NULL);
#endif

	dbus_g_thread_init ();

	channel = xfconf_channel_new(XFPM_CHANNEL_CFG);

	proxy = dbus_g_proxy_new_for_name(bus,
					   "org.xfce.PowerManager",
					   "/org/xfce/PowerManager",
					   "org.xfce.Power.Manager");

	xfpm_manager_dbus_client_get_config (proxy,
					     &config_hash,
					     &error);

	if ( error )
	{
	    g_critical ("Unable to get configuration information from xfce power manager: %s", error->message);
	    xfce_dialog_show_error (NULL, error, "%s", _("Unable to connect to Xfce Power Manager"));
	    g_error_free (error);
	    return EXIT_FAILURE;
	}

	xfpm_debug_init (debug);

	has_battery = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "has-battery"));
	has_lid = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "has-lid"));
	can_suspend = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "can-suspend"));
	can_hibernate = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "can-hibernate"));
	auth_suspend = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "auth-suspend"));
	auth_hibernate = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "auth-hibernate"));
	has_lcd_brightness = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "has-brightness"));
	has_sleep_button = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "sleep-button"));
	has_power_button = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "power-button"));
	has_hibernate_button = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "hibernate-button"));
	can_shutdown = xfpm_string_to_bool (g_hash_table_lookup (config_hash, "can-shutdown"));

	g_hash_table_destroy (config_hash);

	dialog = xfpm_settings_dialog_new (channel, auth_suspend, auth_hibernate,
					   can_suspend, can_hibernate, can_shutdown, has_battery, has_lcd_brightness,
					   has_lid, has_sleep_button, has_hibernate_button, has_power_button,
					   socket_id, device_id);

	g_signal_connect_swapped (unique, "ping-received",
				  G_CALLBACK (gtk_window_present), dialog);

	gtk_main();

	xfpm_dbus_release_name(dbus_g_connection_get_connection(bus), "org.xfce.PowerManager.Config");
	dbus_g_connection_unref (bus);
	g_object_unref (proxy);

	g_object_unref (unique);

	return EXIT_SUCCESS;
    }
    
    return EXIT_SUCCESS;
}
Esempio n. 7
0
gboolean
ostree_builtin_admin (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  gboolean ret = FALSE;
  const char *subcommand_name = NULL;
  OstreeAdminCommand *subcommand;
  gs_free char *prgname = NULL;
  int in, out;

  /*
   * Parse the global options. We rearrange the options as
   * necessary, in order to pass relevant options through
   * to the commands, but also have them take effect globally.
   */

  for (in = 1, out = 1; in < argc; in++, out++)
    {
      /* The non-option is the command, take it out of the arguments */
      if (argv[in][0] != '-')
        {
          if (subcommand_name == NULL)
            {
              subcommand_name = argv[in];
              out--;
              continue;
            }
        }

      else if (g_str_equal (argv[in], "--"))
        {
          break;
        }

      argv[out] = argv[in];
    }

  argc = out;

  subcommand = admin_subcommands;
  while (subcommand->name)
    {
      if (g_strcmp0 (subcommand_name, subcommand->name) == 0)
        break;
      subcommand++;
    }

  if (!subcommand->name)
    {
      GOptionContext *context;
      gs_free char *help;

      context = ostree_admin_option_context_new_with_commands ();

      /* This will not return for some options (e.g. --version). */
      if (ostree_admin_option_context_parse (context, NULL, &argc, &argv, NULL, cancellable, error))
        {
          if (subcommand_name == NULL)
            {
              g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "No \"admin\" subcommand specified");
            }
          else
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
                           "Unknown \"admin\" subcommand '%s'", subcommand_name);
            }
        }

      help = g_option_context_get_help (context, FALSE, NULL);
      g_printerr ("%s", help);

      g_option_context_free (context);

      goto out;
    }

  prgname = g_strdup_printf ("%s %s", g_get_prgname (), subcommand_name);
  g_set_prgname (prgname);

  if (!subcommand->fn (argc, argv, cancellable, error))
    goto out;
 
  ret = TRUE;
 out:
  return ret;
}
Esempio n. 8
0
static gboolean
handle_dir (const gchar *dirname,
            time_t       stored_mtime,
            GHashTable  *converted)
{
  time_t dir_mtime;
  struct stat statbuf;
  GDir *dir;
  const gchar *name;
  gchar *filename;
  GError *error;

  /* If the directory is not newer, exit */
  if (stat (dirname, &statbuf) == 0)
    dir_mtime = statbuf.st_mtime;
 else
    {
      if (verbose)
        g_print ("Directory '%s' does not exist, nothing to do\n", dirname);
      return TRUE;
    }

  if (dir_mtime <= stored_mtime)
    {
      if (verbose)
        g_print ("Directory '%s' all uptodate, nothing to do\n", dirname);
      return TRUE;
    }

  error = NULL;
  dir = g_dir_open (dirname, 0, &error);
  if (dir == NULL)
    {
      g_printerr ("Failed to open '%s': %s\n", dirname, error->message);
      return FALSE;
    }

  while ((name = g_dir_read_name (dir)) != NULL)
    {
      if (g_hash_table_lookup (converted, name))
        {
          if (verbose)
            g_print ("File '%s already converted, skipping\n", name);
          goto next;
        }

      filename = g_build_filename (dirname, name, NULL);

      if (handle_file (filename))
        {
          gchar *myname = g_strdup (name);

          /* Add the the file to the converted list */
          g_hash_table_insert (converted, myname, myname);
          changed = TRUE;
        }

      g_free (filename);

 next: ;
    }

  return TRUE;
}
Esempio n. 9
0
int
main (int argc, char *argv[])
{
  time_t stored_mtime;
  const gchar * const *data_dirs;
  gint i;
  GError *error;
  GHashTable *converted;
  GOptionContext *context;
  const gchar *extra_file = NULL;
  GOptionEntry entries[] = {
    { "verbose", 0, 0, G_OPTION_ARG_NONE, &verbose, "show verbose messages", NULL },
    { "dry-run", 0, 0, G_OPTION_ARG_NONE, &dry_run, "do not perform any changes", NULL },
    { "file", 0, 0, G_OPTION_ARG_STRING, &extra_file, "perform conversions from an extra file", NULL },
    { NULL }
  };

  g_type_init();

  context = g_option_context_new ("");

  g_option_context_set_summary (context,
    "Migrate settings from the users GConf database to GSettings.");

  g_option_context_add_main_entries (context, entries, NULL);

  error = NULL;
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s\n", error->message);
      return 1;
    }

  converted = load_state (&stored_mtime);

  if (extra_file)
    {
      gchar *base;

      base = g_path_get_basename (extra_file);

      if (g_hash_table_lookup (converted, base))
        {
          if (verbose)
            g_print ("'%s' is already converted.  Skipping.\n", base);
        }
      else
        {
          if (handle_file (extra_file))
            {
              gchar *myname = g_strdup (base);

              g_hash_table_insert (converted, myname, myname);
              changed = TRUE;
            }
        }

      g_free (base);
    }

  data_dirs = g_get_system_data_dirs ();
  for (i = 0; data_dirs[i]; i++)
    {
      gchar *convert_dir;

      convert_dir = g_build_filename (data_dirs[i], "GConf", "gsettings", NULL);

      if (!handle_dir (convert_dir, stored_mtime, converted))
        return 1;

      g_free (convert_dir);
    }

  if (changed && !dry_run)
    {
      if (!save_state (converted))
        return 1;
    }

  return 0;
}
Esempio n. 10
0
int
main (int argc, char **argv)
{
	int i;
	char **argv_copy;
	int argc_copy;
	const char *startup_id, *display_name, *home_dir;
	GdkDisplay *display;
	TerminalOptions *options;
	GError *error = NULL;
	char *working_directory;
	int ret = EXIT_SUCCESS;

	setlocale (LC_ALL, "");

	bindtextdomain (GETTEXT_PACKAGE, TERM_LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

	_terminal_debug_init ();

	/* Make a NULL-terminated copy since we may need it later */
	argv_copy = g_new (char *, argc + 1);
	for (i = 0; i < argc; ++i)
		argv_copy [i] = argv [i];
	argv_copy [i] = NULL;
	argc_copy = argc;

	startup_id = g_getenv ("DESKTOP_STARTUP_ID");

	working_directory = g_get_current_dir ();

	gdk_set_allowed_backends ("x11");

	/* Now change directory to $HOME so we don't prevent unmounting, e.g. if the
	 * factory is started by caja-open-terminal. See bug #565328.
	 * On failure back to /.
	 */
	home_dir = g_get_home_dir ();
	if (home_dir == NULL || chdir (home_dir) < 0)
		(void) chdir ("/");

	options = terminal_options_parse (working_directory,
	                                  NULL,
	                                  startup_id,
	                                  NULL,
	                                  FALSE,
	                                  FALSE,
	                                  &argc, &argv,
	                                  &error,
	                                  gtk_get_option_group (TRUE),
	                                  egg_sm_client_get_option_group (),
	                                  NULL);

	g_free (working_directory);

	if (options == NULL)
	{
		g_printerr (_("Failed to parse arguments: %s\n"), error->message);
		g_error_free (error);
		exit (EXIT_FAILURE);
	}

	g_set_application_name (_("Terminal"));

	/* Unset the these env variables, so they doesn't end up
	 * in the factory's env and thus in the terminals' envs.
	 */
	g_unsetenv ("DESKTOP_STARTUP_ID");
	g_unsetenv ("GIO_LAUNCHED_DESKTOP_FILE_PID");
	g_unsetenv ("GIO_LAUNCHED_DESKTOP_FILE");

	display = gdk_display_get_default ();
	display_name = gdk_display_get_name (display);
	options->display_name = g_strdup (display_name);

	if (options->startup_id == NULL)
	{
		/* Create a fake one containing a timestamp that we can use */
		Time timestamp;

		timestamp = slowly_and_stupidly_obtain_timestamp (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()));

		options->startup_id = g_strdup_printf ("_TIME%lu", timestamp);
	}

	if (options->use_factory)
	{
		OwnData *data;
		guint owner_id;

		data = g_new (OwnData, 1);
		data->factory_name = get_factory_name_for_display (display_name);
		data->options = options;
		data->exit_code = -1;
		data->argv = argv_copy;
		data->argc = argc_copy;

		gtk_init(&argc, &argv);
		options->initial_workspace = get_initial_workspace ();

		owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
		                           data->factory_name,
		                           G_BUS_NAME_OWNER_FLAGS_NONE,
		                           bus_acquired_cb,
		                           name_acquired_cb,
		                           name_lost_cb,
		                           data, NULL);

		gtk_main ();

		ret = data->exit_code;
		g_bus_unown_name (owner_id);

		g_free (data->factory_name);
		g_free (data);

	}
	else
	{

		terminal_app_handle_options (terminal_app_get (), options, TRUE /* allow resume */, &error);
		terminal_options_free (options);

		if (error == NULL)
		{
			gtk_main ();
		}
		else
		{
			g_printerr ("Error handling options: %s\n", error->message);
			g_error_free (error);
			ret = EXIT_FAILURE;
		}
	}

	terminal_app_shutdown ();

	g_free (argv_copy);

	return ret;
}
Esempio n. 11
0
static gboolean
handle_file (const gchar *filename)
{
  GKeyFile *keyfile;
  GConfClient *client;
  GConfValue *value;
  gint i, j;
  gchar *gconf_key;
  gchar **groups;
  gchar **keys;
  GVariantBuilder *builder;
  GVariant *v;
  const gchar *s;
  gchar *str;
  gint ii;
  GSList *list, *l;
  GSettingsSchemaSource *source;
  GSettingsSchema *schema;
  GSettings *settings;
  GError *error;

  keyfile = g_key_file_new ();

  error = NULL;
  if (!g_key_file_load_from_file (keyfile, filename, 0, &error))
    {
      if (verbose)
        g_printerr ("%s: %s\n", filename, error->message);
      g_error_free (error);

      g_key_file_free (keyfile);

      return FALSE;
    }

  client = get_writable_client ();
  source = g_settings_schema_source_get_default ();

  groups = g_key_file_get_groups (keyfile, NULL);
  for (i = 0; groups[i]; i++)
    {
      gchar **schema_path;

      schema_path = g_strsplit (groups[i], ":", 2);

      schema = g_settings_schema_source_lookup (source, schema_path[0], TRUE);
      if (schema == NULL)
        {
          if (verbose)
            {
              g_print ("Schema '%s' not found, skipping\n", schema_path[0]);
            }

          g_strfreev (schema_path);
          continue;
        }

      g_settings_schema_unref (schema);

      if (verbose)
        {
          g_print ("Collecting settings for schema '%s'\n", schema_path[0]);
          if (schema_path[1])
            g_print ("for storage at '%s'\n", schema_path[1]);
        }

      if (schema_path[1] != NULL)
        settings = g_settings_new_with_path (schema_path[0], schema_path[1]);
      else
        settings = g_settings_new (schema_path[0]);

      g_settings_delay (settings);

      error = NULL;
      if ((keys = g_key_file_get_keys (keyfile, groups[i], NULL, &error)) == NULL)
        {
          g_printerr ("%s", error->message);
          g_error_free (error);

          continue;
        }

      for (j = 0; keys[j]; j++)
        {
          if (strchr (keys[j], '/') != 0)
            {
              g_printerr ("Key '%s' contains a '/'\n", keys[j]);

              continue;
            }

          error = NULL;
          if ((gconf_key = g_key_file_get_string (keyfile, groups[i], keys[j], &error)) ==  NULL)
            {
              g_printerr ("%s", error->message);
              g_error_free (error);

              continue;
            }

          error = NULL;
          if ((value = gconf_client_get_without_default (client, gconf_key, &error)) == NULL)
            {
              if (error)
                {
                  g_printerr ("Failed to get GConf key '%s': %s\n",
                              gconf_key, error->message);
                  g_error_free (error);
                }
              else
                {
                  if (verbose)
                    g_print ("Skipping GConf key '%s', no user value\n",
                             gconf_key);
                }

              g_free (gconf_key);

              continue;
            }

          switch (value->type)
            {
            case GCONF_VALUE_STRING:
              if (dry_run)
                g_print ("Set key '%s' to string '%s'\n", keys[j],
                         gconf_value_get_string (value));
              else
                g_settings_set (settings, keys[j], "s",
                                gconf_value_get_string (value));
              break;

            case GCONF_VALUE_INT:
              if (dry_run)
                g_print ("Set key '%s' to integer '%d'\n",
                         keys[j], gconf_value_get_int (value));
              else
                {
                  GVariant *range;
                  gchar *type;

                  range = g_settings_get_range (settings, keys[j]);
                  g_variant_get (range, "(&sv)", &type, NULL);

                  if (strcmp (type, "enum") == 0)
                    g_settings_set_enum (settings, keys[j], gconf_value_get_int (value));
                  else if (strcmp (type, "flags") == 0)
                    g_settings_set_flags (settings, keys[j], gconf_value_get_int (value));
                  else if (type_uint32 (settings, keys[j]))
                    g_settings_set (settings, keys[j], "u",
                                    gconf_value_get_int (value));
                  else
                    g_settings_set (settings, keys[j], "i",
                                    gconf_value_get_int (value));

                  g_variant_unref (range);
                }
              break;

            case GCONF_VALUE_BOOL:
              if (dry_run)
                g_print ("Set key '%s' to boolean '%d'\n",
                         keys[j], gconf_value_get_bool (value));
              else
                g_settings_set (settings, keys[j], "b",
                                gconf_value_get_bool (value));
              break;

            case GCONF_VALUE_FLOAT:
              if (dry_run)
                g_print ("Set key '%s' to double '%g'\n",
                         keys[j], gconf_value_get_float (value));
              else
                g_settings_set (settings, keys[j], "d",
                                gconf_value_get_float (value));
              break;

            case GCONF_VALUE_LIST:
              switch (gconf_value_get_list_type (value))
                {
                case GCONF_VALUE_STRING:
                  builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
                  list = gconf_value_get_list (value);
                  if (list != NULL)
                    {
                      for (l = list; l; l = l->next)
                        {
                          GConfValue *lv = l->data;
                          s = gconf_value_get_string (lv);
                          g_variant_builder_add (builder, "s", s);
                        }
                      v = g_variant_new ("as", builder);
                    }
                  else
                    v = g_variant_new_array (G_VARIANT_TYPE_STRING, NULL, 0);
                  g_variant_ref_sink (v);

                  if (dry_run)
                    {
                      str = g_variant_print (v, FALSE);
                      g_print ("Set key '%s' to a list of strings: %s\n",
                               keys[j], str);
                      g_free (str);
                    }
                  else
                    g_settings_set_value (settings, keys[j], v);

                  g_variant_unref (v);
                  g_variant_builder_unref (builder);
                  break;

                case GCONF_VALUE_INT:
                  builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
                  list = gconf_value_get_list (value);
                  if (list != NULL)
                    {
                      for (l = list; l; l = l->next)
                        {
                          GConfValue *lv = l->data;
                          ii = gconf_value_get_int (lv);
                          g_variant_builder_add (builder, "i", ii);
                        }
                      v = g_variant_new ("ai", builder);
                    }
                  else
                    v = g_variant_new_array (G_VARIANT_TYPE_INT32, NULL, 0);
                  g_variant_ref_sink (v);

                  if (dry_run)
                    {
                      str = g_variant_print (v, FALSE);
                      g_print ("Set key '%s' to a list of integers: %s\n",
                               keys[j], str);
                      g_free (str);
                    }
                  else
                    g_settings_set_value (settings, keys[j], v);

                  g_variant_unref (v);
                  g_variant_builder_unref (builder);
                  break;

                default:
                  g_printerr ("Keys of type 'list of %s' not handled yet\n",
                              gconf_value_type_to_string (gconf_value_get_list_type (value)));
                  break;
                }
              break;

            default:
              g_printerr ("Keys of type %s not handled yet\n",
                          gconf_value_type_to_string (value->type));
              break;
            }

          gconf_value_free (value);
          g_free (gconf_key);
        }

      g_strfreev (keys);

      if (!dry_run)
        g_settings_apply (settings);

      g_object_unref (settings);
      g_strfreev (schema_path);
    }

  g_strfreev (groups);

  g_object_unref (client);

  return TRUE;
}
Esempio n. 12
0
static void
name_lost_cb (GDBusConnection *connection,
              const char *name,
              gpointer user_data)
{
	OwnData *data = (OwnData *) user_data;
	GError *error = NULL;
	char **envv;
	int i;
	GVariantBuilder builder;
	GVariant *value;
	GString *string;
	char *s;
	gsize len;

	_terminal_debug_print (TERMINAL_DEBUG_FACTORY,
	                       "Lost the name %s on the session bus\n", name);

	/* Couldn't get the connection? No way to continue! */
	if (connection == NULL)
	{
		data->exit_code = EXIT_FAILURE;
		gtk_main_quit ();
		return;
	}

	if (data->options == NULL)
	{
		/* Already handled */
		data->exit_code = EXIT_SUCCESS;
		gtk_main_quit ();
		return;
	}

	_terminal_debug_print (TERMINAL_DEBUG_FACTORY,
	                       "Forwarding arguments to existing instance\n");

    g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ayayayayiay)"));
    
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->default_working_dir));
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->display_name));
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->startup_id));

	string = g_string_new (NULL);
	envv = g_get_environ ();
	for (i = 0; envv[i]; ++i)
	{
		if (i > 0)
			g_string_append_c (string, '\0');

		g_string_append (string, envv[i]);
	}
	g_strfreev (envv);

	len = string->len;
	s = g_string_free (string, FALSE);
	g_variant_builder_add (&builder, "@ay",
	                       g_variant_new_from_data (G_VARIANT_TYPE ("ay"), s, len, TRUE, g_free, s));

    g_variant_builder_add (&builder, "@i", g_variant_new_int32 (data->options->initial_workspace));

	string = g_string_new (NULL);

	for (i = 0; i < data->argc; ++i)
	{
		if (i > 0)
			g_string_append_c (string, '\0');
		g_string_append (string, data->argv[i]);
	}

	len = string->len;
	s = g_string_free (string, FALSE);
	g_variant_builder_add (&builder, "@ay",
	                       g_variant_new_from_data (G_VARIANT_TYPE ("ay"), s, len, TRUE, g_free, s));

	value = g_dbus_connection_call_sync (connection,
	                                     data->factory_name,
	                                     TERMINAL_FACTORY_SERVICE_PATH,
	                                     TERMINAL_FACTORY_INTERFACE_NAME,
	                                     "HandleArguments",
	                                     g_variant_builder_end (&builder),
	                                     G_VARIANT_TYPE ("()"),
	                                     G_DBUS_CALL_FLAGS_NONE,
	                                     -1,
	                                     NULL,
	                                     &error);
	if (value == NULL)
	{
		g_printerr ("Failed to forward arguments: %s\n", error->message);
		g_error_free (error);
		data->exit_code = EXIT_FAILURE;
		gtk_main_quit ();
	}
	else
	{
		g_variant_unref (value);
		data->exit_code = EXIT_SUCCESS;
	}

	terminal_options_free (data->options);
	data->options = NULL;

	gtk_main_quit ();
}
Esempio n. 13
0
int
main (int argc, char *argv[])
{
  GOptionContext *context;
  GError         *error;
  GFile          *file;
  GFile          *new_file;
  int             retval = 0;
  gchar          *param;
  gchar          *summary;

  setlocale (LC_ALL, "");

  bindtextdomain (GETTEXT_PACKAGE, GVFS_LOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);

  error = NULL;
  param = g_strdup_printf ("%s %s", _("LOCATION"), _("NEW-NAME"));
  summary = _("Rename a file.");

  context = g_option_context_new (param);
  g_option_context_set_summary (context, summary);
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  g_option_context_parse (context, &argc, &argv, &error);

  if (error != NULL)
    {
      g_printerr (_("Error parsing commandline options: %s\n"), error->message);
      g_printerr ("\n");
      g_printerr (_("Try \"%s --help\" for more information."), g_get_prgname ());
      g_printerr ("\n");
      g_error_free (error);
      return 1;
    }

  if (show_version)
    {
      g_print (PACKAGE_STRING "\n");
      return 0;
    }

  if (argc < 3)
    {
      show_help (context, _("Missing operand\n"));
      return 1;
    }

  g_option_context_free (context);
  g_free (param);

  file = g_file_new_for_commandline_arg (argv[1]);

  new_file = g_file_set_display_name (file, argv[2],
				      NULL, &error);

  if (new_file == NULL)
    {
      g_printerr (_("Error: %s\n"), error->message);
      g_error_free (error);
      retval = 1;
    }
  else
    {
      char *uri = g_file_get_uri (new_file);
      g_print (_("Rename successful. New uri: %s\n"), uri);
      g_object_unref (new_file);
      g_free (uri);
    }

  g_object_unref (file);
  return retval;
}
static void
gb_view_source_save (GbView *view)
{
    GbViewSourcePrivate *priv;
    GFileOutputStream *stream;
    GtkTextBuffer *buffer;
    GbViewSource *source = (GbViewSource *)view;
    GCancellable *cancellable = NULL;
    GtkTextIter iter1;
    GtkTextIter iter2;
    const gchar *etag = NULL;
    GtkWidget *widget;
    gboolean make_backup = FALSE;
    GError *error = NULL;
    gchar *text;
    gsize n_written;

    ENTRY;

    g_return_if_fail(GB_IS_VIEW_SOURCE(source));

    priv = source->priv;

    if (!priv->file) {
        GtkDialog *dialog;

        widget = gtk_widget_get_toplevel(GTK_WIDGET(view));
        dialog = g_object_new(GTK_TYPE_FILE_CHOOSER_DIALOG,
                              "action", GTK_FILE_CHOOSER_ACTION_SAVE,
                              "title", _("Save File"),
                              "transient-for", widget,
                              NULL);
        gtk_dialog_add_buttons(dialog,
                               GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                               GTK_STOCK_SAVE, GTK_RESPONSE_OK,
                               NULL);
        if (gtk_dialog_run(dialog) != GTK_RESPONSE_OK) {
            gtk_widget_destroy(GTK_WIDGET(dialog));
            EXIT;
        }
        priv->file = gtk_file_chooser_get_file(GTK_FILE_CHOOSER(dialog));
        gtk_widget_destroy(GTK_WIDGET(dialog));
    }

    g_signal_emit(source, gSignals[PRE_SAVE], 0);

    g_object_set(priv->progress,
                 "fraction", 0.0,
                 "visible", TRUE,
                 NULL);
    gb_object_animate_full(priv->progress,
                           GB_ANIMATION_EASE_IN_OUT_QUAD,
                           500,
                           60,
                           save_animation_done,
                           g_object_ref(priv->progress),
                           "fraction", 1.0,
                           NULL);

    buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(priv->source1));

    /*
     * TODO: Do this all async.
     */

    if (!(stream = g_file_replace(priv->file, etag, make_backup,
                                  G_FILE_CREATE_NONE,
                                  cancellable, &error))) {
        g_printerr("%s\n", error->message);
        g_error_free(error);
        EXIT;
    }

    gtk_text_buffer_get_start_iter(buffer, &iter1);
    gtk_text_buffer_get_end_iter(buffer, &iter2);
    text = gtk_text_buffer_get_text(buffer, &iter1, &iter2, TRUE);

    if (!g_output_stream_write_all(G_OUTPUT_STREAM(stream), text, strlen(text),
                                   &n_written, cancellable, &error)) {
        g_printerr("%s\n", error->message);
        g_error_free(error);
    } else {
        g_output_stream_flush(G_OUTPUT_STREAM(stream), NULL, NULL);
        if (!g_output_stream_close(G_OUTPUT_STREAM(stream), cancellable,
                                   &error)) {
            g_printerr("%s\n", error->message);
            g_error_free(error);
        } else {
            gb_view_set_can_save(view, FALSE);
        }
    }

    gtk_text_buffer_set_modified(buffer, FALSE);

    g_object_unref(stream);
    g_free(text);

    gb_view_source_set_file_attribs(source, priv->file);

    EXIT;
}
Esempio n. 15
0
gint main_runShadow(gint argc, gchar* argv[]) {
    /* check the compiled GLib version */
    if (!GLIB_CHECK_VERSION(2, 32, 0)) {
        g_printerr("** GLib version 2.32.0 or above is required but Shadow was compiled against version %u.%u.%u\n",
            (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION);
        return EXIT_FAILURE;
    }

    if(GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION == 40) {
        g_printerr("** You compiled against GLib version %u.%u.%u, which has bugs known to break Shadow. Please update to a newer version of GLib.\n",
                    (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION);
        return EXIT_FAILURE;
    }

    /* check the that run-time GLib matches the compiled version */
    const gchar* mismatch = glib_check_version(GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
    if(mismatch) {
        g_printerr("** The version of the run-time GLib library (%u.%u.%u) is not compatible with the version against which Shadow was compiled (%u.%u.%u). GLib message: '%s'\n",
        glib_major_version, glib_minor_version, glib_micro_version,
        (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION,
        mismatch);
        return EXIT_FAILURE;
    }

    /* parse the options from the command line */
    gchar* cmds = g_strjoinv(" ", argv);
    gchar** cmdv = g_strsplit(cmds, " ", 0);
    g_free(cmds);
    Options* options = options_new(argc, cmdv);
    g_strfreev(cmdv);
    if(!options) {
        return EXIT_FAILURE;
    }

    /* if they just want the shadow version, print it and exit */
    if(options_doRunPrintVersion(options)) {
        g_printerr("%s running GLib v%u.%u.%u and IGraph v%s\n%s\n",
                SHADOW_VERSION_STRING,
                (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION,
#if defined(IGRAPH_VERSION)
                IGRAPH_VERSION,
#else
                "(n/a)",
#endif
                SHADOW_INFO_STRING);
        options_free(options);
        return EXIT_SUCCESS;
    }

    /* start up the logging subsystem to handle all future messages */
    Logger* shadowLogger = logger_new(options_getLogLevel(options));
    logger_setDefault(shadowLogger);

    /* disable buffering during startup so that we see every message immediately in the terminal */
    logger_setEnableBuffering(shadowLogger, FALSE);

    gint returnCode = _main_helper(options);

    options_free(options);
    Logger* logger = logger_getDefault();
    if(logger) {
        logger_setDefault(NULL);
        logger_unref(logger);
    }

    g_printerr("** Stopping Shadow, returning code %i (%s)\n", returnCode, (returnCode == 0) ? "success" : "error");
    return returnCode;
}
Esempio n. 16
0
void handle_error(const char* msg, const char* reason, gboolean fatal) {
    g_printerr("ERROR: %s (%s)\n", msg, reason);
    if (fatal)
        exit(EXIT_FAILURE);
}
Esempio n. 17
0
gint
main (gint argc, gchar **argv)
{
        GtkApplication *application;
        GApplicationFlags flags;
        gchar *path;
        GError *error = NULL;

        bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
        bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
        textdomain (GETTEXT_PACKAGE);

        gtk_init_with_args (
                &argc, &argv, NULL, entries, GETTEXT_PACKAGE, &error);
        if (error != NULL)
                g_error ("%s", error->message);

        /* This installs handlers for our custom debug log levels. */
        gva_get_debug_flags ();

        /* Change the working directory to that of the MAME executable.
         * Why?  Because SDLMAME's default configuration uses relative
         * search paths such as "rompath = roms".  The paths are relative
         * to the directory containing the MAME executable, so we must run
         * from that directory in order for SDLMAME's default configuration
         * to work.  Annoying, but a common problem for users. */
        path = g_path_get_dirname (MAME_PROGRAM);
        g_chdir (path);
        g_free (path);

        if (opt_inspect != NULL)
        {
                gchar *value;

                value = gva_mame_get_config_value (opt_inspect, &error);
                if (value != NULL)
                {
                        g_print ("%s\n", value);
                        g_free (value);
                }
                else
                {
                        g_printerr ("%s\n", error->message);
                        g_clear_error (&error);
                }
                exit (EXIT_SUCCESS);
        }

        if (opt_version)
        {
                g_print ("%s\n", PACKAGE_STRING);
                exit (EXIT_SUCCESS);
        }

        if (opt_which_emulator)
        {
                g_print ("%s\n", MAME_PROGRAM);
                exit (EXIT_SUCCESS);
        }

        /* Register the application with the session bus. */
        flags = G_APPLICATION_FLAGS_NONE;
        application = gtk_application_new (APPLICATION_ID, flags);
        g_application_register (G_APPLICATION (application), NULL, &error);

        if (error != NULL)
                g_error ("%s", error->message);

        /* If another instance is running, exit now. */
        if (g_application_get_is_remote (G_APPLICATION (application)))
        {
                gint exit_status;

                if (opt_build_database)
                {
                        g_printerr (
                                "Cannot build database: "
                                PACKAGE_NAME " is already running\n");
                        exit_status = EXIT_FAILURE;
                }
                else
                {
                        g_application_activate (G_APPLICATION (application));
                        exit_status = EXIT_SUCCESS;
                }

                g_object_unref (application);

                exit (exit_status);
        }
        else
        {
                GtkWindow *window;

                window = GTK_WINDOW (GVA_WIDGET_MAIN_WINDOW);
                gtk_application_add_window (application, window);
        }

        gtk_window_set_default_icon_name (PACKAGE);

        if (!gva_db_init (&error))
                g_error ("%s", error->message);

        gva_main_init ();
        gva_play_back_init ();
        gva_preferences_init ();
        gva_properties_init ();
        gva_ui_init ();

        gva_categories_init (&error);
        gva_error_handle (&error);

        gva_history_init (&error);
        gva_error_handle (&error);

        gva_nplayers_init (&error);
        gva_error_handle (&error);

        g_idle_add (idle_start, NULL);

        g_idle_add (tweak_css, NULL);

        gtk_main ();

        g_object_unref (application);

        return EXIT_SUCCESS;
}
Esempio n. 18
0
/* Fork a shell into the VTE Terminal
 *
 * @param tt the tilda_term to fork into
 *
 * SUCCESS: return 0
 * FAILURE: return non-zero
 */
static gint start_shell (struct tilda_term_ *tt)
{
    DEBUG_FUNCTION ("start_shell");
    DEBUG_ASSERT (tt != NULL);

    gint ret;
    gint argc;
    gchar **argv;
    GError *error = NULL;

    gchar *default_command;

    if (config_getbool ("run_command"))
    {
        ret = g_shell_parse_argv (config_getstr ("command"), &argc, &argv, &error);

        /* Check for error */
        if (ret == FALSE)
        {
            g_printerr (_("Problem parsing custom command: %s\n"), error->message);
            g_printerr (_("Launching default shell instead\n"));

            g_error_free (error);
            goto launch_default_shell;
        }

        char **envv = malloc(2*sizeof(void *));
        envv[0] = getenv("PATH");
        envv[1] = NULL;

        ret = vte_terminal_fork_command_full (VTE_TERMINAL (tt->vte_term),
            VTE_PTY_DEFAULT, /* VtePtyFlags pty_flags */
            config_getstr ("working_dir"), /* const char *working_directory */
            argv, /* char **argv */
            envv, /* char **envv */
            G_SPAWN_SEARCH_PATH,    /* GSpawnFlags spawn_flags */
            NULL, /* GSpawnChildSetupFunc child_setup */
            NULL, /* gpointer child_setup_data */
            NULL, /* GPid *child_pid */
            NULL  /* GError **error */
            );

        g_strfreev (argv);
        g_free (envv);

        /* Check for error */
        if (ret == -1)
        {
            g_printerr (_("Unable to launch custom command: %s\n"), config_getstr ("command"));
            g_printerr (_("Launching default shell instead\n"));

            goto launch_default_shell;
        }

        return 0; /* SUCCESS: the early way out */
    }

launch_default_shell:

    /* No custom command, get it from the environment */
    default_command = (gchar *) g_getenv ("SHELL");

    /* Check for error */
    if (default_command == NULL)
        default_command = "/bin/sh";

    /* We need to create a NULL terminated list of arguments.
     * The first item is the command to execute in the shell, in this
     * case there are no further arguments being passed. */
    argv = malloc(2 * sizeof(void *));
    argv[0] = default_command;
    argv[1] = NULL;

    ret = vte_terminal_fork_command_full (VTE_TERMINAL (tt->vte_term),
        VTE_PTY_DEFAULT, /* VtePtyFlags pty_flags */
        config_getstr ("working_dir"), /* const char *working_directory */
        argv, /* char **argv */
        NULL, /* char **envv */
        0,    /* GSpawnFlags spawn_flags */
        NULL, /* GSpawnChildSetupFunc child_setup */
        NULL, /* gpointer child_setup_data */
        NULL, /* GPid *child_pid */
        NULL  /* GError **error */
        );

    g_free (argv);

    if (ret == -1)
    {
        g_printerr (_("Unable to launch default shell: %s\n"), default_command);
        return ret;
    }

    return 0;
}
gint
main (gint argc, gchar ** argv)
{
	GtkWidget *window;
	GtkWidget *matekbd_keyboard_drawing;
	GdkScreen *screen;
	gint monitor;
	GdkRectangle rect;
	GOptionContext *context;

	MatekbdKeyboardDrawingGroupLevel groupLevels[4] =
	    { {0, 0}, {1, 0}, {0, 1}, {1, 1} };
	MatekbdKeyboardDrawingGroupLevel *pgroupLevels[4] =
	    { &groupLevels[0], &groupLevels[1], &groupLevels[2],
		&groupLevels[3]
	};

	context = g_option_context_new ("kbdraw");
	g_option_context_add_main_entries (context, options, NULL);
	g_option_context_parse (context, &argc, &argv, NULL);
	g_option_context_free (context);

	if (program_version) {
		g_print ("kbdraw %s\n", VERSION);
		exit (0);
	}

	gtk_init (&argc, &argv);

	if (!set_groups (groups, groupLevels)) {
		g_printerr ("--groups: invalid argument\n");
		exit (1);
	}

	if (!set_levels (levels, groupLevels)) {
		g_printerr ("--levels: invalid argument\n");
		exit (1);
	}

	window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	g_signal_connect (G_OBJECT (window), "destroy",
			  G_CALLBACK (gtk_main_quit), NULL);

	screen = gtk_window_get_screen (GTK_WINDOW (window));
	monitor = gdk_screen_get_monitor_at_point (screen, 0, 0);
	gdk_screen_get_monitor_geometry (screen, monitor, &rect);
	gtk_window_set_default_size (GTK_WINDOW (window),
				     rect.width * 4 / 5,
				     rect.height * 1 / 2);

	gtk_widget_show (window);

	matekbd_keyboard_drawing = matekbd_keyboard_drawing_new ();
	gtk_widget_show (matekbd_keyboard_drawing);
	gtk_container_add (GTK_CONTAINER (window), matekbd_keyboard_drawing);

	matekbd_keyboard_drawing_set_groups_levels (MATEKBD_KEYBOARD_DRAWING
						 (matekbd_keyboard_drawing),
						 pgroupLevels);

	if (track_modifiers)
		matekbd_keyboard_drawing_set_track_modifiers
		    (MATEKBD_KEYBOARD_DRAWING (matekbd_keyboard_drawing), TRUE);
	if (track_config)
		matekbd_keyboard_drawing_set_track_config
		    (MATEKBD_KEYBOARD_DRAWING (matekbd_keyboard_drawing), TRUE);
	g_signal_connect (G_OBJECT (matekbd_keyboard_drawing), "bad-keycode",
			  G_CALLBACK (bad_keycode), NULL);

	if (symbols || geometry || keycodes) {
		XkbComponentNamesRec names;
		gint success;

		memset (&names, '\0', sizeof (names));

		if (symbols)
			names.symbols = symbols;
		else
			names.symbols = (gchar *)
			    matekbd_keyboard_drawing_get_symbols
			    (MATEKBD_KEYBOARD_DRAWING
			     (matekbd_keyboard_drawing));

		if (keycodes)
			names.keycodes = keycodes;
		else
			names.keycodes = (gchar *)
			    matekbd_keyboard_drawing_get_keycodes
			    (MATEKBD_KEYBOARD_DRAWING
			     (matekbd_keyboard_drawing));

		if (geometry)
			names.geometry = geometry;
		else
			names.geometry = (gchar *)
			    matekbd_keyboard_drawing_get_geometry
			    (MATEKBD_KEYBOARD_DRAWING
			     (matekbd_keyboard_drawing));

		success =
		    matekbd_keyboard_drawing_set_keyboard
		    (MATEKBD_KEYBOARD_DRAWING (matekbd_keyboard_drawing),
		     &names);
		if (!success) {
			g_printerr
			    ("\nError loading new keyboard description with components:\n\n"
			     "  keycodes:  %s\n" "  types:     %s\n"
			     "  compat:    %s\n" "  symbols:   %s\n"
			     "  geometry:  %s\n\n", names.keycodes,
			     names.types, names.compat, names.symbols,
			     names.geometry);
			exit (1);
		}
	}

	gtk_widget_grab_focus (matekbd_keyboard_drawing);

	gtk_main ();

	return 0;
}
Esempio n. 20
0
static void popup_menu (tilda_window *tw, tilda_term *tt)
{
    DEBUG_FUNCTION ("popup_menu");
    DEBUG_ASSERT (tw != NULL);
    DEBUG_ASSERT (tt != NULL);

    GtkAction *action;
    GtkActionGroup *action_group;
    GtkUIManager *ui_manager;
    GError *error = NULL;
    GtkWidget *menu;

    /* Just use a static string here to initialize the GtkUIManager,
     * rather than installing and reading from a file all the time. */
    static const gchar menu_str[] =
        "<ui>"
            "<popup name=\"popup-menu\">"
                "<menuitem action=\"new-tab\" />"
                "<menuitem action=\"close-tab\" />"
                "<separator />"
                "<menuitem action=\"copy\" />"
                "<menuitem action=\"paste\" />"
                "<separator />"
                "<menuitem action=\"fullscreen\" />"
                "<separator />"
                "<menuitem action=\"preferences\" />"
                "<separator />"
                "<menuitem action=\"quit\" />"
            "</popup>"
        "</ui>";

    /* Create the action group */
    action_group = gtk_action_group_new ("popup-menu-action-group");

    /* Add Actions and connect callbacks */
    action = gtk_action_new ("new-tab", _("_New Tab"), NULL, GTK_STOCK_ADD);
    gtk_action_group_add_action_with_accel (action_group, action, config_getstr("addtab_key"));
    g_signal_connect (G_OBJECT(action), "activate", G_CALLBACK(menu_add_tab_cb), tw);

    action = gtk_action_new ("close-tab", _("_Close Tab"), NULL, GTK_STOCK_CLOSE);
    gtk_action_group_add_action_with_accel (action_group, action, config_getstr("closetab_key"));
    g_signal_connect (G_OBJECT(action), "activate", G_CALLBACK(menu_close_tab_cb), tw);

    action = gtk_action_new ("copy", NULL, NULL, GTK_STOCK_COPY);
    gtk_action_group_add_action_with_accel (action_group, action, config_getstr("copy_key"));
    g_signal_connect (G_OBJECT(action), "activate", G_CALLBACK(menu_copy_cb), tt);

    action = gtk_action_new ("paste", NULL, NULL, GTK_STOCK_PASTE);
    gtk_action_group_add_action_with_accel (action_group, action, config_getstr("paste_key"));
    g_signal_connect (G_OBJECT(action), "activate", G_CALLBACK(menu_paste_cb), tt);

    action = gtk_action_new ("fullscreen", _("Toggle fullscreen"), NULL, NULL);
    gtk_action_group_add_action (action_group, action);
    g_signal_connect (G_OBJECT(action), "activate", G_CALLBACK(menu_fullscreen_cb), tw);

    action = gtk_action_new ("preferences", NULL, NULL, GTK_STOCK_PREFERENCES);
    gtk_action_group_add_action (action_group, action);
    g_signal_connect (G_OBJECT(action), "activate", G_CALLBACK(menu_preferences_cb), tw);

    action = gtk_action_new ("quit", NULL, NULL, GTK_STOCK_QUIT);
    gtk_action_group_add_action_with_accel (action_group, action, config_getstr("quit_key"));
    g_signal_connect (G_OBJECT(action), "activate", G_CALLBACK(menu_quit_cb), tw);

    /* Create and add actions to the GtkUIManager */
    ui_manager = gtk_ui_manager_new ();
    gtk_ui_manager_insert_action_group (ui_manager, action_group, 0);
    gtk_ui_manager_add_ui_from_string (ui_manager, menu_str, -1, &error);

    /* Check for an error (REALLY REALLY unlikely, unless the developers screwed up */
    if (error)
    {
        DEBUG_ERROR ("GtkUIManager problem\n");
        g_printerr ("Error message: %s\n", error->message);
        g_error_free (error);
    }

    /* Get the popup menu out of the GtkUIManager */
    menu = gtk_ui_manager_get_widget (ui_manager, "/ui/popup-menu");

    /* Disable auto hide */
    tw->disable_auto_hide = TRUE;
    g_signal_connect (G_OBJECT(menu), "unmap", G_CALLBACK(on_popup_hide), tw);

    /* Display the menu */
    gtk_menu_popup (GTK_MENU(menu), NULL, NULL, NULL, NULL, 3, gtk_get_current_event_time());
    gtk_widget_show_all(menu);
}
Esempio n. 21
0
static void disconn_func(GObex *obex, GError *err, gpointer user_data)
{
	g_printerr("Disconnected: %s\n", err ? err->message : "(no error)");
	g_main_loop_quit(main_loop);
}
Esempio n. 22
0
static int button_press_cb (GtkWidget *widget, GdkEventButton *event, gpointer data)
{
    DEBUG_FUNCTION ("button_press_cb");
    DEBUG_ASSERT (data != NULL);

    VteTerminal *terminal;
    tilda_term *tt;
    gchar *match;
    gint tag;
    gint xpad, ypad;
    gchar *cmd;
    gchar *web_browser_cmd;
    gboolean ret = FALSE;

    tt = TILDA_TERM(data);

    switch (event->button)
    {
        case 3: /* Right Click */
            popup_menu (tt->tw, tt);
            break;
        case 2: /* Middle Click */
            break;
        case 1: /* Left Click */
            terminal  = VTE_TERMINAL(tt->vte_term);
            GtkBorder border;
            gtk_widget_style_get (GTK_WIDGET (terminal),
                "inner-border", &border, NULL);
            xpad = border.left;
            ypad = border.bottom;
            match = vte_terminal_match_check (terminal,
                    (event->x - ypad) /
                    vte_terminal_get_char_width (terminal),
                    (event->y - ypad) /
                    vte_terminal_get_char_height (terminal),
                    &tag);

            /* Check if we can launch a web browser, and do so if possible */
            if ((event->state & GDK_CONTROL_MASK) && match != NULL)
            {
#if DEBUG
                g_print ("Got a Ctrl+Left Click -- Matched: `%s' (%d)\n", match, tag);
#endif
                web_browser_cmd = g_strescape (config_getstr ("web_browser"), NULL);
                cmd = g_strdup_printf ("%s %s", web_browser_cmd, match);
#if DEBUG
                g_print ("Launching command: `%s'\n", cmd);
#endif
                ret = g_spawn_command_line_async(cmd, NULL);

                /* Check that the command launched */
                if (!ret)
                {
                    g_printerr (_("Failed to launch the web browser. The command was `%s'\n"), cmd);
                    TILDA_PERROR ();
                }

                g_free (cmd);
            }

            /* Always free match if it is non NULL */
            if (match)
                g_free (match);

            break;
        default:
            break;
    }

    return FALSE;
}
int main (int argc,
	  char **argv)
{
	gint retval;
	GList *etds, *l;
	UhmServer *server;
	gchar *module_path = NULL;
	GModule *module = NULL;

	retval = ews_test_init (argc, argv);

	if (retval < 0)
		goto exit;

	if (!g_module_supported ())
		goto exit;

	module_path = g_module_build_path (CALENDAR_MODULE_DIR, "libecalbackendews");
	module = g_module_open (module_path, G_MODULE_BIND_LAZY | G_MODULE_BIND_LOCAL);

	if (module == NULL)
		goto exit;

	if (!g_module_symbol (
		module,
		"e_cal_backend_ews_populate_windows_zones",
		(gpointer *) &populate_windows_zones)) {
			g_printerr ("\n%s\n", g_module_error ());
			goto exit;
	}

	if (!g_module_symbol (
		module,
		"e_cal_backend_ews_tz_util_get_msdn_equivalent",
		(gpointer *) &ical_to_msdn_equivalent)) {
			g_printerr ("\n%s\n", g_module_error ());
			goto exit;
	}

	if (!g_module_symbol (
		module,
		"e_cal_backend_ews_convert_calcomp_to_xml",
		(gpointer *) &convert_calcomp_to_xml)) {
			g_printerr ("\n%s\n", g_module_error ());
			goto exit;
	}


	server = ews_test_get_mock_server ();
	etds = ews_test_get_test_data_list ();

	/* Set handler of debug information */
	populate_windows_zones ();
	builtin_timezones = icaltimezone_get_builtin_timezones ();

	for (l = etds; l != NULL; l = l->next) {
		EwsTestData *etd = l->data;
		gchar *message;

		if (!uhm_server_get_enable_online (server))
			g_signal_connect (server, "notify::resolver", (GCallback) server_notify_resolver_cb, etd);

		/* Create folder */
		if (e_ews_debug_get_server_version_from_string (etd->version) >= E_EWS_EXCHANGE_2010) {
			message = g_strdup_printf ("/%s/calendar/timezones/ical_compatibility", etd->version);
			g_test_add_data_func (message, etd, test_libical_timezones_compatibility);
			g_free (message);

			message = g_strdup_printf ("/%s/calendar/timezones/time_zones_sync", etd->version);
			g_test_add_data_func (message, etd, test_time_zones_sync);
			g_free (message);
		}
	}

	retval = g_test_run ();

	if (!uhm_server_get_enable_online (server))
		for (l = etds; l != NULL; l = l->next)
			g_signal_handlers_disconnect_by_func (server, server_notify_resolver_cb, l->data);

 exit:
	g_free (module_path);
	if (module != NULL)
		g_module_close (module);
	if (builtin_timezones != NULL)
		icalarray_free (builtin_timezones);
	ews_test_cleanup ();

	return retval;
}
Esempio n. 24
0
/** Initializes a new pwstorage context. */
const dt_pwstorage_t* dt_pwstorage_new()
{
  dt_pwstorage_t *pwstorage = g_malloc(sizeof(dt_pwstorage_t));
  dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_new] Creating new context %lx\n",(unsigned long int)pwstorage);

  if(pwstorage == NULL)
    return NULL;

  gint _backend = dt_conf_get_int( "plugins/pwstorage/pwstorage_backend" );

  switch(_backend)
  {
    default:
      dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_new] unknown storage backend. Using none.\n");
    case PW_STORAGE_BACKEND_NONE:
      pwstorage->pw_storage_backend = PW_STORAGE_BACKEND_NONE;
      pwstorage->backend_context = NULL;
      dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_new] no storage backend. not storing username/password. please change in gconf: \"plugins/pwstorage/pwstorage_backend\".\n");
      break;
    case PW_STORAGE_BACKEND_GCONF:
      // this is so important that I want it to be printed in any case. so g_printerr() instead of dt_print()
      g_printerr("[pwstorage_new] WARNING: you are using gconf for username/password storage! they are being stored unencrypted on your hard disk.\n");
      pwstorage->pw_storage_backend = PW_STORAGE_BACKEND_GCONF;
      pwstorage->backend_context = NULL;
      break;
    case PW_STORAGE_BACKEND_KWALLET:
#ifdef HAVE_KWALLET
      dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_new] using kwallet backend for username/password storage");
      pwstorage->backend_context = (void*)dt_pwstorage_kwallet_new();
      if(pwstorage->backend_context == NULL)
      {
        dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_new] error starting kwallet. using no storage backend.\n");
        pwstorage->backend_context = NULL;
        pwstorage->pw_storage_backend = PW_STORAGE_BACKEND_NONE;
      }
      else
      {
        pwstorage->pw_storage_backend = PW_STORAGE_BACKEND_KWALLET;
      }
      dt_print(DT_DEBUG_PWSTORAGE,"  done.\n");
#else
      dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_new] kwallet storage not available. using no storage backend.\n");
      pwstorage->backend_context = NULL;
      pwstorage->pw_storage_backend = PW_STORAGE_BACKEND_NONE;
#endif
      break;
#ifdef HAVE_GKEYRING
    case PW_STORAGE_BACKEND_GNOME_KEYRING:
      dt_print (DT_DEBUG_PWSTORAGE,"[pwstorage_new] using gnome keyring backend for usersname/password storage.\n");
      pwstorage->backend_context = (void*)dt_pwstorage_gkeyring_new ();
      if (pwstorage->backend_context == NULL)
      {
        dt_print (DT_DEBUG_PWSTORAGE,"[pwstorage_new] error starting gnome keyring. using no storage backend.\n");
        pwstorage->backend_context = NULL;
        pwstorage->pw_storage_backend = PW_STORAGE_BACKEND_NONE;
      }
      else
        pwstorage->pw_storage_backend = PW_STORAGE_BACKEND_GNOME_KEYRING;
#else
      dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_new] gnome keyring storage not available. using no storage backend.\n");
      pwstorage->backend_context = NULL;
      pwstorage->pw_storage_backend = PW_STORAGE_BACKEND_NONE;
#endif
      break;
  }

  dt_conf_set_int( "plugins/pwstorage/pwstorage_backend", pwstorage->pw_storage_backend );

  return pwstorage;
}
Esempio n. 25
0
int main(int argc, char *argv[]) {

    GError *error = NULL;

    gchar *server = NULL;
    gchar *form_data;
    gchar *form_seconds;
    SoupURI *watchdog_uri;
    guint ret = 0;
    guint64 seconds;

    gchar *prefix = NULL;
    gchar *server_recipe_key = NULL;
    gchar *server_recipe = NULL;
    GHashTable *data_table = g_hash_table_new (NULL, NULL);

    GOptionEntry entries[] = {
        {"server", 's', 0, G_OPTION_ARG_STRING, &server,
            "Server to connect to", "URL" },
        { NULL }
    };
    GOptionContext *context = g_option_context_new(NULL);
    g_option_context_set_summary(context,
            "Adjust watchdog on lab controller. if you don't specify the\n"
            "the server url you must have RECIPEID defined.\n"
            "If HARNESS_PREFIX is defined then the value of that must be\n"
            "prefixed to RECIPEID");
    g_option_context_add_main_entries(context, entries, NULL);
    gboolean parse_succeeded = g_option_context_parse(context, &argc, &argv, &error);
    g_option_context_free(context);

    if (!parse_succeeded) {
        goto cleanup;
    }

    seconds = parse_time_string (argv[1], &error);
    if (error) {
        goto cleanup;
     }

    prefix = getenv("HARNESS_PREFIX") ? getenv("HARNESS_PREFIX") : "";
    server_recipe_key = g_strdup_printf ("%sRECIPE_URL", prefix);
    server_recipe = getenv(server_recipe_key);

    if (!server && server_recipe) {
        server = g_strdup_printf ("%s/watchdog", server_recipe);
    }

    if (!server) {
        g_printerr("Try %s --help\n", argv[0]);
        goto cleanup;
    }

    watchdog_uri = soup_uri_new (server);
    session = soup_session_new_with_options("timeout", 3600, NULL);
    SoupMessage *server_msg = soup_message_new_from_uri ("POST", watchdog_uri);
    form_seconds = g_strdup_printf ("%" PRIu64, seconds);
    g_hash_table_insert (data_table, "seconds", form_seconds);
    form_data = soup_form_encode_hash (data_table);
    g_free (form_seconds);
    soup_message_set_request (server_msg, "application/x-www-form-urlencoded",
                              SOUP_MEMORY_TAKE, form_data, strlen (form_data));

    ret = soup_session_send_message (session, server_msg);
    if (SOUP_STATUS_IS_SUCCESSFUL (ret)) {
    } else {
        g_warning ("Failed to adjust watchdog, status: %d Message: %s\n", ret, server_msg->reason_phrase);
    }

    soup_uri_free (watchdog_uri);

cleanup:
    if (error) {
        g_printerr("%s [%s, %d]\n", error->message,
                g_quark_to_string(error->domain), error->code);
        return error->code;
    } else {
        return EXIT_SUCCESS;
    }
}
Esempio n. 26
0
GPtrArray *create_derivation_array(const gchar *distributed_derivation_file)
{
    /* Declarations */
    xmlDocPtr doc;
    xmlNodePtr node_root;
    xmlXPathObjectPtr result;
    GPtrArray *derivation_array = NULL;
    
    /* Parse the XML document */
    
    if((doc = xmlParseFile(distributed_derivation_file)) == NULL)
    {
	g_printerr("Error with parsing the distributed derivation XML file!\n");
	xmlCleanupParser();
	return NULL;
    }
    
    /* Retrieve root element */
    node_root = xmlDocGetRootElement(doc);
    
    if(node_root == NULL)
    {
        g_printerr("The distributed derivation XML file is empty!\n");
	xmlFreeDoc(doc);
	xmlCleanupParser();
	return NULL;
    }

    /* Query the mapping elements */
    result = executeXPathQuery(doc, "/distributedderivation/build/mapping");
    
    /* Iterate over all the mapping elements and add them to the array */
    
    if(result)
    {
	xmlNodeSetPtr nodeset = result->nodesetval;
	unsigned int i;
	
	/* Create a derivation array */
        derivation_array = g_ptr_array_new();
	
	/* Iterate over all the mapping elements */
	for(i = 0; i < nodeset->nodeNr; i++)
        {
	    xmlNodePtr mapping_children = nodeset->nodeTab[i]->children;
	    DerivationItem *item = (DerivationItem*)g_malloc(sizeof(DerivationItem));
	    gchar *derivation = NULL, *target = NULL;
	    
	    /* Iterate over all the mapping item children (derivation and target elements) */
	    
	    while(mapping_children != NULL)
	    {
		if(xmlStrcmp(mapping_children->name, (xmlChar*) "derivation") == 0)
		    derivation = duplicate_node_text(mapping_children);
		else if(xmlStrcmp(mapping_children->name, (xmlChar*) "target") == 0)
		    target = duplicate_node_text(mapping_children);
		
		mapping_children = mapping_children->next;
	    }
	    
	    /* Added the mapping to the array */
	    item->derivation = derivation;
	    item->target = target;
	    item->result = NULL;
	    
	    if(item->derivation == NULL || item->target == NULL)
	    {
	        /* Check if all mandatory properties have been provided */
	        g_printerr("A mandatory property seems to be missing. Have you provided a correct\n");
	        g_printerr("distributed derivation file?\n");
	        delete_derivation_array(derivation_array);
	        derivation_array = NULL;
	        break;
	    }
	    else
	        g_ptr_array_add(derivation_array, item); /* Add item to the array */
        }
        
        xmlXPathFreeObject(result);
    }
    
    /* Cleanup */
    xmlFreeDoc(doc);
    xmlCleanupParser();
    
    /* Return the derivation array */
    return derivation_array;
}
Esempio n. 27
0
static void
print_plugin_automatic_install_info_codecs (GstElementFactory * factory)
{
  GstPadDirection direction;
  const gchar *type_name;
  const gchar *klass;
  const GList *static_templates, *l;
  GstCaps *caps = NULL;
  guint i, num;

  klass = gst_element_factory_get_klass (factory);
  g_return_if_fail (klass != NULL);

  if (strstr (klass, "Demuxer") ||
      strstr (klass, "Decoder") ||
      strstr (klass, "Depay") || strstr (klass, "Parser")) {
    type_name = "decoder";
    direction = GST_PAD_SINK;
  } else if (strstr (klass, "Muxer") ||
      strstr (klass, "Encoder") || strstr (klass, "Pay")) {
    type_name = "encoder";
    direction = GST_PAD_SRC;
  } else {
    return;
  }

  /* decoder/demuxer sink pads should always be static and there should only
   * be one, the same applies to encoders/muxers and source pads */
  static_templates = gst_element_factory_get_static_pad_templates (factory);
  for (l = static_templates; l != NULL; l = l->next) {
    GstStaticPadTemplate *tmpl = NULL;

    tmpl = (GstStaticPadTemplate *) l->data;
    if (tmpl->direction == direction) {
      caps = gst_static_pad_template_get_caps (tmpl);
      break;
    }
  }

  if (caps == NULL) {
    g_printerr ("Couldn't find static pad template for %s '%s'\n",
        type_name, GST_PLUGIN_FEATURE_NAME (factory));
    return;
  }

  caps = gst_caps_make_writable (caps);
  num = gst_caps_get_size (caps);
  for (i = 0; i < num; ++i) {
    GstStructure *s;
    gchar *s_str;

    s = gst_caps_get_structure (caps, i);
    /* remove fields that are almost always just MIN-MAX of some sort
     * in order to make the caps look less messy */
    gst_structure_remove_field (s, "pixel-aspect-ratio");
    gst_structure_remove_field (s, "framerate");
    gst_structure_remove_field (s, "channels");
    gst_structure_remove_field (s, "width");
    gst_structure_remove_field (s, "height");
    gst_structure_remove_field (s, "rate");
    gst_structure_remove_field (s, "depth");
    gst_structure_remove_field (s, "clock-rate");
    s_str = gst_structure_to_string (s);
    g_print ("%s-%s\n", type_name, s_str);
    g_free (s_str);
  }
  gst_caps_unref (caps);
}
Esempio n. 28
0
static gint _main_helper(Options* options) {
    /* start off with some status messages */
#if defined(IGRAPH_VERSION)
    gint igraphMajor = -1, igraphMinor = -1, igraphPatch = -1;
    igraph_version(NULL, &igraphMajor, &igraphMinor, &igraphPatch);

    gchar* startupStr = g_strdup_printf("Starting %s with GLib v%u.%u.%u and IGraph v%i.%i.%i",
            SHADOW_VERSION_STRING,
            (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION,
            igraphMajor, igraphMinor, igraphPatch);
#else
    gchar* startupStr = g_strdup_printf("Starting %s with GLib v%u.%u.%u (IGraph version not available)",
            SHADOW_VERSION_STRING,
            (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION);
#endif

    message("%s", startupStr);
    /* avoid logging the message to stderr twice (only log if this is not a relaunch) */
    if(g_getenv("SHADOW_SPAWNED") == NULL) {
        g_printerr("** %s\n", startupStr);
    }
    g_free(startupStr);

    message(SHADOW_INFO_STRING);
    message("logging current startup arguments and environment");

    gchar** envlist = g_get_environ();
    gchar** arglist = g_strsplit(options_getArgumentString(options), " ", 0);
    _main_logEnvironment(arglist, envlist);
    g_strfreev(arglist);
    g_strfreev(envlist);

    /* check if we still need to setup our required environment and relaunch */
    if(g_getenv("SHADOW_SPAWNED") == NULL) {
        message("shadow will automatically adjust environment and relaunch");
        message("loading shadow configuration file");

        /* we need to relaunch.
         * first lets load the config file to help us setup the environment */
        const GString* fileName = options_getInputXMLFilename(options);
        if(!fileName) {
            return EXIT_FAILURE;
        }

        GString* file = utility_getFileContents(fileName->str);
        if(!file) {
            critical("unable to read config file contents");
            return EXIT_FAILURE;
        }

        Configuration* config = configuration_new(options, file);
        g_string_free(file, TRUE);
        file = NULL;
        if(!config) {
            critical("there was a problem parsing the Shadow config file, and we can't run without it");
            return EXIT_FAILURE;
        }

        message("shadow configuration file loaded, parsed, and passed validation");

        /* now start to set up the environment */
        gchar** envlist = g_get_environ();
        GString* commandBuffer = g_string_new(options_getArgumentString(options));

        if(!envlist || !commandBuffer) {
            critical("there was a problem loading existing environment");
            configuration_free(config);
            return EXIT_FAILURE;
        }

        message("setting up LD_PRELOAD environment");

        /* compute the proper LD_PRELOAD value, extract the shadow preload file and
         * set it as a command line argument if needed */
        gchar* preloadArgValue = NULL;
        {
            /* before we restart, we should:
             *  -set the shadow preload lib as a command line arg
             *  -make sure it does not exist in LD_PRELOAD, but otherwise leave LD_PRELOAD in place
             * we need to search for our preload lib. our order of preference follows.
             */

            /* 1. existing "--preload=" option value */

            if(_main_isValidPathToPreloadLib(options_getPreloadString(options))) {
                preloadArgValue = g_strdup(options_getPreloadString(options));
            }

            /* 2. the 'preload' attribute value of the 'shadow' element in shadow.config.xml */

            /* we only need to search if we haven't already found a valid path */
            if(!preloadArgValue) {
                ConfigurationShadowElement* element = configuration_getShadowElement(config);
                if(element && element->preloadPath.isSet) {
                    gchar* path = element->preloadPath.string->str;
                    if(_main_isValidPathToPreloadLib(path)) {
                        preloadArgValue = g_strdup(path);
                    }
                }
            }

            /* 3. the LD_PRELOAD value */

            GString* preloadEnvValueBuffer = NULL;
            /* we always search the env variable and remove existing Shadow preload libs */
            if(g_environ_getenv(envlist, "LD_PRELOAD") != NULL) {
                gchar** tokens = g_strsplit(g_environ_getenv(envlist, "LD_PRELOAD"), ":", 0);

                for(gint i = 0; tokens[i] != NULL; i++) {
                    /* each token in the env variable should be an absolute path */
                    if(_main_isValidPathToPreloadLib(tokens[i])) {
                        /* found a valid path, only save it if we don't have one yet (from options or config) */
                        if(!preloadArgValue) {
                            preloadArgValue = g_strdup(tokens[i]);
                        }
                    } else {
                        /* maintain non-shadow entries */
                        if(preloadEnvValueBuffer) {
                            g_string_append_printf(preloadEnvValueBuffer, ":%s", tokens[i]);
                        } else {
                            preloadEnvValueBuffer = g_string_new(tokens[i]);
                        }
                    }
                }

                g_strfreev(tokens);
            }

            /* 4. the 'environment' attribute of the 'shadow' configuration element in shadow.config.xml */

            /* always go through the 'environment' attribute of the 'shadow' element to pull in any keys defined there */
            {
                ConfigurationShadowElement* element = configuration_getShadowElement(config);
                if(element && element->environment.isSet) {
                    /* entries are split by ';' */
                    gchar** envTokens = g_strsplit(element->environment.string->str, ";", 0);

                    for(gint i = 0; envTokens[i] != NULL; i++) {
                        /* each env entry is key=value, get 2 tokens max */
                        gchar** items = g_strsplit(envTokens[i], "=", 2);

                        gchar* key = items[0];
                        gchar* value = items[1];

                        if(key != NULL && value != NULL) {
                            /* check if the key is LD_PRELOAD */
                            if(!g_ascii_strncasecmp(key, "LD_PRELOAD", 10)) {
                                gchar** preloadTokens = g_strsplit(value, ":", 0);

                                for(gint j = 0; preloadTokens[j] != NULL; j++) {
                                    /* each token in the env variable should be an absolute path */
                                    if(_main_isValidPathToPreloadLib(preloadTokens[j])) {
                                        /* found a valid path, only save it if we don't have one yet (from options or config) */
                                        if(!preloadArgValue) {
                                            preloadArgValue = g_strdup(preloadTokens[j]);
                                        }
                                    } else {
                                        /* maintain non-shadow entries */
                                        if(preloadEnvValueBuffer) {
                                            g_string_append_printf(preloadEnvValueBuffer, ":%s", preloadTokens[j]);
                                        } else {
                                            preloadEnvValueBuffer = g_string_new(preloadTokens[j]);
                                        }
                                    }
                                }

                                g_strfreev(preloadTokens);
                            } else {
                                /* set the key=value pair, but don't overwrite any existing settings */
                                envlist = g_environ_setenv(envlist, key, value, 0);
                            }
                        }

                        g_strfreev(items);
                    }

                    g_strfreev(envTokens);
                }
            }

            /* save away the non-shadow preload libs */
            if(preloadEnvValueBuffer) {
                envlist = g_environ_setenv(envlist, "LD_PRELOAD", preloadEnvValueBuffer->str, 1);
                g_string_free(preloadEnvValueBuffer, TRUE);
                preloadEnvValueBuffer = NULL;
            } else {
                envlist = g_environ_unsetenv(envlist, "LD_PRELOAD");
            }

            /* 5. as a last hope, try looking in RPATH since shadow is built with one */

            /* we only need to search if we haven't already found a valid path */
            if(!preloadArgValue) {
                gchar* rpathStr = _main_getRPath();
                if(rpathStr != NULL) {
                    gchar** tokens = g_strsplit(rpathStr, ":", 0);

                    for(gint i = 0; tokens[i] != NULL; i++) {
                        GString* candidateBuffer = g_string_new(NULL);

                        /* rpath specifies directories, so look inside */
                        g_string_printf(candidateBuffer, "%s/%s", tokens[i], INTERPOSELIBSTR);
                        gchar* candidate = g_string_free(candidateBuffer, FALSE);

                        if(_main_isValidPathToPreloadLib(candidate)) {
                            preloadArgValue = candidate;
                            break;
                        } else {
                            g_free(candidate);
                        }
                    }

                    g_strfreev(tokens);
                }
                g_free(rpathStr);
            }

            /* if we still didn't find our preload lib, that is a user error */
            if(!preloadArgValue) {
                critical("can't find path to %s, did you specify an absolute path to an existing readable file?", INTERPOSELIBSTR);
                configuration_free(config);
                return EXIT_FAILURE;
            }

            /* now that we found the correct path to the preload lib, first remove any possibly
             * incomplete path that might exist in the command line args, and then replace it
             * with the path that we found and verified is correct. */

            {
                /* first remove all preload options */
                gchar** tokens = g_strsplit(commandBuffer->str, " ", 0);
                g_string_free(commandBuffer, TRUE);
                commandBuffer = NULL;

                for(gint i = 0; tokens[i] != NULL; i++) {
                    /* use -1 to search the entire string */
                    if(!g_ascii_strncasecmp(tokens[i], "--preload=", 10)) {
                        /* skip this key=value string */
                    } else if(!g_ascii_strncasecmp(tokens[i], "-p", 2)) {
                        /* skip this key, and also the next arg which is the value */
                        i++;
                    } else {
                        if(commandBuffer) {
                            g_string_append_printf(commandBuffer, " %s", tokens[i]);
                        } else {
                            commandBuffer = g_string_new(tokens[i]);
                        }
                    }
                }

                g_strfreev(tokens);

                /* now add back in the preload option */
                g_string_append_printf(commandBuffer, " --preload=%s", preloadArgValue);
            }

        }

        message("setting up LD_STATIC_TLS_EXTRA environment");

        /* compute the proper TLS size we need for dlmopen()ing all of the plugins,
         * but only do this if the user didn't manually specify a size */
        if(g_environ_getenv(envlist, "LD_STATIC_TLS_EXTRA") == NULL) {
            gchar* staticTLSValue = _main_getStaticTLSValue(options, config, preloadArgValue);
            envlist = g_environ_setenv(envlist, "LD_STATIC_TLS_EXTRA", staticTLSValue, 0);
            message("we need %s total bytes of static TLS storage", staticTLSValue);
            g_free(staticTLSValue);
        }

        /* cleanup unused string */
        if(preloadArgValue) {
            g_free(preloadArgValue);
            preloadArgValue = NULL;
        }

        /* are we running valgrind */
        if(options_doRunValgrind(options)) {
            message("setting up environment for valgrind");

            /* make glib friendlier to valgrind */
            envlist = g_environ_setenv(envlist, "G_DEBUG", "gc-friendly", 0);
            envlist = g_environ_setenv(envlist, "G_SLICE", "always-malloc", 0);

            /* add the valgrind command and some default options */
            g_string_prepend(commandBuffer,
                            "valgrind --leak-check=full --show-reachable=yes --track-origins=yes --trace-children=yes --log-file=shadow-valgrind-%p.log --error-limit=no ");
        } else {
            /* The following can be used to add internal GLib memory validation that
             * will abort the program if it finds an error. This is only useful outside
             * of the valgrind context, as otherwise valgrind will complain about
             * the implementation of the GLib validator.
             * e.g. $ G_SLICE=debug-blocks shadow --file
             *
             * envlist = g_environ_setenv(envlist, "G_SLICE", "debug-blocks", 0);
             */
        }

        /* keep track that we are relaunching shadow */
        envlist = g_environ_setenv(envlist, "SHADOW_SPAWNED", "TRUE", 1);

        gchar* command = g_string_free(commandBuffer, FALSE);
        gchar** arglist = g_strsplit(command, " ", 0);
        g_free(command);

        configuration_free(config);

        message("environment was updated; shadow is relaunching now with new environment");

        Logger* logger = logger_getDefault();
        if(logger) {
            logger_setDefault(NULL);
            logger_unref(logger);
        }

        /* execvpe only returns if there is an error, otherwise the current process
         * image is replaced with a new process */
        gint returnValue = execvpe(arglist[0], arglist, envlist);

        /* cleanup */
        if(envlist) {
            g_strfreev(envlist);
        }
        if(arglist) {
            g_strfreev(arglist);
        }

        critical("** Error %i while re-launching shadow process: %s", returnValue, g_strerror(returnValue));
        return EXIT_FAILURE;
    }

    /* we dont need to relaunch, so we can run the simulation */

    /* make sure we have initialized static tls */
    if(!_main_verifyStaticTLS()) {
        critical("** Shadow Setup Check Failed: LD_STATIC_TLS_EXTRA does not contain a nonzero value");
        return EXIT_FAILURE;
    }

    /* make sure we have the shadow preload lib */
    if(!_main_isValidPathToPreloadLib(options_getPreloadString(options))) {
        critical("** Shadow Setup Check Failed: cannot find absolute path to "INTERPOSELIBSTR"");
        return EXIT_FAILURE;
    }

    /* now load the preload library into shadow's namespace */
    if(!_main_loadShadowPreload(options)) {
        critical("** Shadow Setup Check Failed: unable to load preload library");
        return EXIT_FAILURE;
    }

    /* tell the preload lib we are ready for action */
    extern int interposer_setShadowIsLoaded(int);
    int interposerResult = interposer_setShadowIsLoaded(1);

    if(interposerResult != 0) {
        /* it was not intercepted, meaning our preload library is not set up properly */
        critical("** Shadow Setup Check Failed: preload library is not correctly interposing functions");
        return EXIT_FAILURE;
    }

    message("startup checks passed, we are ready to start simulation");

    /* pause for debugger attachment if the option is set */
    if(options_doRunDebug(options)) {
        gint pid = (gint)getpid();
        message("Pausing with SIGTSTP to enable debugger attachment (pid %i)", pid);
        g_printerr("** Pausing with SIGTSTP to enable debugger attachment (pid %i)\n", pid);
        raise(SIGTSTP);
        message("Resuming now");
    }

    /* allocate and initialize our main simulation driver */
    gint returnCode = 0;
    shadowMaster = master_new(options);

    message("log message buffering is enabled for efficiency");
    logger_setEnableBuffering(logger_getDefault(), TRUE);

    if(shadowMaster) {
        /* run the simulation */
        returnCode = master_run(shadowMaster);
        /* cleanup */
        master_free(shadowMaster);
        shadowMaster = NULL;
    }

    message("%s simulation was shut down cleanly, returning code %i", SHADOW_VERSION_STRING, returnCode);
    return returnCode;
}
Esempio n. 29
0
void parse_config (GromitData *data)
{
  GromitPaintContext *context=NULL;
  GromitPaintContext *context_template=NULL;
  GScanner *scanner;
  GTokenType token;
  gchar *filename;
  int file;

  gchar *name, *copy;

  GromitPaintType type;
  GdkRGBA *fg_color=NULL;
  guint width, arrowsize, minwidth;

  filename = g_strjoin (G_DIR_SEPARATOR_S,
                        g_get_user_config_dir(), "gromit-mpx.cfg", NULL);
  file = open (filename, O_RDONLY);

  if (file < 0)
    {
      g_printerr ("Could not open %s: %s\n", filename, g_strerror (errno));
      /* try global config file */
      g_free (filename);
      filename = g_strdup ("/etc/gromit-mpx/gromit-mpx.cfg");
      file = open (filename, O_RDONLY);

      if (file < 0)
        {
          g_printerr ("Could not open %s: %s\n", filename, g_strerror (errno));
          g_free (filename);
          return;
        }
    }

  scanner = g_scanner_new (NULL);
  scanner->input_name = filename;
  scanner->config->case_sensitive = 0;
  scanner->config->scan_octal = 0;
  scanner->config->identifier_2_string = 0;
  scanner->config->char_2_token = 1;
  scanner->config->numbers_2_int = 1;
  scanner->config->int_2_float = 1;

  g_scanner_scope_add_symbol (scanner, 0, "PEN",    (gpointer) GROMIT_PEN);
  g_scanner_scope_add_symbol (scanner, 0, "ERASER", (gpointer) GROMIT_ERASER);
  g_scanner_scope_add_symbol (scanner, 0, "RECOLOR",(gpointer) GROMIT_RECOLOR);

  g_scanner_scope_add_symbol (scanner, 1, "BUTTON1", (gpointer) 1);
  g_scanner_scope_add_symbol (scanner, 1, "BUTTON2", (gpointer) 2);
  g_scanner_scope_add_symbol (scanner, 1, "BUTTON3", (gpointer) 3);
  g_scanner_scope_add_symbol (scanner, 1, "BUTTON4", (gpointer) 4);
  g_scanner_scope_add_symbol (scanner, 1, "BUTTON5", (gpointer) 5);
  g_scanner_scope_add_symbol (scanner, 1, "SHIFT",   (gpointer) 11);
  g_scanner_scope_add_symbol (scanner, 1, "CONTROL", (gpointer) 12);
  g_scanner_scope_add_symbol (scanner, 1, "META",    (gpointer) 13);
  g_scanner_scope_add_symbol (scanner, 1, "ALT",     (gpointer) 13);

  g_scanner_scope_add_symbol (scanner, 2, "size",      (gpointer) 1);
  g_scanner_scope_add_symbol (scanner, 2, "color",     (gpointer) 2);
  g_scanner_scope_add_symbol (scanner, 2, "arrowsize", (gpointer) 3);
  g_scanner_scope_add_symbol (scanner, 2, "minsize",   (gpointer) 4);

  g_scanner_set_scope (scanner, 0);
  scanner->config->scope_0_fallback = 0;

  g_scanner_input_file (scanner, file);

  token = g_scanner_get_next_token (scanner);
  while (token != G_TOKEN_EOF)
    {

      /*
       * New tool definition
       */

      if (token == G_TOKEN_STRING)
        {
          name = parse_name (scanner);
          token = g_scanner_cur_token(scanner);

          if (token != G_TOKEN_EQUAL_SIGN)
            {
              g_scanner_unexp_token (scanner, G_TOKEN_EQUAL_SIGN, NULL,
                                     NULL, NULL, "aborting", TRUE);
              exit (1);
            }

          token = g_scanner_get_next_token (scanner);

          /* defaults */

          type = GROMIT_PEN;
          width = 7;
          arrowsize = 0;
          minwidth = 1;
          fg_color = data->red;

          if (token == G_TOKEN_SYMBOL)
            {
              type = (GromitPaintType) scanner->value.v_symbol;
              token = g_scanner_get_next_token (scanner);
            }
          else if (token == G_TOKEN_STRING)
            {
              copy = parse_name (scanner);
              token = g_scanner_cur_token(scanner);
              context_template = g_hash_table_lookup (data->tool_config, copy);
              if (context_template)
                {
                  type = context_template->type;
                  width = context_template->width;
                  arrowsize = context_template->arrowsize;
                  minwidth = context_template->minwidth;
                  fg_color = context_template->paint_color;
                }
              else
                {
                  g_printerr ("WARNING: Unable to copy \"%s\": "
                              "not yet defined!\n", copy);
                }
            }
          else
            {
              g_printerr ("Expected Tool-definition "
                          "or name of template tool\n");
              exit (1);
            }

          /* Are there any tool-options?
           */

          if (token == G_TOKEN_LEFT_PAREN)
            {
              GdkRGBA *color = NULL;
              g_scanner_set_scope (scanner, 2);
              scanner->config->int_2_float = 1;
              token = g_scanner_get_next_token (scanner);
              while (token != G_TOKEN_RIGHT_PAREN)
                {
                  if (token == G_TOKEN_SYMBOL)
                    {
                      if ((intptr_t) scanner->value.v_symbol == 1)
                        {
                          token = g_scanner_get_next_token (scanner);
                          if (token != G_TOKEN_EQUAL_SIGN)
                            {
                              g_printerr ("Missing \"=\"... aborting\n");
                              exit (1);
                            }
                          token = g_scanner_get_next_token (scanner);
                          if (token != G_TOKEN_FLOAT)
                            {
                              g_printerr ("Missing Size (float)... aborting\n");
                              exit (1);
                            }
                          width = (guint) (scanner->value.v_float + 0.5);
                        }
                      else if ((intptr_t) scanner->value.v_symbol == 2)
                        {
                          token = g_scanner_get_next_token (scanner);
                          if (token != G_TOKEN_EQUAL_SIGN)
                            {
                              g_printerr ("Missing \"=\"... aborting\n");
                              exit (1);
                            }
                          token = g_scanner_get_next_token (scanner);
                          if (token != G_TOKEN_STRING)
                            {
                              g_printerr ("Missing Color (string)... "
                                          "aborting\n");
                              exit (1);
                            }
                          color = g_malloc (sizeof (GdkRGBA));
                          if (gdk_rgba_parse (color, scanner->value.v_string))
                            {
			      fg_color = color;
                            }
                          else
                            {
                              g_printerr ("Unable to parse color. "
                                          "Keeping default.\n");
                              g_free (color);
                            }
                          color = NULL;
                        }
                      else if ((intptr_t) scanner->value.v_symbol == 3)
                        {
                          token = g_scanner_get_next_token (scanner);
                          if (token != G_TOKEN_EQUAL_SIGN)
                            {
                              g_printerr ("Missing \"=\"... aborting\n");
                              exit (1);
                            }
                          token = g_scanner_get_next_token (scanner);
                          if (token != G_TOKEN_FLOAT)
                            {
                              g_printerr ("Missing Arrowsize (float)... "
                                          "aborting\n");
                              exit (1);
                            }
                          arrowsize = scanner->value.v_float;
                        }
                      else if ((intptr_t) scanner->value.v_symbol == 4)
                        {
                          token = g_scanner_get_next_token (scanner);
                          if (token != G_TOKEN_EQUAL_SIGN)
                            {
                              g_printerr ("Missing \"=\"... aborting\n");
                              exit (1);
                            }
                          token = g_scanner_get_next_token (scanner);
                          if (token != G_TOKEN_FLOAT)
                            {
                              g_printerr ("Missing Minsize (float)... "
                                          "aborting\n");
                              exit (1);
                            }
                          minwidth = scanner->value.v_float;
                        }
		      else
                        {
                          g_printerr ("Unknown tool type?????\n");
                        }
                    }
                  else
                    {
                      g_printerr ("skipped token!!!\n");
                    }
                  token = g_scanner_get_next_token (scanner);
                }
              g_scanner_set_scope (scanner, 0);
              token = g_scanner_get_next_token (scanner);
            }

          /*
           * Finally we expect a semicolon
           */

          if (token != ';')
            {
              g_printerr ("Expected \";\"\n");
              exit (1);
            }

          context = paint_context_new (data, type, fg_color, width, arrowsize, minwidth);
          g_hash_table_insert (data->tool_config, name, context);
        }
      else
        {
          g_printerr ("Expected name of Tool to define\n");
          exit(1);
        }

      token = g_scanner_get_next_token (scanner);
    }
  g_scanner_destroy (scanner);
  close (file);
  g_free (filename);
}
Esempio n. 30
0
void CommandLine::errorHelp(const char* binName)
{
	//TODO - strip this down to just the filename
	g_printerr("USAGE: %s [options] [nds-file]\n", binName);
	g_printerr("USAGE: %s --help    - for help\n", binName);
}