Example #1
0
int main(int argc, char **argv)
{
	GOptionContext *context;
	GError *err = NULL;
	DBusConnection *conn;
	DBusError error;
	guint signal;

#ifdef NEED_THREADS
	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);
#endif

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

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

		g_printerr("An unknown error occurred\n");
		return 1;
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(0);
	}

	if (option_detach == TRUE) {
		if (daemon(0, 0)) {
			perror("Can't start daemon");
			return 1;
		}
	}

	event_loop = g_main_loop_new(NULL, FALSE);

#ifdef NEED_THREADS
	if (dbus_threads_init_default() == FALSE) {
		fprintf(stderr, "Can't init usage of threads\n");
		exit(1);
	}
#endif

	signal = setup_signalfd();

	__ofono_log_init(argv[0], option_debug, option_detach);

	dbus_error_init(&error);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, OFONO_SERVICE, &error);
	if (conn == NULL) {
		if (dbus_error_is_set(&error) == TRUE) {
			ofono_error("Unable to hop onto D-Bus: %s",
					error.message);
			dbus_error_free(&error);
		} else {
			ofono_error("Unable to hop onto D-Bus");
		}

		goto cleanup;
	}

	g_dbus_set_disconnect_function(conn, system_bus_disconnected,
					NULL, NULL);

	__ofono_dbus_init(conn);

	__ofono_modemwatch_init();

	__ofono_manager_init();

	__ofono_plugin_init(option_plugin, option_noplugin);

	g_free(option_plugin);
	g_free(option_noplugin);

	g_main_loop_run(event_loop);

	__ofono_plugin_cleanup();

	__ofono_manager_cleanup();

	__ofono_modemwatch_cleanup();

	__ofono_dbus_cleanup();
	dbus_connection_unref(conn);

cleanup:
	g_source_remove(signal);

	g_main_loop_unref(event_loop);

	__ofono_log_cleanup();

	g_free(option_debug);

	return 0;
}
Example #2
0
int
main (int argc, char *argv[])
{
    GMainLoop *inner;
    GError *err = NULL;
    guint name_id;

    g_type_init ();

    /* Setup application context */
    mm_context_init (argc, argv);

    if (!mm_log_setup (mm_context_get_log_level (),
                       mm_context_get_log_file (),
                       mm_context_get_timestamps (),
                       mm_context_get_relative_timestamps (),
                       mm_context_get_debug (),
                       &err)) {
        g_warning ("Failed to set up logging: %s", err->message);
        g_error_free (err);
        exit (1);
    }

    g_unix_signal_add (SIGTERM, quit_cb, NULL);
    g_unix_signal_add (SIGINT, quit_cb, NULL);

    mm_info ("ModemManager (version " MM_DIST_VERSION ") starting in %s bus...",
             mm_context_get_test_session () ? "session" : "system");

    /* Acquire name, don't allow replacement */
    name_id = g_bus_own_name (mm_context_get_test_session () ? G_BUS_TYPE_SESSION : G_BUS_TYPE_SYSTEM,
                              MM_DBUS_SERVICE,
                              G_BUS_NAME_OWNER_FLAGS_NONE,
                              bus_acquired_cb,
                              name_acquired_cb,
                              name_lost_cb,
                              NULL,
                              NULL);

    /* Go into the main loop */
    loop = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (loop);

    /* Clear the global variable, so that subsequent requests to
     * exit succeed. */
    inner = loop;
    loop = NULL;

    if (manager) {
        GTimer *timer;

        mm_base_manager_shutdown (manager);

        /* Wait for all modems to be disabled and removed, but don't wait
         * forever: if disabling the modems takes longer than 20s, just
         * shutdown anyway. */
        timer = g_timer_new ();
        while (mm_base_manager_num_modems (manager) &&
               g_timer_elapsed (timer, NULL) < (gdouble)MAX_SHUTDOWN_TIME_SECS) {
            GMainContext *ctx = g_main_loop_get_context (inner);

            g_main_context_iteration (ctx, FALSE);
            g_usleep (50);
        }

        if (mm_base_manager_num_modems (manager))
            mm_warn ("Disabling modems took too long, "
                     "shutting down with '%u' modems around",
                     mm_base_manager_num_modems (manager));

        g_object_unref (manager);
        g_timer_destroy (timer);
    }

    g_main_loop_unref (inner);

    g_bus_unown_name (name_id);

    mm_info ("ModemManager is shut down");

    mm_log_shutdown ();

    return 0;
}
Example #3
0
Player::Backend::~Backend() {
    gst_element_set_state (pipeline_, GST_STATE_NULL);
    gst_object_unref (GST_OBJECT (pipeline_));
    g_main_loop_unref (loop_);
}
static gpointer
provider_thread (gpointer data)
{
  GstV4l2DeviceProvider *provider = data;
  GMainContext *context = NULL;
  GMainLoop *loop = NULL;
  GUdevClient *client;
  GList *devices;
  static const gchar *subsystems[] = { "video4linux", NULL };

  GST_OBJECT_LOCK (provider);
  if (provider->context)
    context = g_main_context_ref (provider->context);
  if (provider->loop)
    loop = g_main_loop_ref (provider->loop);

  if (context == NULL || loop == NULL) {
    provider->started = TRUE;
    g_cond_broadcast (&provider->started_cond);
    GST_OBJECT_UNLOCK (provider);
    return NULL;
  }
  GST_OBJECT_UNLOCK (provider);

  g_main_context_push_thread_default (context);

  client = g_udev_client_new (subsystems);

  g_signal_connect (client, "uevent", G_CALLBACK (uevent_cb), provider);

  devices = g_udev_client_query_by_subsystem (client, "video4linux");

  while (devices) {
    GUdevDevice *udev_device = devices->data;
    GstDevice *gstdev;

    devices = g_list_remove (devices, udev_device);

    if (g_udev_device_get_property_as_int (udev_device, "ID_V4L_VERSION") == 2) {
      gstdev =
          gst_v4l2_device_provider_device_from_udev (provider, udev_device);
      if (gstdev)
        gst_device_provider_device_add (GST_DEVICE_PROVIDER (provider), gstdev);
    }

    g_object_unref (udev_device);
  }

  GST_OBJECT_LOCK (provider);
  provider->started = TRUE;
  g_cond_broadcast (&provider->started_cond);
  GST_OBJECT_UNLOCK (provider);

  g_main_loop_run (loop);
  g_main_loop_unref (loop);

  g_object_unref (client);
  g_main_context_unref (context);

  gst_object_unref (provider);

  return NULL;
}
Example #5
0
int
main (int argc, char **argv)
{
	GError *error = NULL;
	gint ret = 1;
	GOptionContext *opt_context = NULL;
	guint name_owner_id = 0;
	guint sigint_id = 0;
	gboolean verbose = FALSE;
	GOptionEntry opt_entries[] = {
		{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
			_("Show extra debugging information"), NULL },
		{ "replace", 'r', 0, G_OPTION_ARG_NONE, &opt_replace,
			"Replace existing daemon", NULL},
		{ "no-sigint", 's', 0, G_OPTION_ARG_NONE, &opt_no_sigint,
			"Do not handle SIGINT for controlled shutdown", NULL},
		{ "session", 'S', 0, G_OPTION_ARG_NONE, &opt_session,
			_("Use the session D-Bus (for testing)"), NULL},
		{NULL }
	};

#if !GLIB_CHECK_VERSION(2,36,0)
	g_type_init ();
#endif /* glib < 2.36 */

	/* avoid gvfs (http://bugzilla.gnome.org/show_bug.cgi?id=526454) */
	if (!g_setenv ("GIO_USE_VFS", "local", TRUE)) {
		g_printerr ("Error setting GIO_USE_GVFS\n");
		goto out;
	}

	opt_context = g_option_context_new ("printer daemon");
	g_option_context_add_main_entries (opt_context, opt_entries, NULL);
	if (!g_option_context_parse (opt_context, &argc, &argv, &error)) {
		g_printerr ("Error parsing options: %s\n", error->message);
		g_error_free (error);
		goto out;
	}

	/* verbose? */
	if (verbose) {
		g_log_set_fatal_mask (NULL, G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL);
		g_log_set_handler ("printerd",
				   G_LOG_LEVEL_ERROR |
				   G_LOG_LEVEL_CRITICAL |
				   G_LOG_LEVEL_DEBUG |
				   G_LOG_LEVEL_WARNING,
				   pd_log_handler_cb, NULL);
	} else {
		g_log_set_fatal_mask (NULL, G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL);
		g_log_set_handler ("printerd", G_LOG_LEVEL_DEBUG,
				   pd_log_ignore_cb, NULL);
	}

	loop = g_main_loop_new (NULL, FALSE);

	if (!opt_no_sigint) {
		sigint_id = g_unix_signal_add_full (G_PRIORITY_DEFAULT,
						    SIGINT,
						    on_sigint,
						    NULL,	/* user_data */
						    NULL); /* GDestroyNotify */
	}

	name_owner_id = g_bus_own_name (opt_session ?
					G_BUS_TYPE_SESSION : G_BUS_TYPE_SYSTEM,
					"org.freedesktop.printerd",
					G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT |
						(opt_replace ? G_BUS_NAME_OWNER_FLAGS_REPLACE : 0),
					on_bus_acquired,
					on_name_acquired,
					on_name_lost,
					NULL,
					NULL);
	g_debug ("Entering main event loop");
	g_main_loop_run (loop);

	/* success */
	ret = 0;
 out:
	if (sigint_id > 0)
		g_source_remove (sigint_id);
	if (the_daemon != NULL)
		g_object_unref (the_daemon);
	if (name_owner_id != 0)
		g_bus_unown_name (name_owner_id);
	if (loop != NULL)
		g_main_loop_unref (loop);
	if (opt_context != NULL)
		g_option_context_free (opt_context);
	g_debug ("printerd daemon version %s exiting", PACKAGE_VERSION);
	return ret;
}
Example #6
0
int main(int argc, char **argv)
{
	GOptionContext *context;
	GError *error = NULL;
	DBusConnection *conn;
	DBusError err;
	guint watch;
	struct sigaction sa;

#ifdef NEED_THREADS
	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);
#endif

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

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		if (error != NULL) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		exit(1);
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(0);
	}

	main_loop = g_main_loop_new(NULL, FALSE);

#ifdef NEED_THREADS
	if (dbus_threads_init_default() == FALSE) {
		fprintf(stderr, "Can't init usage of threads\n");
		exit(1);
	}
#endif

	dbus_error_init(&err);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, &err);
	if (conn == NULL) {
		if (dbus_error_is_set(&err) == TRUE) {
			fprintf(stderr, "%s\n", err.message);
			dbus_error_free(&err);
		} else
			fprintf(stderr, "Can't register with system bus\n");
		exit(1);
	}

	g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sig_term;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

	watch = g_dbus_add_service_watch(conn, OFONO_SERVICE,
				ofono_connect, ofono_disconnect, NULL, NULL);

	g_main_loop_run(main_loop);

	g_dbus_remove_watch(conn, watch);

	if (ofono_running == TRUE)
		ofono_disconnect(conn, NULL);

	dbus_connection_unref(conn);

	g_main_loop_unref(main_loop);

	return 0;
}
Example #7
0
int main (void)
{
  NiceAgent *lagent, *ragent;      /* agent's L and R */
  NiceAddress baseaddr;
  int result;
  guint timer_id;
  const char *stun_server = NULL, *stun_server_port = NULL;

#ifdef G_OS_WIN32
  WSADATA w;

  WSAStartup(0x0202, &w);
#endif
  g_type_init ();
  g_thread_init(NULL);

  global_mainloop = g_main_loop_new (NULL, FALSE);

  /* Note: impl limits ...
   * - no multi-stream support
   * - no IPv6 support
   */


  /* step: create the agents L and R */
  lagent = nice_agent_new (g_main_loop_get_context (global_mainloop), NICE_COMPATIBILITY_RFC5245);
  ragent = nice_agent_new (g_main_loop_get_context (global_mainloop), NICE_COMPATIBILITY_RFC5245);


  /* step: add a timer to catch state changes triggered by signals */
  timer_id = g_timeout_add (30000, timer_cb, NULL);

  /* step: specify which local interface to use */
  if (!nice_address_set_from_string (&baseaddr, "127.0.0.1"))
    g_assert_not_reached ();
  nice_agent_add_local_address (lagent, &baseaddr);
  nice_agent_add_local_address (ragent, &baseaddr);

  g_signal_connect (G_OBJECT (lagent), "candidate-gathering-done", 
		    G_CALLBACK (cb_candidate_gathering_done), (gpointer)1);
  g_signal_connect (G_OBJECT (ragent), "candidate-gathering-done", 
		    G_CALLBACK (cb_candidate_gathering_done), (gpointer)2);
  g_signal_connect (G_OBJECT (lagent), "component-state-changed", 
		    G_CALLBACK (cb_component_state_changed), (gpointer)1);
  g_signal_connect (G_OBJECT (ragent), "component-state-changed", 
		    G_CALLBACK (cb_component_state_changed), (gpointer)2);
  g_signal_connect (G_OBJECT (lagent), "new-selected-pair", 
		    G_CALLBACK (cb_new_selected_pair), (gpointer)1);
  g_signal_connect (G_OBJECT (ragent), "new-selected-pair", 
		    G_CALLBACK (cb_new_selected_pair), (gpointer)2);
  g_signal_connect (G_OBJECT (lagent), "new-candidate", 
		    G_CALLBACK (cb_new_candidate), (gpointer)1);
  g_signal_connect (G_OBJECT (ragent), "new-candidate", 
		    G_CALLBACK (cb_new_candidate), (gpointer)2);
  g_signal_connect (G_OBJECT (lagent), "initial-binding-request-received", 
		    G_CALLBACK (cb_initial_binding_request_received), (gpointer)1);
  g_signal_connect (G_OBJECT (ragent), "initial-binding-request-received", 
		    G_CALLBACK (cb_initial_binding_request_received), (gpointer)2);

  stun_server = getenv ("NICE_STUN_SERVER");
  stun_server_port = getenv ("NICE_STUN_SERVER_PORT");
  if (stun_server) {
    g_object_set (G_OBJECT (lagent), "stun-server", stun_server,  NULL);
    g_object_set (G_OBJECT (lagent), "stun-server-port", atoi (stun_server_port),  NULL);
    g_object_set (G_OBJECT (ragent), "stun-server", stun_server,  NULL);
    g_object_set (G_OBJECT (ragent), "stun-server-port", atoi (stun_server_port),  NULL);
  }

  /* step: run test the first time */
  g_debug ("test-restart: TEST STARTS / restart test");
  result = run_restart_test (lagent, ragent, &baseaddr);
  priv_print_global_status ();
  g_assert (result == 0);
  g_assert (global_lagent_state == NICE_COMPONENT_STATE_READY);
  g_assert (global_ragent_state == NICE_COMPONENT_STATE_READY);

  g_object_unref (lagent);
  g_object_unref (ragent);


  g_main_loop_unref (global_mainloop);
  global_mainloop = NULL;

  g_source_remove (timer_id);
#ifdef G_OS_WIN32
  WSACleanup();
#endif
  return result;
}
Example #8
0
File: main.c Project: KDE/kimtoy
static void
ibus_impanel_start (void)
{
    ibus_init ();
    bus = ibus_bus_new ();
    if (!ibus_bus_is_connected (bus)) {
        exit (-1);
    }
    g_signal_connect (bus, "disconnected", G_CALLBACK (ibus_disconnected_cb), NULL);
    impanel = ibus_panel_impanel_new (ibus_bus_get_connection (bus));
    ibus_bus_request_name (bus, IBUS_SERVICE_PANEL, 0);
    ibus_panel_impanel_set_bus(impanel, bus);
#if !IBUS_CHECK_VERSION(1,4,99)
    ibus_main ();
#else

    Display*    dpy     = XOpenDisplay(0);
    Window      root    = DefaultRootWindow(dpy);
    XEvent      ev;

    unsigned int    modifiers       = ControlMask;
    int             keycode         = XKeysymToKeycode(dpy, XK_space);

    XGrabKey(dpy, keycode, modifiers, root, False, GrabModeAsync, GrabModeAsync);
    XGrabKey(dpy, keycode, modifiers | LockMask, root, False, GrabModeAsync, GrabModeAsync); // capslock
    XGrabKey(dpy, keycode, modifiers | Mod2Mask, root, False, GrabModeAsync, GrabModeAsync); // numlock
    XGrabKey(dpy, keycode, modifiers | LockMask | Mod2Mask, root, False, GrabModeAsync, GrabModeAsync);

    XSelectInput(dpy, root, KeyPressMask);

//     XCloseDisplay(dpy);

    main_loop = g_main_loop_new(NULL, FALSE);

    int dpyfd = ConnectionNumber(dpy);
    GPollFD dpy_pollfd = {dpyfd, G_IO_IN | G_IO_HUP | G_IO_ERR, 0};

    GSourceFuncs x11_source_funcs = {
        x11_fd_prepare,
        x11_fd_check,
        x11_fd_dispatch,
        NULL, /* finalize */
        NULL, /* closure_callback */
        NULL /* closure_marshal */
    };

    GSource *x11_source = g_source_new(&x11_source_funcs, sizeof(x11_source_t));
    ((x11_source_t*)x11_source)->dpy = dpy;

    g_source_add_poll(x11_source, &dpy_pollfd);
    g_source_set_can_recurse(x11_source, TRUE);
    g_source_attach(x11_source, NULL);

    g_main_loop_run (main_loop);

    g_main_loop_unref (main_loop);
    main_loop = NULL;

    XUngrabKey(dpy, keycode, modifiers, root);
    XUngrabKey(dpy, keycode, modifiers | LockMask, root);
    XUngrabKey(dpy, keycode, modifiers | Mod2Mask, root);
    XUngrabKey(dpy, keycode, modifiers | LockMask | Mod2Mask, root);

    XCloseDisplay(dpy);
#endif
}
Example #9
0
File: app.c Project: DevMaggio/gimp
void
app_run (const gchar         *full_prog_name,
         const gchar        **filenames,
         const gchar         *alternate_system_gimprc,
         const gchar         *alternate_gimprc,
         const gchar         *session_name,
         const gchar         *batch_interpreter,
         const gchar        **batch_commands,
         gboolean             as_new,
         gboolean             no_interface,
         gboolean             no_data,
         gboolean             no_fonts,
         gboolean             no_splash,
         gboolean             be_verbose,
         gboolean             use_shm,
         gboolean             use_cpu_accel,
         gboolean             console_messages,
         gboolean             use_debug_handler,
         GimpStackTraceMode   stack_trace_mode,
         GimpPDBCompatMode    pdb_compat_mode)
{
  GimpInitStatusFunc  update_status_func = NULL;
  Gimp               *gimp;
  GimpGeglConfig     *config;
  GMainLoop          *loop;
  gboolean            swap_is_ok;

  /*  Create an instance of the "Gimp" object which is the root of the
   *  core object system
   */
  gimp = gimp_new (full_prog_name,
                   session_name,
                   be_verbose,
                   no_data,
                   no_fonts,
                   no_interface,
                   use_shm,
                   console_messages,
                   stack_trace_mode,
                   pdb_compat_mode);

  errors_init (gimp, full_prog_name, use_debug_handler, stack_trace_mode);

  units_init (gimp);

  /*  Check if the user's gimp_directory exists
   */
  if (! g_file_test (gimp_directory (), G_FILE_TEST_IS_DIR))
    {
      GimpUserInstall *install = gimp_user_install_new (be_verbose);

#ifdef GIMP_CONSOLE_COMPILATION
      gimp_user_install_run (install);
#else
      if (! (no_interface ?
	     gimp_user_install_run (install) :
	     user_install_dialog_run (install)))
	exit (EXIT_FAILURE);
#endif

      gimp_user_install_free (install);
    }

  gimp_load_config (gimp, alternate_system_gimprc, alternate_gimprc);

  config = GIMP_GEGL_CONFIG (gimp->config);

  /*  change the locale if a language if specified  */
  language_init (gimp->config->language);

  /*  initialize lowlevel stuff  */
  swap_is_ok = base_init (config, be_verbose, use_cpu_accel);

  gimp_gegl_init (gimp);

#ifndef GIMP_CONSOLE_COMPILATION
  if (! no_interface)
    update_status_func = gui_init (gimp, no_splash);
#endif

  if (! update_status_func)
    update_status_func = app_init_update_noop;

  /*  Create all members of the global Gimp instance which need an already
   *  parsed gimprc, e.g. the data factories
   */
  gimp_initialize (gimp, update_status_func);

  /*  Load all data files
   */
  gimp_restore (gimp, update_status_func);

  /* display a warning when no test swap file could be generated */
  if (! swap_is_ok)
    {
      gchar *path = gimp_config_path_expand (config->swap_path, FALSE, NULL);

      g_message (_("Unable to open a test swap file.\n\n"
		   "To avoid data loss, please check the location "
		   "and permissions of the swap directory defined in "
		   "your Preferences (currently \"%s\")."), path);

      g_free (path);
    }

  /*  enable autosave late so we don't autosave when the
   *  monitor resolution is set in gui_init()
   */
  gimp_rc_set_autosave (GIMP_RC (gimp->edit_config), TRUE);

  /*  Load the images given on the command-line.
   */
  if (filenames)
    {
      gint i;

      for (i = 0; filenames[i] != NULL; i++)
        file_open_from_command_line (gimp, filenames[i], as_new);
    }

  batch_run (gimp, batch_interpreter, batch_commands);

  loop = g_main_loop_new (NULL, FALSE);

  g_signal_connect_after (gimp, "exit",
                          G_CALLBACK (app_exit_after_callback),
                          loop);

  gimp_threads_leave (gimp);
  g_main_loop_run (loop);
  gimp_threads_enter (gimp);

  g_main_loop_unref (loop);

  g_object_unref (gimp);

  gimp_debug_instances ();

  errors_exit ();
  gegl_exit ();
  base_exit ();
}
Example #10
0
static void dom_document_fixture_teardown(DomDocumentFixture* fixture, gconstpointer data)
{
    if (fixture->webView)
        g_object_unref(fixture->webView);
    g_main_loop_unref(fixture->loop);
}
Example #11
0
 ~DownloadTest()
 {
     g_signal_handlers_disconnect_matched(m_webContext, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this);
     g_main_loop_unref(m_mainLoop);
 }
Example #12
0
int
main (int argc, char **argv)
{
	SoupSession *session;
	SoupMessage *msg;
	const char *base_uri;
	char *uri;
	gboolean authenticated;
	int i, ntests;

	test_init (argc, argv, NULL);
	apache_init ();

	base_uri = "http://127.0.0.1:47524/";

	/* Main tests */
	current_tests = main_tests;
	ntests = G_N_ELEMENTS (main_tests);
	do_batch_tests (base_uri, ntests);

	/* Re-login tests */
	current_tests = relogin_tests;
	ntests = G_N_ELEMENTS (relogin_tests);
	do_batch_tests (base_uri, ntests);

	/* And now for some regression tests */
	loop = g_main_loop_new (NULL, TRUE);

	debug_printf (1, "Testing pipelined auth (bug 271540):\n");
	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);

	authenticated = FALSE;
	g_signal_connect (session, "authenticate",
			  G_CALLBACK (bug271540_authenticate), &authenticated);

	uri = g_strconcat (base_uri, "Basic/realm1/", NULL);
	for (i = 0; i < 10; i++) {
		msg = soup_message_new (SOUP_METHOD_GET, uri);
		g_object_set_data (G_OBJECT (msg), "#", GINT_TO_POINTER (i + 1));
		g_signal_connect (msg, "wrote_headers",
				  G_CALLBACK (bug271540_sent), &authenticated);

		soup_session_queue_message (session, msg,
					    bug271540_finished, &i);
	}
	g_free (uri);

	g_main_loop_run (loop);
	soup_test_session_abort_unref (session);

	debug_printf (1, "\nTesting digest nonce expiration:\n");

	/* We test two different things here:
	 *
	 *   1. If we get a 401 response with
	 *      "WWW-Authenticate: Digest stale=true...", we should
	 *      retry and succeed *without* the session asking for a
	 *      password again.
	 *
	 *   2. If we get a successful response with
	 *      "Authentication-Info: nextnonce=...", we should update
	 *      the nonce automatically so as to avoid getting a
	 *      stale nonce error on the next request.
	 *
	 * In our Apache config, /Digest/realm1 and
	 * /Digest/realm1/expire are set up to use the same auth info,
	 * but only the latter has an AuthDigestNonceLifetime (of 2
	 * seconds). The way nonces work in Apache, a nonce received
	 * from /Digest/realm1 will still expire in
	 * /Digest/realm1/expire, but it won't issue a nextnonce for a
	 * request in /Digest/realm1. This lets us test both
	 * behaviors.
	 *
	 * The expected conversation is:
	 *
	 * First message
	 *   GET /Digest/realm1
	 *
	 *   401 Unauthorized
	 *   WWW-Authenticate: Digest nonce=A
	 *
	 *   [emit 'authenticate']
	 *
	 *   GET /Digest/realm1
	 *   Authorization: Digest nonce=A
	 *
	 *   200 OK
	 *   [No Authentication-Info]
	 *
	 * [sleep 2 seconds: nonce A is no longer valid, but we have no
	 * way of knowing that]
	 *
	 * Second message
	 *   GET /Digest/realm1/expire/
	 *   Authorization: Digest nonce=A
	 *
	 *   401 Unauthorized
	 *   WWW-Authenticate: Digest stale=true nonce=B
	 *
	 *   GET /Digest/realm1/expire/
	 *   Authorization: Digest nonce=B
	 *
	 *   200 OK
	 *   Authentication-Info: nextnonce=C
	 *
	 * [sleep 1 second]
	 *
	 * Third message
	 *   GET /Digest/realm1/expire/
	 *   Authorization: Digest nonce=C
	 *   [nonce=B would work here too]
	 *
	 *   200 OK
	 *   Authentication-Info: nextnonce=D
	 *
	 * [sleep 1 second; nonces B and C are no longer valid, but D is]
	 *
	 * Fourth message
	 *   GET /Digest/realm1/expire/
	 *   Authorization: Digest nonce=D
	 *
	 *   200 OK
	 *   Authentication-Info: nextnonce=D
	 *
	 */

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);

	uri = g_strconcat (base_uri, "Digest/realm1/", NULL);
	do_digest_nonce_test (session, "First", uri, TRUE, TRUE);
	g_free (uri);
	sleep (2);
	uri = g_strconcat (base_uri, "Digest/realm1/expire/", NULL);
	do_digest_nonce_test (session, "Second", uri, TRUE, FALSE);
	sleep (1);
	do_digest_nonce_test (session, "Third", uri, FALSE, FALSE);
	sleep (1);
	do_digest_nonce_test (session, "Fourth", uri, FALSE, FALSE);
	g_free (uri);

	soup_test_session_abort_unref (session);

	/* Async auth */
	do_async_auth_test (base_uri);

	/* Selecting correct auth when multiple auth types are available */
	do_select_auth_test ();

	g_main_loop_unref (loop);

	test_cleanup ();
	return errors != 0;
}
Example #13
0
/**
 * Main entry point for sleepd - runs the initialization hooks installed at program load time
 *
 * A bit counter-intuitively, this is not the first part of this program which
 * is run.
 *
 * First, everything which uses the {@link INIT_FUNC} macro in init.h are run,
 * which registers a bunch of hooks with the initialization system so that
 * individual modules can be registered without touching the main sleepd
 * initialization code.  Then, once all of those hooks are installed, execution
 * proceeds to this function which actually runs those hooks.
 *
 * - Initializes sleepd.
 * - Attaches as a Luna service under com.palm.sleep.
 * - Attaches to Nyx.
 * - Subscribes to events related to the charger being plugged and unplugged from the com.palm.power service.
 * - Calls {@link TheOneInit()} to finish initialization of the service.
 * - Issues a request to the com.palm.power service to check on the plugged/unplugged status of the charger.
 *
 * @param   argc        Number of command-line arguments.
 * @param   argv        List of command-line arguments.
 *
 * @todo Move the logging initialization functionality into {@link TheOneInit()}.
 */
int
main(int argc, char **argv)
{
	bool retVal;

	/*
	 * Register a function to be able to gracefully handle termination signals
	 * from the OS or other processes.
	 */
	signal(SIGTERM, term_handler);
	signal(SIGINT, term_handler);

#if !GLIB_CHECK_VERSION(2,32,0)

	if (!g_thread_supported())
	{
		g_thread_init(NULL);
	}

#endif

	mainloop = g_main_loop_new(NULL, FALSE);

	/*
	 *  initialize the lunaservice and we want it before all the init
	 *  stuff happening.
	 */
	LSError lserror;
	LSErrorInit(&lserror);

	/*
	 * Register ourselves as the com.palm.sleep service.
	 */
	retVal = LSRegisterPalmService("com.palm.sleep", &psh, &lserror);

	if (retVal)
	{
		/*
		 * Attach our main loop to the service so we can process IPC messages addressed to us.
		 */
		retVal = LSGmainAttachPalmService(psh, mainloop, &lserror);

		if (retVal)
		{

			/*
			 * Get our private bus for our service so we can pass a message to com.palm.power.
			 */
			private_sh = LSPalmServiceGetPrivateConnection(psh);

			/*
			 * Register with com.palm.power for events regarding changes in status
			 * to the plug/unplug state of any chargers which may be attached to our
			 * device.
			 */
			retVal = LSCall(private_sh, "luna://com.palm.lunabus/signal/addmatch",
			                "{\"category\":\"/com/palm/power\","
			                "\"method\":\"USBDockStatus\"}", ChargerStatus, NULL, NULL, &lserror);

			if (retVal)
			{
				/*
				 * Connect to Nyx so we can use it later.
				 */
				int ret = nyx_device_open(NYX_DEVICE_SYSTEM, "Main", &nyxSystem);

				if (ret != NYX_ERROR_NONE)
				{
					SLEEPDLOG_CRITICAL(MSGID_NYX_DEVICE_OPEN_FAIL, 1,
					                   PMLOGKS(CAUSE, "Unable to open the nyx device system"), "");
					abort();
				}


				/*
				 * Call our main initialization function - this is the function which
				 * is supposed to handle initializing pretty much everything for us.
				 */
				TheOneInit();

				/*
				 * Now that we've got something listening for charger status changes,
				 * request the current state of the charger from com.palm.power.
				 */
				LSCall(private_sh, "luna://com.palm.power/com/palm/power/chargerStatusQuery",
				       "{}", ChargerStatus, NULL, NULL, &lserror);

				SLEEPDLOG_DEBUG("Sleepd daemon started");

				g_main_loop_run(mainloop);
			}
		}
	}
	else
	{
		SLEEPDLOG_CRITICAL(MSGID_SRVC_REGISTER_FAIL, 1, PMLOGKS(ERRTEXT,
		                   lserror.message), "Could not initialize sleepd");
		LSErrorFree(&lserror);
	}

	g_main_loop_unref(mainloop);
	return 0;
}
Example #14
0
int
main (int argc, char *argv[])
{
    GstBus *bus;
    gint watch_id;

    gst_init (NULL, NULL);

    loop = g_main_loop_new (NULL, TRUE);

    pipeline = gst_pipeline_new ("pipeline");
#ifdef ASYNC_VERSION
    /* this enables messages of individual elements inside the pipeline */
    g_object_set (pipeline, "message-forward", TRUE, NULL);
#endif

    /* make a bin with the playback elements this is a non-live pipeline */
    play_bin = gst_bin_new ("play_bin");
    play_source = gst_element_factory_make ("audiotestsrc", "play_source");
    play_sink = gst_element_factory_make ("autoaudiosink", "play_sink");

    gst_bin_add (GST_BIN (play_bin), play_source);
    gst_bin_add (GST_BIN (play_bin), play_sink);

    gst_element_link (play_source, play_sink);

    /* make bin with the record elements, this is a live pipeline */
    rec_bin = gst_bin_new ("rec_bin");
    rec_source = gst_element_factory_make ("autoaudiosrc", "rec_source");
    rec_sink = gst_element_factory_make ("fakesink", "rec_sink");

    gst_bin_add (GST_BIN (rec_bin), rec_source);
    gst_bin_add (GST_BIN (rec_bin), rec_sink);

    gst_element_link (rec_source, rec_sink);

    gst_bin_add (GST_BIN (pipeline), play_bin);
    gst_bin_add (GST_BIN (pipeline), rec_bin);

    bus = gst_element_get_bus (pipeline);
    watch_id = gst_bus_add_watch (bus, message_handler, NULL);
    gst_object_unref (bus);

    g_print ("going to PAUSED\n");
    /* returns NO_PREROLL because we have a live element */
    if (gst_element_set_state (pipeline,
                               GST_STATE_PAUSED) != GST_STATE_CHANGE_NO_PREROLL) {
        g_warning ("Expected state change NO_PREROLL result");
    }

    g_print ("waiting for playback preroll\n");
#ifndef ASYNC_VERSION
    /* sync wait for preroll on the playback bin and then go to PLAYING */
    if (gst_element_get_state (play_bin, NULL, NULL,
                               GST_CLOCK_TIME_NONE) != GST_STATE_CHANGE_SUCCESS) {
        g_warning ("Error while waiting for state change");
    }
    g_print ("prerolled, starting synchronized playback and recording\n");
    /* returns ASYNC because the sink linked to the live source is not
     * prerolled */
    if (gst_element_set_state (pipeline,
                               GST_STATE_PLAYING) != GST_STATE_CHANGE_ASYNC) {
        g_warning ("Expected state change NO_PREROLL result");
    }
#endif

    g_main_loop_run (loop);

    g_source_remove (watch_id);
    gst_element_set_state (pipeline, GST_STATE_NULL);
    gst_object_unref (pipeline);

    g_main_loop_unref (loop);

    return 0;
}
Example #15
0
int
main(int argc, char *argv[])
{
    gboolean print_version = FALSE;
    gboolean one_shot = FALSE;
    gchar *output_plugin = NULL;
    gchar **servers_desc = NULL;
    gchar **streams_desc = NULL;
    gchar **input_plugins = NULL;
    gchar **order = NULL;
    gchar *config = NULL;

    int retval = 0;
    GError *error = NULL;
    GOptionContext *option_context = NULL;
    GOptionGroup *option_group;

#if DEBUG
    g_setenv("G_MESSAGES_DEBUG", "all", FALSE);
#endif /* ! DEBUG */

    setlocale(LC_ALL, "");
#ifdef ENABLE_NLS
    bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
    bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
#endif /* ENABLE_NLS */

#if DEBUG
    const gchar *debug_log_filename =  g_getenv("J4STATUS_DEBUG_LOG_FILENAME");
    GDataOutputStream *debug_stream = NULL;

    if ( debug_log_filename != NULL )
    {
        GFile *debug_log;

        debug_log = g_file_new_for_path(debug_log_filename);

        GError *error = NULL;
        GFileOutputStream *debug_log_stream;

        debug_log_stream = g_file_append_to(debug_log, G_FILE_CREATE_NONE, NULL, &error);

        if ( debug_log_stream == NULL )
        {
            g_warning("Couldn't open debug log file: %s", error->message);
            g_clear_error(&error);
        }
        else
        {
            debug_stream = g_data_output_stream_new(G_OUTPUT_STREAM(debug_log_stream));
            g_object_unref(debug_log_stream);

            g_log_set_default_handler(_j4status_core_debug_log_handler, debug_stream);
        }
        g_object_unref(debug_log);
    }
#endif /* DEBUG */

    GOptionEntry entries[] =
    {
        { "output",     'o', 0, G_OPTION_ARG_STRING,       &output_plugin, "Output plugin to use", "<plugin>" },
        { "listen",     'l', 0, G_OPTION_ARG_STRING_ARRAY, &servers_desc,  "Socket to listen on, will create a stream on connection (may be specified several times)", "<listen description>" },
        { "stream",     't', 0, G_OPTION_ARG_STRING_ARRAY, &streams_desc,  "Stream to read from/write to (may be specified several times)", "<stream description>" },
        { "input",      'i', 0, G_OPTION_ARG_STRING_ARRAY, &input_plugins, "Input plugins to use (may be specified several times)", "<plugin>" },
        { "order",      'O', 0, G_OPTION_ARG_STRING_ARRAY, &order,         "Order of sections, specified once a section (see man)", "<section id>" },
        { "one-shot",   '1', 0, G_OPTION_ARG_NONE,         &one_shot,      "Tells j4status to stop right after starting",           NULL },
        { "config",     'c', 0, G_OPTION_ARG_STRING,       &config,        "Config file to use", "<config>" },
        { "version",    'V', 0, G_OPTION_ARG_NONE,         &print_version, "Print version",        NULL },
        { NULL }
    };


    option_context = g_option_context_new("- status line generator");

    option_group = g_option_group_new(NULL, NULL, NULL, NULL, NULL);
    g_option_group_set_translation_domain(option_group, GETTEXT_PACKAGE);
    g_option_group_add_entries(option_group, entries);
    g_option_context_set_main_group(option_context, option_group);

    if ( ! g_option_context_parse(option_context, &argc, &argv, &error) )
    {
        g_warning("Option parsing failed: %s\n", error->message);
        g_clear_error(&error);
        retval = 1;
        goto end;
    }
    g_option_context_free(option_context);

    if ( print_version )
    {
        g_fprintf(stdout, PACKAGE_NAME " " PACKAGE_VERSION "\n");
        goto end;
    }

    if ( config != NULL )
    {
        g_setenv("J4STATUS_CONFIG_FILE", config, TRUE);
        g_free(config);
    }

    GKeyFile *key_file;
    key_file = j4status_config_get_key_file("Plugins");
    if ( key_file != NULL )
    {
        if ( output_plugin == NULL )
            output_plugin = g_key_file_get_string(key_file, "Plugins", "Output", NULL);

        if ( input_plugins == NULL )
            input_plugins = g_key_file_get_string_list(key_file, "Plugins", "Input", NULL, NULL);

        if ( order == NULL )
            order = g_key_file_get_string_list(key_file, "Plugins", "Order", NULL, NULL);

        g_key_file_free(key_file);
    }

    J4statusCoreContext *context;
    context = g_new0(J4statusCoreContext, 1);

    J4statusCoreInterface interface = {
        .context = context,
        .add_section = _j4status_core_add_section,
        .remove_section = _j4status_core_remove_section,
        .trigger_generate = _j4status_core_trigger_generate,
        .trigger_action = _j4status_core_trigger_action,
    };

#ifdef G_OS_UNIX
    g_unix_signal_add(SIGTERM, _j4status_core_source_quit, context);

    g_unix_signal_add(SIGINT, _j4status_core_source_quit, context);
    g_unix_signal_add(SIGUSR1, _j4status_core_signal_usr1, context);
    g_unix_signal_add(SIGUSR2, _j4status_core_signal_usr2, context);

    /* Ignore SIGPIPE as it is useless */
    signal(SIGPIPE, SIG_IGN);
#endif /* G_OS_UNIX */

    context->output_plugin = j4status_plugins_get_output_plugin(&interface, output_plugin);
    if ( context->output_plugin == NULL )
    {
        g_warning("No usable output plugin, tried '%s'", output_plugin);
        retval = 10;
        goto end;
    }

    gchar *header = NULL;
    if ( context->output_plugin->interface.generate_header != NULL )
        header = context->output_plugin->interface.generate_header(context->output_plugin->context);

    /* Creating input/output stream */
    context->io = j4status_io_new(context, header, (const gchar * const *) servers_desc, (const gchar * const *) streams_desc);
    if ( context->io == NULL )
    {
        g_warning("Couldn't create input/output streams");
        retval = 2;
        goto end;
    }

    if ( order != NULL )
    {
        context->order_weights = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
        gchar **id;
        for ( id = order ; *id != NULL ; ++id )
            g_hash_table_insert(context->order_weights, *id, GINT_TO_POINTER(1 + id - order));
        g_free(order);
    }

    context->sections_hash = g_hash_table_new(g_str_hash, g_str_equal);

    context->input_plugins = j4status_plugins_get_input_plugins(&interface, input_plugins);
    if ( context->input_plugins == NULL )
    {
        g_warning("No input plugins, will stop early");
        one_shot = TRUE;
        retval = 11;
    }
    context->sections = g_list_reverse(context->sections);
    if ( context->order_weights != NULL )
        context->sections = g_list_sort(context->sections, _j4status_core_compare_sections);

    _j4status_core_start(context);

    if ( one_shot )
        g_idle_add(_j4status_core_source_quit, context);

    context->loop = g_main_loop_new(NULL, FALSE);
    g_main_loop_run(context->loop);
    g_main_loop_unref(context->loop);
    context->loop = NULL;

    GList *input_plugin_;
    J4statusInputPlugin *input_plugin;
    for ( input_plugin_ = context->input_plugins ; input_plugin_ != NULL ; input_plugin_ = g_list_next(input_plugin_) )
    {
        input_plugin = input_plugin_->data;
        input_plugin->interface.uninit(input_plugin->context);
    }

    if ( context->output_plugin->interface.uninit != NULL )
        context->output_plugin->interface.uninit(context->output_plugin->context);

    j4status_io_free(context->io);

    if ( context->order_weights != NULL )
        g_hash_table_unref(context->order_weights);

    g_hash_table_unref(context->sections_hash);

end:
#if DEBUG
    if ( debug_stream != NULL )
        g_object_unref(debug_stream);
#endif /* DEBUG */

    return retval;
}
Example #16
0
int main (int argc, char **argv)
{
  GMainLoop *loop = NULL;
  GstElement *pipeline = NULL;
  GstBus *bus = NULL;
  GstElement *conf = NULL;
  FsParticipant *part = NULL;
  GError *error = NULL;
  GInputStream *istream = NULL;
  gchar *send_socket, *recv_socket;
  TestSession *ses;

  gst_init (&argc, &argv);

  if (argc != 3)
  {
    g_print ("Usage: %s <send socket> <recv_socket>\n", argv[0]);
    return 1;
  }

  send_socket = argv[1];
  recv_socket = argv[2];

  if (unlink (send_socket) < 0 && errno != ENOENT)
  {
    g_print ("Could not delete send or recv sockets");
    return 2;
  }

  g_print ("Press ENTER when the other side is ready\n");

  loop = g_main_loop_new (NULL, FALSE);

  pipeline = gst_pipeline_new (NULL);

  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  gst_bus_add_watch (bus, async_bus_cb, pipeline);
  gst_object_unref (bus);

  conf = gst_element_factory_make ("fsrtpconference", NULL);
  g_assert (conf);

  part = fs_conference_new_participant (FS_CONFERENCE (conf), "test@ignore",
      &error);
  print_error (error);
  g_assert (part);

  g_assert (gst_bin_add (GST_BIN (pipeline), conf));

  istream = g_unix_input_stream_new (0, FALSE);

  ses = add_audio_session (pipeline, FS_CONFERENCE (conf), 1, part, send_socket,
      recv_socket);

  g_input_stream_skip_async (istream, 1, G_PRIORITY_DEFAULT, NULL, skipped_cb,
      ses);

  g_assert (gst_element_set_state (pipeline, GST_STATE_PLAYING) !=
      GST_STATE_CHANGE_FAILURE);
  g_main_loop_run (loop);

  g_assert (gst_element_set_state (pipeline, GST_STATE_NULL) !=
      GST_STATE_CHANGE_FAILURE);

  g_object_unref (part);
  g_object_unref (istream);

  free_session (ses);

  gst_object_unref (pipeline);
  g_main_loop_unref (loop);

  return 0;
}
Example #17
0
int main (int argc, char *argv[])
{
    //Force line-only buffering so we can see the output during hangs
    setvbuf(stdout, NULL, _IOLBF, 0);
    setvbuf(stderr, NULL, _IOLBF, 0);

    GOOGLE_PROTOBUF_VERIFY_VERSION;

    hu_log_library_versions();
    hu_install_crash_handler();

    DBus::_init_threading();

    gst_init(&argc, &argv);

    try
    {
        MazdaCommandServerCallbacks commandCallbacks;
        CommandServer commandServer(commandCallbacks);
        printf("headunit version: %s \n", commandCallbacks.GetVersion().c_str());
        if (!commandServer.Start())
        {
            loge("Command server failed to start");
            return 1;
        }

        if (argc >= 2 && strcmp(argv[1], "test") == 0)
        {
            //test mode from the installer, if we got here it's ok
            printf("###TESTMODE_OK###\n");
            return 0;
        }

        config::readConfig();
        printf("Looping\n");
        while (true)
        {
            //Make a new one instead of using the default so we can clean it up each run
            run_on_thread_main_context = g_main_context_new();
            //Recreate this each time, it makes the error handling logic simpler
            DBus::Glib::BusDispatcher dispatcher;
            dispatcher.attach(run_on_thread_main_context);
            printf("DBus::Glib::BusDispatcher attached\n");

            DBus::default_dispatcher = &dispatcher;

            printf("Making debug connections\n");
            DBus::Connection hmiBus(HMI_BUS_ADDRESS, false);
            hmiBus.register_bus();

            DBus::Connection serviceBus(SERVICE_BUS_ADDRESS, false);
            serviceBus.register_bus();

            hud_start();

            MazdaEventCallbacks callbacks(serviceBus, hmiBus);
            HUServer headunit(callbacks);
            g_hu = &headunit.GetAnyThreadInterface();
            commandCallbacks.eventCallbacks = &callbacks;

            //Wait forever for a connection
            int ret = headunit.hu_aap_start(config::transport_type, true);
            if (ret < 0) {
                loge("Something bad happened");
                continue;
            }

            gst_app.loop = g_main_loop_new(run_on_thread_main_context, FALSE);
            callbacks.connected = true;

            std::condition_variable quitcv;
            std::mutex quitmutex;
            std::mutex hudmutex;

            std::thread nm_thread([&quitcv, &quitmutex](){ nightmode_thread_func(quitcv, quitmutex); } );
            std::thread gp_thread([&quitcv, &quitmutex](){ gps_thread_func(quitcv, quitmutex); } );
            std::thread hud_thread([&quitcv, &quitmutex, &hudmutex](){ hud_thread_func(quitcv, quitmutex, hudmutex); } );

            /* Start gstreamer pipeline and main loop */

            printf("Starting Android Auto...\n");

            g_main_loop_run (gst_app.loop);

            commandCallbacks.eventCallbacks = nullptr;

            callbacks.connected = false;
            callbacks.videoFocus = false;
            callbacks.audioFocus = AudioManagerClient::FocusType::NONE;
            callbacks.inCall = false;

            printf("quitting...\n");
            //wake up night mode  and gps polling threads
            quitcv.notify_all();

            printf("waiting for nm_thread\n");
            nm_thread.join();

            printf("waiting for gps_thread\n");
            gp_thread.join();

            printf("waiting for hud_thread\n");
            hud_thread.join();

            printf("shutting down\n");

            g_main_loop_unref(gst_app.loop);
            gst_app.loop = nullptr;

            /* Stop AA processing */
            ret = headunit.hu_aap_shutdown();
            if (ret < 0) {
                printf("hu_aap_shutdown() ret: %d\n", ret);
                return ret;
            }

            g_main_context_unref(run_on_thread_main_context);
            run_on_thread_main_context = nullptr;
            g_hu = nullptr;
            DBus::default_dispatcher = nullptr;
        }
    }
    catch(DBus::Error& error)
    {
        loge("DBUS Error: %s: %s", error.name(), error.message());
        return 1;
    }

    return 0;
}
Example #18
0
void
app_run (const gchar         *full_prog_name,
         const gchar        **filenames,
         GFile               *alternate_system_gimprc,
         GFile               *alternate_gimprc,
         const gchar         *session_name,
         const gchar         *batch_interpreter,
         const gchar        **batch_commands,
         gboolean             as_new,
         gboolean             no_interface,
         gboolean             no_data,
         gboolean             no_fonts,
         gboolean             no_splash,
         gboolean             be_verbose,
         gboolean             use_shm,
         gboolean             use_cpu_accel,
         gboolean             console_messages,
         gboolean             use_debug_handler,
         gboolean             show_playground,
         GimpStackTraceMode   stack_trace_mode,
         GimpPDBCompatMode    pdb_compat_mode)
{
  GimpInitStatusFunc  update_status_func = NULL;
  Gimp               *gimp;
  GMainLoop          *loop;
  GMainLoop          *run_loop;
  GFile              *default_folder = NULL;
  GFile              *gimpdir;

  if (filenames && filenames[0] && ! filenames[1] &&
      g_file_test (filenames[0], G_FILE_TEST_IS_DIR))
    {
      if (g_path_is_absolute (filenames[0]))
        {
          default_folder = g_file_new_for_path (filenames[0]);
        }
      else
        {
          gchar *absolute = g_build_path (G_DIR_SEPARATOR_S,
                                          g_get_current_dir (),
                                          filenames[0],
                                          NULL);
          default_folder = g_file_new_for_path (absolute);
          g_free (absolute);
        }

      filenames = NULL;
    }

  /*  Create an instance of the "Gimp" object which is the root of the
   *  core object system
   */
  gimp = gimp_new (full_prog_name,
                   session_name,
                   default_folder,
                   be_verbose,
                   no_data,
                   no_fonts,
                   no_interface,
                   use_shm,
                   use_cpu_accel,
                   console_messages,
                   show_playground,
                   stack_trace_mode,
                   pdb_compat_mode);

  if (default_folder)
    g_object_unref (default_folder);

  gimp_cpu_accel_set_use (use_cpu_accel);

  errors_init (gimp, full_prog_name, use_debug_handler, stack_trace_mode);

  units_init (gimp);

  /*  Check if the user's gimp_directory exists
   */
  gimpdir = gimp_directory_file (NULL);

  if (g_file_query_file_type (gimpdir, G_FILE_QUERY_INFO_NONE, NULL) !=
      G_FILE_TYPE_DIRECTORY)
    {
      GimpUserInstall *install = gimp_user_install_new (be_verbose);

#ifdef GIMP_CONSOLE_COMPILATION
      gimp_user_install_run (install);
#else
      if (! (no_interface ?
	     gimp_user_install_run (install) :
	     user_install_dialog_run (install)))
	exit (EXIT_FAILURE);
#endif

      gimp_user_install_free (install);
    }

  g_object_unref (gimpdir);

  gimp_load_config (gimp, alternate_system_gimprc, alternate_gimprc);

  /*  change the locale if a language if specified  */
  language_init (gimp->config->language);

  /*  initialize lowlevel stuff  */
  gimp_gegl_init (gimp);

  /*  Connect our restore_after callback before gui_init() connects
   *  theirs, so ours runs first and can grab the initial monitor
   *  before the GUI's restore_after callback resets it.
   */
  g_signal_connect_after (gimp, "restore",
                          G_CALLBACK (app_restore_after_callback),
                          NULL);

#ifndef GIMP_CONSOLE_COMPILATION
  if (! no_interface)
    update_status_func = gui_init (gimp, no_splash);
#endif

  if (! update_status_func)
    update_status_func = app_init_update_noop;

  /*  Create all members of the global Gimp instance which need an already
   *  parsed gimprc, e.g. the data factories
   */
  gimp_initialize (gimp, update_status_func);

  /*  Load all data files
   */
  gimp_restore (gimp, update_status_func);

  /*  enable autosave late so we don't autosave when the
   *  monitor resolution is set in gui_init()
   */
  gimp_rc_set_autosave (GIMP_RC (gimp->edit_config), TRUE);

  loop = run_loop = g_main_loop_new (NULL, FALSE);

  g_signal_connect_after (gimp, "exit",
                          G_CALLBACK (app_exit_after_callback),
                          &run_loop);

  /*  Load the images given on the command-line.
   */
  if (filenames)
    {
      gint i;

      for (i = 0; filenames[i] != NULL; i++)
        {
          if (run_loop)
            {
              GFile *file = g_file_new_for_commandline_arg (filenames[i]);

              file_open_from_command_line (gimp, file, as_new,
                                           initial_screen,
                                           initial_monitor);

              g_object_unref (file);
            }
        }
    }

  if (run_loop)
    batch_run (gimp, batch_interpreter, batch_commands);

  if (run_loop)
    {
      gimp_threads_leave (gimp);
      g_main_loop_run (loop);
      gimp_threads_enter (gimp);
    }

  g_main_loop_unref (loop);

  g_object_unref (gimp);

  gimp_debug_instances ();

  errors_exit ();
  gegl_exit ();
}
Example #19
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *error = NULL;
	DBusConnection *conn;
	DBusError err;
	struct sigaction sa;
	mode_t old_umask;

#ifdef NEED_THREADS
	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);
#endif

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

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		if (error != NULL) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		exit(1);
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(0);
	}

	if (option_detach == TRUE) {
		if (daemon(0, 0)) {
			perror("Can't start daemon");
			exit(1);
		}
	}

	if (mkdir(STATEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create state directory");
	}

	if (mkdir(STORAGEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create storage directory");
	}

	old_umask = umask(077);

	main_loop = g_main_loop_new(NULL, FALSE);

#ifdef NEED_THREADS
	if (dbus_threads_init_default() == FALSE) {
		fprintf(stderr, "Can't init usage of threads\n");
		exit(1);
	}
#endif

	dbus_error_init(&err);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, CONNMAN_SERVICE, &err);
	if (conn == NULL) {
		if (dbus_error_is_set(&err) == TRUE) {
			fprintf(stderr, "%s\n", err.message);
			dbus_error_free(&err);
		} else
			fprintf(stderr, "Can't register with system bus\n");
		exit(1);
	}

	g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);

	if (option_compat == TRUE) {
		if (g_dbus_request_name(conn, NM_SERVICE, NULL) == FALSE) {
			fprintf(stderr, "Can't register compat service\n");
			option_compat = FALSE;
		}
	}

	__connman_log_init(option_detach, option_debug ? DBG_ANY : 0);

	if (option_selftest == TRUE) {
		if (__connman_selftest() < 0) {
			connman_error("Self testing routines failed");
			goto selftest;
		}
	}

	__connman_dbus_init(conn);

	__connman_storage_init();
	__connman_element_init(option_device, option_nodevice);

	__connman_agent_init();
	__connman_manager_init(option_compat);
	__connman_profile_init();

	__connman_resolver_init();
	__connman_ipconfig_init();
	__connman_rtnl_init();
	__connman_udev_init();
	__connman_task_init();

	__connman_plugin_init(option_plugin, option_noplugin);

	__connman_element_start();

	g_free(option_device);
	g_free(option_plugin);
	g_free(option_nodevice);
	g_free(option_noplugin);

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sig_term;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

	g_main_loop_run(main_loop);

	__connman_element_stop();

	__connman_plugin_cleanup();

	__connman_task_cleanup();
	__connman_udev_cleanup();
	__connman_rtnl_cleanup();
	__connman_ipconfig_cleanup();
	__connman_resolver_cleanup();

	__connman_profile_cleanup();
	__connman_manager_cleanup();
	__connman_agent_cleanup();

	__connman_element_cleanup();
	__connman_storage_cleanup();

	__connman_dbus_cleanup();

selftest:
	__connman_log_cleanup();

	dbus_connection_unref(conn);

	g_main_loop_unref(main_loop);

	return 0;
}
Example #20
0
int
main (int argc,
      char **argv)
{
  GError *error;
  GOptionContext *opt_context;
  gint ret;
  guint name_owner_id;
  guint sigint_id;

  ret = 1;
  loop = NULL;
  opt_context = NULL;
  name_owner_id = 0;
  sigint_id = 0;

  /* Ignore SIGPIPE, it's not useful in daemons */
  signal (SIGPIPE, SIG_IGN);

  g_type_init ();

  g_setenv ("GIO_USE_PROXY_RESOLVER", "dummy", TRUE);

  /* avoid gvfs (http://bugzilla.gnome.org/show_bug.cgi?id=526454) */
  if (!g_setenv ("GIO_USE_VFS", "local", TRUE))
    {
      g_printerr ("Error setting GIO_USE_GVFS\n");
      goto out;
    }

  opt_context = g_option_context_new ("cockpit storage daemon");
  g_option_context_add_main_entries (opt_context, opt_entries, NULL);
  error = NULL;
  if (!g_option_context_parse (opt_context, &argc, &argv, &error))
    {
      g_printerr ("Error parsing options: %s\n", error->message);
      g_error_free (error);
      goto out;
    }

  if (g_getenv ("PATH") == NULL)
    g_setenv ("PATH", "/usr/bin:/bin:/usr/sbin:/sbin", TRUE);

  cockpit_set_journal_logging (!isatty (2));

  g_info ("cockpit daemon version %s starting", PACKAGE_VERSION);

  loop = g_main_loop_new (NULL, FALSE);

  sigint_id = 0;
  if (!opt_no_sigint)
    {
      sigint_id = g_unix_signal_add_full (G_PRIORITY_DEFAULT,
                                          SIGINT,
                                          on_sigint,
                                          NULL,  /* user_data */
                                          NULL); /* GDestroyNotify */
    }

  name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
                                  "com.redhat.Cockpit",
                                  G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT |
                                    (opt_replace ? G_BUS_NAME_OWNER_FLAGS_REPLACE : 0),
                                  on_bus_acquired,
                                  on_name_acquired,
                                  on_name_lost,
                                  NULL,
                                  NULL);

  g_main_loop_run (loop);

  ret = 0;

out:
  if (sigint_id > 0)
    g_source_remove (sigint_id);
  if (the_daemon != NULL)
    g_object_unref (the_daemon);
  if (name_owner_id != 0)
    g_bus_unown_name (name_owner_id);
  if (loop != NULL)
    g_main_loop_unref (loop);
  if (opt_context != NULL)
    g_option_context_free (opt_context);

  g_info ("cockpit daemon version %s exiting", PACKAGE_VERSION);

  return ret;
}
int
main (AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char *argv[])
{
    GMainLoop *loop = NULL;
    const AvahiPoll *poll_api;
    AvahiGLibPoll *glib_poll;
    AvahiClient *client;
    struct timeval tv;
    const char *version;
    int error;

    /* Optional: Tell avahi to use g_malloc and g_free */
    avahi_set_allocator (avahi_glib_allocator ());

    /* Create the GLIB main loop */
    loop = g_main_loop_new (NULL, FALSE);

    /* Create the GLIB Adaptor */
    glib_poll = avahi_glib_poll_new (NULL, G_PRIORITY_DEFAULT);
    poll_api = avahi_glib_poll_get (glib_poll);

    /* Example, schedule a timeout event with the Avahi API */
    avahi_elapse_time (&tv,                         /* timeval structure */
            1000,                                   /* 1 second */
            0);                                     /* "jitter" - Random additional delay from 0 to this value */

    poll_api->timeout_new (poll_api,                /* The AvahiPoll object */
                      &tv,                          /* struct timeval indicating when to go activate */
                      avahi_timeout_event,          /* Pointer to function to call */
                      NULL);                        /* User data to pass to function */

    /* Schedule a timeout event with the glib api */
    g_timeout_add (5000,                            /* 5 seconds */
            avahi_timeout_event_glib,               /* Pointer to function callback */
            loop);                                  /* User data to pass to function */

    /* Create a new AvahiClient instance */
    client = avahi_client_new (poll_api,            /* AvahiPoll object from above */
                               0,
            avahi_client_callback,                  /* Callback function for Client state changes */
            loop,                                   /* User data */
            &error);                                /* Error return */

    /* Check the error return code */
    if (client == NULL)
    {
        /* Print out the error string */
        g_warning ("Error initializing Avahi: %s", avahi_strerror (error));

        goto fail;
    }

    /* Make a call to get the version string from the daemon */
    version = avahi_client_get_version_string (client);

    /* Check if the call suceeded */
    if (version == NULL)
    {
        g_warning ("Error getting version string: %s", avahi_strerror (avahi_client_errno (client)));

        goto fail;
    }

    g_message ("Avahi Server Version: %s", version);

    /* Start the GLIB Main Loop */
    g_main_loop_run (loop);

fail:
    /* Clean up */
    g_main_loop_unref (loop);
    avahi_client_free (client);
    avahi_glib_poll_free (glib_poll);

    return 0;
}
Example #22
0
int
main(int argc, char **argv)
{
    bool retVal;
    int opt;
    bool invertCarrier = false;

    LSPalmService * lsps = NULL;

    while ((opt = getopt(argc, argv, "chdst")) != -1)
    {
        switch (opt) {
        case 'c':
            invertCarrier = true;
            break;
        case 'd':
            setLogLevel(G_LOG_LEVEL_DEBUG);
            break;
        case 's':
            setUseSyslog(true);
            break;
        case 'h':
        default:
            PrintUsage(argv[0]);
            return EXIT_SUCCESS;
        }
    }

	// make sure we aren't already running.  
	if (!LockProcess("storaged")) {
		g_error("%s: %s daemon is already running.\n", __func__, argv[0]);
		exit(EXIT_FAILURE);
	}


    g_log_set_default_handler(logFilter, NULL);
    g_debug( "entering %s in %s", __func__, __FILE__ );

    signal(SIGTERM, term_handler);

    g_mainloop = g_main_loop_new(NULL, FALSE);


 	int ret = nyx_device_open(NYX_DEVICE_SYSTEM, "Main", &nyxSystem);
 	if(ret != NYX_ERROR_NONE)
 	{
 		g_critical("Unable to open the nyx device system");
 		abort();
 	}
 	else
 		g_debug("Initialized nyx system device");

    /**
     *  initialize the lunaservice and we want it before all the init
     *  stuff happening.
     */
    LSError lserror;
    LSErrorInit(&lserror);

    retVal = LSRegisterPalmService("com.palm.storage", &lsps, &lserror);
    if (!retVal)
    {
        g_critical ("failed in function %s with erro %s", lserror.func, lserror.message);
        LSErrorFree(&lserror);
        return EXIT_FAILURE;
    }

    SignalsInit( lsps );

    LSHandle *lsh_priv = LSPalmServiceGetPrivateConnection(lsps);
    LSHandle *lsh_pub = LSPalmServiceGetPublicConnection(lsps);

    DiskModeInterfaceInit( g_mainloop, lsh_priv, lsh_pub, invertCarrier );
    EraseInit(g_mainloop, lsh_priv);

    retVal = LSGmainAttach( lsh_priv, g_mainloop, &lserror ); 
    if ( !retVal )
    {
        g_critical( "LSGmainAttach private returned %s", lserror.message );
        LSErrorFree(&lserror);
    }
    retVal = LSGmainAttach( lsh_pub, g_mainloop, &lserror ); 
    if ( !retVal )
    {
        g_critical( "LSGmainAttach public returned %s", lserror.message );
        LSErrorFree(&lserror);
    }
    g_main_loop_run(g_mainloop);
    g_main_loop_unref(g_mainloop);

    if (!LSUnregister( lsh_priv, &lserror)) {
        g_critical( "LSUnregister private returned %s", lserror.message );
    }
    if (!LSUnregister( lsh_pub, &lserror)) {
        g_critical( "LSUnregister public returned %s", lserror.message );
    }

	UnlockProcess();

    g_debug( "exiting %s in %s", __func__, __FILE__ );

    if (!retVal)
        return EXIT_FAILURE;
    else
        return EXIT_SUCCESS;
}
Example #23
0
int
main (int argc,
      char *argv[])
{
  gint ret = 1;
  CockpitWebServer *server = NULL;
  GOptionContext *context;
  CockpitHandlerData data;
  GTlsCertificate *certificate = NULL;
  GError *local_error = NULL;
  GError **error = &local_error;
  gchar **roots = NULL;
  gchar *cert_path = NULL;
  GMainLoop *loop = NULL;
  gchar *login_html = NULL;
  gchar *login_po_html = NULL;
  CockpitPipe *pipe = NULL;
  int outfd = -1;

  signal (SIGPIPE, SIG_IGN);
  g_setenv ("GSETTINGS_BACKEND", "memory", TRUE);
  g_setenv ("GIO_USE_PROXY_RESOLVER", "dummy", TRUE);
  g_setenv ("GIO_USE_VFS", "local", TRUE);

  /* Any interaction with a krb5 ccache should be explicit */
  g_setenv ("KRB5CCNAME", "FILE:/dev/null", TRUE);

  g_setenv ("G_TLS_GNUTLS_PRIORITY", "SECURE128:%LATEST_RECORD_VERSION:-VERS-SSL3.0:-VERS-TLS1.0", FALSE);

  memset (&data, 0, sizeof (data));

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

  if (!g_option_context_parse (context, &argc, &argv, error))
    {
      goto out;
    }

  if (opt_version)
    {
      print_version ();
      ret = 0;
      goto out;
    }

  /*
   * This process talks on stdin/stdout. However lots of stuff wants to write
   * to stdout, such as g_debug, and uses fd 1 to do that. Reroute fd 1 so that
   * it goes to stderr, and use another fd for stdout.
   */
  outfd = dup (1);
  if (outfd < 0 || dup2 (2, 1) < 1)
    {
      g_printerr ("ws couldn't redirect stdout to stderr");
      if (outfd > -1)
        close (outfd);
      goto out;
    }

  cockpit_set_journal_logging (NULL, !isatty (2));

  if (opt_local_session || opt_no_tls)
    {
      /* no certificate */
    }
  else
    {
      cert_path = cockpit_certificate_locate (FALSE, error);
      if (cert_path != NULL)
        certificate = cockpit_certificate_load (cert_path, error);
      if (certificate == NULL)
        goto out;
      g_info ("Using certificate: %s", cert_path);
    }

  loop = g_main_loop_new (NULL, FALSE);

  data.os_release = cockpit_system_load_os_release ();
  data.auth = cockpit_auth_new (opt_local_ssh);
  roots = setup_static_roots (data.os_release);

  data.branding_roots = (const gchar **)roots;
  login_html = g_strdup (DATADIR "/cockpit/static/login.html");
  data.login_html = (const gchar *)login_html;
  login_po_html = g_strdup (DATADIR "/cockpit/static/login.po.html");
  data.login_po_html = (const gchar *)login_po_html;

  server = cockpit_web_server_new (opt_address,
                                   opt_port,
                                   certificate,
                                   NULL,
                                   error);
  if (server == NULL)
    {
      g_prefix_error (error, "Error starting web server: ");
      goto out;
    }

  cockpit_web_server_set_redirect_tls (server, !cockpit_conf_bool ("WebService", "AllowUnencrypted", FALSE));

  if (cockpit_conf_string ("WebService", "UrlRoot"))
    {
      g_object_set (server, "url-root",
                    cockpit_conf_string ("WebService", "UrlRoot"),
                    NULL);
    }
  if (cockpit_web_server_get_socket_activated (server))
    g_signal_connect_swapped (data.auth, "idling", G_CALLBACK (g_main_loop_quit), loop);

  /* Ignores stuff it shouldn't handle */
  g_signal_connect (server, "handle-stream",
                    G_CALLBACK (cockpit_handler_socket), &data);

  /* External channels, ignore stuff they shouldn't handle */
  g_signal_connect (server, "handle-stream",
                    G_CALLBACK (cockpit_handler_external), &data);

  /* Don't redirect to TLS for /ping */
  g_object_set (server, "ssl-exception-prefix", "/ping", NULL);
  g_signal_connect (server, "handle-resource::/ping",
                    G_CALLBACK (cockpit_handler_ping), &data);

  /* Files that cannot be cache-forever, because of well known names */
  g_signal_connect (server, "handle-resource::/favicon.ico",
                    G_CALLBACK (cockpit_handler_root), &data);
  g_signal_connect (server, "handle-resource::/apple-touch-icon.png",
                    G_CALLBACK (cockpit_handler_root), &data);

  /* The fallback handler for everything else */
  g_signal_connect (server, "handle-resource",
                    G_CALLBACK (cockpit_handler_default), &data);

  if (opt_local_session)
    {
      struct passwd *pwd;

      if (g_str_equal (opt_local_session, "-"))
        {
          pipe = cockpit_pipe_new (opt_local_session, 0, outfd);
          outfd = -1;
        }
      else
        {
          const gchar *args[] = { opt_local_session, NULL };
          pipe = cockpit_pipe_spawn (args, NULL, NULL, COCKPIT_PIPE_FLAGS_NONE);
        }

      /* Spawn a local session as a bridge */
      pwd = getpwuid (geteuid ());
      if (!pwd)
        {
          g_printerr ("Failed to resolve current user id %u\n", geteuid ());
          goto out;
        }
      cockpit_auth_local_async (data.auth, pwd->pw_name, pipe, on_local_ready, g_object_ref (server));
      g_object_unref (pipe);
    }
  else
    {
      /* When no local bridge, start serving immediately */
      cockpit_web_server_start (server);
    }

  /* Debugging issues during testing */
#if WITH_DEBUG
  signal (SIGABRT, cockpit_test_signal_backtrace);
  signal (SIGSEGV, cockpit_test_signal_backtrace);
#endif

  g_main_loop_run (loop);

  ret = 0;

out:
  if (outfd >= 0)
    close (outfd);
  if (loop)
    g_main_loop_unref (loop);
  if (local_error)
    {
      g_printerr ("cockpit-ws: %s\n", local_error->message);
      g_error_free (local_error);
    }
  g_clear_object (&server);
  g_clear_object (&data.auth);
  if (data.os_release)
    g_hash_table_unref (data.os_release);
  g_clear_object (&certificate);
  g_free (cert_path);
  g_strfreev (roots);
  g_free (login_po_html);
  g_free (login_html);
  g_free (opt_address);
  g_free (opt_local_session);
  cockpit_conf_cleanup ();
  return ret;
}
int
main (int argc, char *argv[])
{
  App *app = &s_app;
  GError *error = NULL;
  GstBus *bus;

  gst_init (&argc, &argv);

  GST_DEBUG_CATEGORY_INIT (appsrc_playbin_debug, "appsrc-playbin", 0,
      "appsrc playbin example");

  if (argc < 2) {
    g_print ("usage: %s <filename>\n", argv[0]);
    return -1;
  }

  /* try to open the file as an mmapped file */
  app->file = g_mapped_file_new (argv[1], FALSE, &error);
  if (error) {
    g_print ("failed to open file: %s\n", error->message);
    g_error_free (error);
    return -2;
  }
  /* get some vitals, this will be used to read data from the mmapped file and
   * feed it to appsrc. */
  app->length = g_mapped_file_get_length (app->file);
  app->data = (guint8 *) g_mapped_file_get_contents (app->file);
  app->offset = 0;

  /* create a mainloop to get messages */
  app->loop = g_main_loop_new (NULL, TRUE);

  app->playbin = gst_element_factory_make ("playbin2", NULL);
  g_assert (app->playbin);

  bus = gst_pipeline_get_bus (GST_PIPELINE (app->playbin));

  /* add watch for messages */
  gst_bus_add_watch (bus, (GstBusFunc) bus_message, app);

  /* set to read from appsrc */
  g_object_set (app->playbin, "uri", "appsrc://", NULL);

  /* get notification when the source is created so that we get a handle to it
   * and can configure it */
  g_signal_connect (app->playbin, "deep-notify::source",
      (GCallback) found_source, app);

  /* go to playing and wait in a mainloop. */
  gst_element_set_state (app->playbin, GST_STATE_PLAYING);

  /* this mainloop is stopped when we receive an error or EOS */
  g_main_loop_run (app->loop);

  GST_DEBUG ("stopping");

  gst_element_set_state (app->playbin, GST_STATE_NULL);

  /* free the file */
  g_mapped_file_free (app->file);

  gst_object_unref (bus);
  g_main_loop_unref (app->loop);

  return 0;
}
Example #25
0
GST_END_TEST
GST_START_TEST (check_emit_encoded_media)
{
  guint bus_watch_id1, bus_watch_id2;
  GstBus *srcbus, *testbus;
  GstCaps *caps;

  GST_INFO ("Running test check_push_buffer");

  loop = g_main_loop_new (NULL, FALSE);

  /* Create source pipeline */
  src_pipeline = gst_pipeline_new ("src-pipeline");
  uridecodebin = gst_element_factory_make ("uridecodebin", NULL);
  appsink = gst_element_factory_make ("appsink", NULL);

  srcbus = gst_pipeline_get_bus (GST_PIPELINE (src_pipeline));

  bus_watch_id1 = gst_bus_add_watch (srcbus, gst_bus_async_signal_func, NULL);
  g_signal_connect (srcbus, "message", G_CALLBACK (bus_msg_cb), src_pipeline);
  g_object_unref (srcbus);

  gst_bin_add_many (GST_BIN (src_pipeline), uridecodebin, appsink, NULL);

  caps = gst_caps_new_any ();
  g_object_set (G_OBJECT (uridecodebin), "uri", VIDEO_PATH, "caps", caps, NULL);
  gst_caps_unref (caps);

  g_signal_connect (G_OBJECT (uridecodebin), "pad-added", G_CALLBACK (link_pad),
      appsink);

  g_object_set (appsink, "emit-signals", TRUE, NULL);
  g_signal_connect (appsink, "new-sample", G_CALLBACK (post_recv_sample), NULL);
  g_signal_connect (appsink, "eos", G_CALLBACK (appsink_eos_cb), NULL);

  /* Create test pipeline */
  test_pipeline = gst_pipeline_new ("test-pipeline");
  httpep = gst_element_factory_make ("httppostendpoint", NULL);
  g_object_set (httpep, "use-encoded-media", TRUE, NULL);

  testbus = gst_pipeline_get_bus (GST_PIPELINE (test_pipeline));

  bus_watch_id2 = gst_bus_add_watch (testbus, gst_bus_async_signal_func, NULL);
  g_signal_connect (testbus, "message", G_CALLBACK (bus_msg_cb), test_pipeline);
  g_object_unref (testbus);

  gst_bin_add (GST_BIN (test_pipeline), httpep);
  g_signal_connect (G_OBJECT (httpep), "eos", G_CALLBACK (http_eos_cb), NULL);

  /* Set pipeline to start state */
  gst_element_set_state (test_pipeline, GST_STATE_PLAYING);

  g_object_get (G_OBJECT (httpep), "http-method", &method, NULL);
  GST_INFO ("Http end point configured as %d", method);

  mark_point ();

  g_timeout_add_seconds (WAIT_TIMEOUT, timer_cb, NULL);

  g_main_loop_run (loop);

  mark_point ();

  GST_DEBUG ("Main loop stopped");

  GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (src_pipeline),
      GST_DEBUG_GRAPH_SHOW_ALL, "src_after_main_loop");

  GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (test_pipeline),
      GST_DEBUG_GRAPH_SHOW_ALL, "test_after_main_loop");

  gst_element_set_state (src_pipeline, GST_STATE_NULL);
  gst_object_unref (GST_OBJECT (src_pipeline));

  gst_element_set_state (test_pipeline, GST_STATE_NULL);
  gst_object_unref (GST_OBJECT (test_pipeline));

  g_source_remove (bus_watch_id1);
  g_source_remove (bus_watch_id2);
  g_main_loop_unref (loop);
}
Example #26
0
gint
main (gint   argc,
      gchar *argv[])
{
  GstStateChangeReturn ret;
  GstElement *pipeline, *filesrc, *decoder, *filter, *sink;
  GstElement *convert1, *convert2, *resample;
  GMainLoop *loop;
  GstBus *bus;
  guint watch_id;

  /* initialization */
  gst_init (&argc, &argv);
  loop = g_main_loop_new (NULL, FALSE);
  if (argc != 2) {
    g_print ("Usage: %s <mp3 filename>\n", argv[0]);
    return 01;
  }

  /* create elements */
  pipeline = gst_pipeline_new ("my_pipeline");

  /* watch for messages on the pipeline's bus (note that this will only
   * work like this when a GLib main loop is running) */
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  watch_id = gst_bus_add_watch (bus, bus_call, loop);
  gst_object_unref (bus);

  filesrc  = gst_element_factory_make ("filesrc", "my_filesource");
  decoder  = gst_element_factory_make ("mad", "my_decoder");

  /* putting an audioconvert element here to convert the output of the
   * decoder into a format that my_filter can handle (we are assuming it
   * will handle any sample rate here though) */
  convert1 = gst_element_factory_make ("audioconvert", "audioconvert1");

  /* use "identity" here for a filter that does nothing */
  filter   = gst_element_factory_make ("myfilter", "my_filter");

  /* there should always be audioconvert and audioresample elements before
   * the audio sink, since the capabilities of the audio sink usually vary
   * depending on the environment (output used, sound card, driver etc.) */
  convert2 = gst_element_factory_make ("audioconvert", "audioconvert2");
  resample = gst_element_factory_make ("audioresample", "audioresample");
  sink     = gst_element_factory_make ("pulsesink", "audiosink");

  if (!sink || !decoder) {
    g_print ("Decoder or output could not be found - check your install\n");
    return -1;
  } else if (!convert1 || !convert2 || !resample) {
    g_print ("Could not create audioconvert or audioresample element, "
             "check your installation\n");
    return -1;
  } else if (!filter) {
    g_print ("Your self-written filter could not be found. Make sure it "
             "is installed correctly in $(libdir)/gstreamer-1.0/ or "
             "~/.gstreamer-1.0/plugins/ and that gst-inspect-1.0 lists it. "
             "If it doesn't, check with 'GST_DEBUG=*:2 gst-inspect-1.0' for "
             "the reason why it is not being loaded.");
    return -1;
  }

  g_object_set (G_OBJECT (filesrc), "location", argv[1], NULL);

  gst_bin_add_many (GST_BIN (pipeline), filesrc, decoder, convert1, filter,
                    convert2, resample, sink, NULL);

  /* link everything together */
  if (!gst_element_link_many (filesrc, decoder, convert1, filter, convert2,
                              resample, sink, NULL)) {
    g_print ("Failed to link one or more elements!\n");
    return -1;
  }

  /* run */
  ret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
  if (ret == GST_STATE_CHANGE_FAILURE) {
    GstMessage *msg;

    g_print ("Failed to start up pipeline!\n");

    /* check if there is an error message with details on the bus */
    msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0);
    if (msg) {
      GError *err = NULL;

      gst_message_parse_error (msg, &err, NULL);
      g_print ("ERROR: %s\n", err->message);
      g_error_free (err);
      gst_message_unref (msg);
    }
    return -1;
  }

  g_main_loop_run (loop);

  /* clean up */
  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (pipeline);
  g_source_remove (watch_id);
  g_main_loop_unref (loop);

  return 0;
}
Example #27
0
int
main (int argc, char **argv)
{
  GError *err = NULL;
  GstDiscoverer *dc;
  gint timeout = 10;
  GOptionEntry options[] = {
    {"async", 'a', 0, G_OPTION_ARG_NONE, &async,
        "Run asynchronously", NULL},
    {"silent", 's', 0, G_OPTION_ARG_NONE, &silent,
        "Don't output the information structure", NULL},
    {"timeout", 't', 0, G_OPTION_ARG_INT, &timeout,
        "Specify timeout (in seconds, default 10)", "T"},
    /* {"elem", 'e', 0, G_OPTION_ARG_NONE, &elem_seek, */
    /*     "Seek on elements instead of pads", NULL}, */
    {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
        "Verbose properties", NULL},
    {NULL}
  };
  GOptionContext *ctx;

  if (!g_thread_supported ())
    g_thread_init (NULL);

  ctx =
      g_option_context_new
      ("- discover files synchronously with GstDiscoverer");
  g_option_context_add_main_entries (ctx, options, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());

  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", err->message);
    exit (1);
  }

  g_option_context_free (ctx);

  if (argc < 2) {
    g_print ("usage: %s <uris>\n", argv[0]);
    exit (-1);
  }

  dc = gst_discoverer_new (timeout * GST_SECOND, &err);
  if (G_UNLIKELY (dc == NULL)) {
    g_print ("Error initializing: %s\n", err->message);
    exit (1);
  }

  if (async == FALSE) {
    gint i;
    for (i = 1; i < argc; i++)
      process_file (dc, argv[i]);
  } else {
    PrivStruct *ps = g_new0 (PrivStruct, 1);
    GMainLoop *ml = g_main_loop_new (NULL, FALSE);

    ps->dc = dc;
    ps->argc = argc;
    ps->argv = argv;

    /* adding uris will be started when the mainloop runs */
    g_idle_add ((GSourceFunc) _run_async, ps);

    /* connect signals */
    g_signal_connect (dc, "discovered", G_CALLBACK (_new_discovered_uri), NULL);
    g_signal_connect (dc, "finished", G_CALLBACK (_discoverer_finished), ml);

    gst_discoverer_start (dc);
    /* run mainloop */
    g_main_loop_run (ml);

    gst_discoverer_stop (dc);
    g_free (ps);
    g_main_loop_unref (ml);
  }
  g_object_unref (dc);

  return 0;
}
Example #28
0
int
main(int argc, char *argv[])
{
  GOptionContext *context;
  GError *error = NULL;

  memset (&the_rebinder, 0, sizeof (Rebinder));

  g_type_init ();

  /* Options */
  context = g_option_context_new ("- key rebinder");

  g_option_context_add_main_entries (context, entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_print ("Failed to parse options: %s\n", error->message);
      g_error_free (error);
      return EXIT_FAILURE;
    }

#ifdef REBINDER_ENABLE_DEBUG
  rebinder_debug_init ();
#endif

  if (opt_configure)
    {
      /* lauched in configuration mode */

      if (request_dbus_name (MEX_REBINDER_CONFIGURE_DBUS_INTERFACE) == FALSE)
        {
          g_message ("Could not request DBus name");
          return EXIT_SUCCESS;
        }

      clutter_init (&argc, &argv);

      /* we expect to be build against clutter-glx */
      the_rebinder.dpy = clutter_x11_get_default_display ();

      the_rebinder.config = rebinder_configure (&the_rebinder,
						NULL,
                                                is_evdev_enabled (),
                                                is_fullscreen_enabled ());

      clutter_main ();

      rebinder_configure_free (the_rebinder.config);
    }
  else
    {
      /* launched in daemon mode */
      MexRebinder *rebinder;
      gboolean registered;

      rebinder = mex_rebinder_new ();
      registered = mex_rebinder_register (rebinder,
                                          MEX_REBINDER_DBUS_INTERFACE,
                                          MEX_REBINDER_DBUS_PATH,
                                          &error);
      if (registered == FALSE)
        {
          const gchar prefix[] = "Could not request DBus name";

          if (error)
            g_message ("%s: %s", prefix, error->message);
          else
            g_message ("%s", prefix);

          return EXIT_FAILURE;
        }

      g_signal_connect (rebinder, "quit",
                        G_CALLBACK (on_rebinder_quit), &the_rebinder);

      the_rebinder.dpy = XOpenDisplay (NULL);
      if (G_UNLIKELY (the_rebinder.dpy == NULL))
        {
          g_error ("Could not open display");
          return EXIT_FAILURE;
        }

      the_rebinder.fake = fakekey_init (the_rebinder.dpy);
      if (G_UNLIKELY (the_rebinder.fake == NULL))
        {
          g_error ("Could not initialize fakekey");
          return EXIT_FAILURE;
        }

      if (opt_no_daemon == FALSE)
        daemon (0, 0);

      signal (SIGINT, on_int_term_signaled);
      signal (SIGTERM, on_int_term_signaled);

      the_rebinder.original_bindings =
        g_array_new (FALSE, FALSE, sizeof (Binding));

      /* listens to evdev events and setup everything needed */
      if (is_evdev_enabled ())
        {
          the_rebinder.evdev_manager = rebinder_evdev_manager_get_default ();
          rebinder_evdev_manager_set_key_notifier (the_rebinder.evdev_manager,
                                                   on_evdev_key_pressed,
                                                   &the_rebinder);
          the_rebinder.evdev_bindings =
            g_ptr_array_new_with_free_func (free_binding);
        }

      load_bindings (&the_rebinder);
      setup_monitor (&the_rebinder);

      the_rebinder.mainloop = g_main_loop_new (NULL, TRUE);
      g_main_loop_run (the_rebinder.mainloop);

      restore_bindings (&the_rebinder);

      g_main_loop_unref (the_rebinder.mainloop);
      g_object_unref (the_rebinder.monitor);
    }

  return EXIT_SUCCESS;
}
Example #29
0
static void
test_pipeline (const char *pipeline)
{
  GstElement *bin, *sink;
  GstPad *pad, *sinkpad;
  GstBus *bus;
  GError *error = NULL;
  GMainLoop *loop;
  GstPadLinkReturn linkret;
  guint bus_watch = 0;

  bin = gst_parse_launch (pipeline, &error);
  fail_unless (bin != NULL, "Error parsing pipeline: %s",
      error ? error->message : "(invalid error)");
  pad = gst_bin_find_unlinked_pad (GST_BIN (bin), GST_PAD_SRC);
  fail_unless (pad != NULL, "Could not locate free src pad");

  /* connect the fake sink */
  sink = gst_element_factory_make ("fakesink", "fake_sink");
  fail_unless (sink != NULL, "Could create fakesink");
  fail_unless (gst_bin_add (GST_BIN (bin), sink), "Could not insert fakesink");
  sinkpad = gst_element_get_static_pad (sink, "sink");
  fail_unless (sinkpad != NULL, "Could not get fakesink src pad");

  linkret = gst_pad_link (pad, sinkpad);
  fail_unless (GST_PAD_LINK_SUCCESSFUL (linkret),
      "Could not link to fake sink");
  gst_object_unref (sinkpad);

  /* run until we receive EOS */
  loop = g_main_loop_new (NULL, FALSE);
  bus = gst_element_get_bus (bin);
  bus_watch = gst_bus_add_watch (bus, (GstBusFunc) eos_watch, loop);
  gst_object_unref (bus);

  start_pipeline (bin, pad);
  g_main_loop_run (loop);

  /* we're EOS now; make sure oggmux out caps have stream headers on them */
  {
    GstStructure *s;
    GstCaps *muxcaps;

    muxcaps = gst_pad_get_negotiated_caps (sinkpad);
    fail_unless (muxcaps != NULL);
    s = gst_caps_get_structure (muxcaps, 0);
    fail_unless (gst_structure_has_name (s, "application/ogg"));
    fail_unless (gst_structure_has_field (s, "streamheader"));
    fail_unless (gst_structure_has_field_typed (s, "streamheader",
            GST_TYPE_ARRAY));
    gst_caps_unref (muxcaps);
  }

  stop_pipeline (bin, pad);

  /* clean up */
  g_main_loop_unref (loop);
  g_source_remove (bus_watch);
  gst_object_unref (pad);
  gst_object_unref (bin);
}
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *err = NULL;
	guint signal;

	set_version();

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

	if (g_option_context_parse(context, &argc, &argv, &err) == FALSE) {
		if (err != NULL) {
			g_printerr("%s\n", err->message);
			g_error_free(err);
		} else
			g_printerr("An unknown error occurred\n");

		exit(EXIT_FAILURE);
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(EXIT_SUCCESS);
	}

	signal = setup_signalfd();
	if (!signal)
		return EXIT_FAILURE;

	if (option_dbg || option_mgmt_dbg)
		__btd_log_init("*", 0);
	else
		__btd_log_init(NULL, 0);

	if (!set_capabilities()) {
		__btd_log_cleanup();
		g_source_remove(signal);
		return EXIT_FAILURE;
	}

	quit_timeout = g_timeout_add_seconds(STARTUP_GRACE_SECONDS,
							quit_eventloop, NULL);
	if (quit_timeout == 0) {
		error("Failed to init startup timeout");
		__btd_log_cleanup();
		g_source_remove(signal);
		return EXIT_FAILURE;
	}

	if (!bt_bluetooth_start(option_index, option_mgmt_dbg, adapter_ready)) {
		__btd_log_cleanup();
		g_source_remove(quit_timeout);
		g_source_remove(signal);
		return EXIT_FAILURE;
	}

	/* Use params: mtu = 0, flags = 0 */
	start_sdp_server(0, 0);

	DBG("Entering main loop");

	event_loop = g_main_loop_new(NULL, FALSE);

	g_main_loop_run(event_loop);

	g_source_remove(signal);

	if (quit_timeout > 0)
		g_source_remove(quit_timeout);

	cleanup_services();

	stop_sdp_server();
	bt_bluetooth_cleanup();
	g_main_loop_unref(event_loop);

	/* If no adapter was initialized, hal_ipc is NULL */
	if (hal_ipc) {
		ipc_unregister(hal_ipc, HAL_SERVICE_ID_CORE);
		ipc_cleanup(hal_ipc);
	}

	info("Exit");

	__btd_log_cleanup();

	free(config_vendor);
	free(config_model);
	free(config_name);
	free(config_serial);
	free(config_fw_rev);
	free(config_hw_rev);

	return EXIT_SUCCESS;
}