Example #1
0
/** main function
 */
int
main (int argc, char *argv[])
{
	gchar *address = "0.0.0.0";
	gchar *service = "8080";
	char *docrootphys = NULL;
	gchar *cgiroot = NULL;
	char *cgirootphys = NULL;
	gchar *sysadmin = "server.json";
	gchar *pidfile = NULL;
	gchar *device = NULL;
	GstHTTPServer *server;
	GstHTTPMediaMapping *mapping;
	GstHTTPMedia *media;
	GError *err = NULL;
	GOptionContext *ctx;
	gchar *configfile = NULL;
	gchar *input_dev = NULL;
	int i;

	GOptionEntry options[] = {
		{"config", 'f', 0, G_OPTION_ARG_STRING, &configfile, "config file", "file"},
		{"address", 'a', 0, G_OPTION_ARG_STRING, &address, "address to listen on", "addr"},
		{"service", 's', 0, G_OPTION_ARG_STRING, &service, "service to listen on", "service"},
		{"docroot", 'd', 0, G_OPTION_ARG_STRING, &docroot, "root directory for www", "path"},
		{"cgiroot", 'c', 0, G_OPTION_ARG_STRING, &cgiroot, "root directory for cgi-bin", "path"},
		{"sysadmin", 0, 0, G_OPTION_ARG_STRING, &sysadmin, "path to sysadmin", "path"},
		{"pidfile", 'p', 0, G_OPTION_ARG_STRING, &pidfile, "file to store pid", "filename"},
		{"device", 0, 0, G_OPTION_ARG_STRING, &device, "video device", "filename"},
		{"inputdev", 0, 0, G_OPTION_ARG_STRING, &input_dev, "device file for input", "filename"},
		{NULL}
	};

	printf("gst-mjpeg-streamer v%s\n", VERSION);

	/* must init the threading system before using any other glib function
	 */
	if (!g_thread_supported())
		g_thread_init(NULL);

	GST_DEBUG_CATEGORY_INIT (gst_http_debug, "gst_http", 0, "gst_http");

	ctx = g_option_context_new ("gst-httpd");
	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", GST_STR_NULL(err->message));
		exit (1);
	}
	
	/* install signal handler */ 
	signal(SIGINT, sighandler);
	signal(SIGSEGV, sighandler);
	signal(SIGPIPE, SIG_IGN);

	/* init gstreamer and create mainloop */
	gst_init (&argc, &argv);
	loop = g_main_loop_new (NULL, FALSE);

	/* create a server instance */
	server = gst_http_server_new ();
	mapping = gst_http_server_get_media_mapping (server);
	gst_http_server_set_address (server, address);
	gst_http_server_set_service (server, service);

	/* if standalone video device - dynamically create configuration */
	if (device) {
		v4l2_config_device(device, mapping, input_dev);
	}

	/* parse configfile */
	if (configfile) {
		parse_config(server, configfile, input_dev);
	}

	/* parse commandline arguments */
	i = 1;
	while ( (argc - i) >= 2) {
		media = gst_http_media_new_pipeline ("", argv[i+1], input_dev);
		gst_http_media_mapping_add (mapping, argv[i], media);
		i+=2;
	}

	if (pidfile) {
  	FILE *fp = fopen(pidfile, "w+");
		if (fp) {
			fprintf(fp, "%d", getpid());
			fclose(fp);
		} else {
			perror ("open failed");
		}
	}

	/* add custom URL handlers */
#ifdef V4L2_CTLS
	media = gst_http_media_new_handler ("Video Controls", v4l2_config, server);
	gst_http_media_mapping_add (mapping, "v4l2cfg.json", media);
#endif
	if (sysadmin) {
		media = gst_http_media_new_handler ("Server Status", server_status, server);
		gst_http_media_mapping_add (mapping, sysadmin, media);
	}
#ifdef CGI_PATH
	if (cgiroot) {
			cgirootphys = realpath(cgiroot, NULL);
			if (cgirootphys) {
				media = gst_http_media_new_handler ("CGI Handler", cgi_handoff,
					cgirootphys);
				gst_http_media_mapping_add (mapping, CGI_PATH "/*", media);
			} else {
				g_print ("Error: cgiroot '%s' not found\n", cgiroot);
			}
	}
#endif
#ifdef LOCAL_PAGES
	/* default to a page handler that serves from docroot */
	if (docroot) {
			docrootphys = realpath(docroot, NULL);
			if (docrootphys) {
				media = gst_http_media_new_handler ("Page Handler", serve_page,
					docrootphys);
				gst_http_media_mapping_add (mapping, "*", media);
			} else {
				g_print ("Error: docroot '%s' not found\n", docroot);
			}
	}
#endif // #ifdef LOCAL_PAGES

	/* make sure we have a valid configuration */
	if (gst_http_media_mapping_num_mappings(mapping) == 0) {
		g_print ("Error: no streams defined\n");
		g_print ("%s\n", g_option_context_get_help(ctx, 0, NULL));
		return -1;
	}
	g_object_unref(mapping);
	g_option_context_free(ctx);

	/* attach the server to the default maincontext */
	if (!gst_http_server_attach (server, NULL)) {
		fprintf(stderr, "Failed to attach server\n");
		exit(1);
	}

#ifdef SYS_STAT
	g_timeout_add(1000, sysstat_timer, NULL);
#endif

	/* start serving */
	g_print("%d: Listening on %s:%s\n", getpid(), address, service);
	g_main_loop_run (loop);

	GST_DEBUG("cleaning up...");
	gst_http_server_detach (server);
	g_object_unref (server);

	if (docrootphys)
		free(docrootphys);

	g_main_loop_unref(loop);

	gst_deinit();

	return 0;
}
Example #2
0
int
main (int   argc,
      char *argv[])
{
	TrackerConfig *config;
	TrackerController *controller;
	GOptionContext *context;
	GMainLoop *loop;
	GError *error = NULL;
	gchar *log_filename;
	guint shutdown_timeout;

	/* Set up locale */
	setlocale (LC_ALL, "");

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

	/* Translators: this message will appear immediately after the
	 * usage string - Usage: COMMAND <THIS_MESSAGE>
	 */
	context = g_option_context_new (_("- start the tracker writeback service"));

	g_option_context_add_main_entries (context, entries, NULL);
	g_option_context_parse (context, &argc, &argv, &error);
	g_option_context_free (context);

	if (version) {
		g_print ("\n" ABOUT "\n" LICENSE "\n");
		return EXIT_SUCCESS;
	}

	/* Initialize logging */
	config = tracker_config_new ();

	if (verbosity > -1) {
		tracker_config_set_verbosity (config, verbosity);
	}

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

	sanity_check_option_values (config);

	if (disable_shutdown) {
		shutdown_timeout = 0;
	} else {
		shutdown_timeout = QUIT_TIMEOUT;
	}

	controller = tracker_controller_new (shutdown_timeout, &error);

	if (error) {
		g_critical ("Error creating controller: %s", error->message);
		g_error_free (error);
		return EXIT_FAILURE;
	}

	g_message ("Main thread is: %p", g_thread_self ());

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


	tracker_log_shutdown ();

	g_object_unref (controller);

	g_main_loop_unref (loop);

	g_object_unref (config);

	return EXIT_SUCCESS;
}
Example #3
0
int
main (int argc, char **argv)
{
  int was_result_written = 0;
  int pass;
  /* This was to move gslice area out of the
     tree of Marpa calls during memory debugging */
  /* void* dummy = g_slice_alloc(42); */
  /* g_slice_free1(42, dummy); */
  GError *error = NULL;
  GOptionContext *context;
  char *test_string;

  context = g_option_context_new ("- test balanced parens");
  g_option_context_add_main_entries (context, entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_print ("option parsing failed: %s\n", error->message);
      exit (1);
    }

  if (string)
    {
      /* Never freed */
      test_string = string;
      string_length = strlen (test_string);
      printf ("Target is \"%s\", length=%d\n", test_string, string_length);
    }
  else if (string_length < 10)
    {
      fprintf (stderr, "String length is %d, must be at least 10\n",
	       string_length);
      exit (1);
    }
  else
    {
      /* Never freed */
      test_string = gen_example_string (string_length);
      printf ("Target at end, length=%d\n", string_length);
    }

  for (pass = 0; pass < repeats; pass++)
    {
      int location;
      int start_of_match = -1;
      int end_of_match = -1;
      Marpa_Symbol_ID s_top, s_prefix, s_first_balanced;
      Marpa_Symbol_ID s_prefix_char, s_balanced;
      Marpa_Symbol_ID s_balanced_sequence;
      struct marpa_g *g;
      struct marpa_r *r;
      void *result;
      /* Longest rule is 4 symbols */
      Marpa_Symbol_ID rhs[4];

      g = marpa_g_new ();
      s_top = marpa_symbol_new (g);
      s_prefix = marpa_symbol_new (g);
      s_first_balanced = marpa_symbol_new (g);
      s_prefix_char = marpa_symbol_new (g);
      s_balanced = marpa_symbol_new (g);
      s_lparen = marpa_symbol_new (g);
      s_rparen = marpa_symbol_new (g);
      s_balanced_sequence = marpa_symbol_new (g);
      rhs[0] = s_prefix;
      rhs[1] = s_first_balanced;
      marpa_rule_new (g, s_top, rhs, 2);
      marpa_sequence_new (g, s_prefix, s_prefix_char, -1, 0, 0);
      rhs[0] = s_balanced;
      marpa_rule_new (g, s_first_balanced, rhs, 1);
      rhs[0] = s_lparen;
      rhs[1] = s_rparen;
      marpa_rule_new (g, s_balanced, rhs, 2);
      rhs[0] = s_lparen;
      rhs[1] = s_balanced_sequence;
      rhs[2] = s_rparen;
      marpa_rule_new (g, s_balanced, rhs, 3);
      marpa_sequence_new (g, s_balanced_sequence, s_balanced, -1, 1, 0);
      marpa_symbol_is_terminal_set (g, s_prefix_char, 1);
      marpa_symbol_is_terminal_set (g, s_lparen, 1);
      marpa_symbol_is_terminal_set (g, s_rparen, 1);
      marpa_start_symbol_set (g, s_top);
      result = marpa_precompute (g);
      if (!result)
	{
	  puts (marpa_g_error (g));
	  exit (1);
	}
      {
	int AHFA_state_count = marpa_AHFA_state_count (g);
	int ahfa_id;
	first_balanced_completion = -1;
	for (ahfa_id = 0; ahfa_id < AHFA_state_count; ahfa_id++)
	  {
	    unsigned int aim_ix;
	    unsigned int aim_count = marpa_AHFA_state_item_count (g, ahfa_id);
	    for (aim_ix = 0; aim_ix < aim_count; aim_ix++)
	      {
		int aim_id = marpa_AHFA_state_item (g, ahfa_id, aim_ix);
		int position = marpa_AHFA_item_position (g, aim_id);
		if (position == -1)
		  {
		    Marpa_Rule_ID rule = marpa_AHFA_item_rule (g, aim_id);
		    Marpa_Symbol_ID lhs = marpa_rule_lhs (g, rule);
		    if (lhs == s_first_balanced)
		      {
			if (first_balanced_completion != -1)
			  {
			    fprintf (stderr,
				     "First balanced completion is not unique");
			    exit (1);
			  }
			first_balanced_completion = ahfa_id;
			break;
		      }
		  }
	      }
	  }
      }
      r = create_recce (g);
      for (location = 0; location <= string_length; location++)
	{
	  int origin, status;
	  Marpa_Symbol_ID paren_token =
	    test_string[location] == '(' ? s_lparen : s_rparen;
	  status = marpa_alternative (r, paren_token, 0, 1);
	  if (status < -1)
	    fatal_r_error ("marpa alternative", r, status);
	  status = marpa_alternative (r, s_prefix_char, 0, 1);
	  if (status < -1)
	    fatal_r_error ("marpa alternative", r, status);
	  status = marpa_earleme_complete (r);
	  if (status < -1)
	    fatal_r_error ("marpa_earleme_complete", r, status);
	  /* If none of the alternatives were accepted, we are done */
	  origin = at_first_balanced_completion (r, location + 1);
	  if (origin >= 0)
	    {
	      start_of_match = origin;
	      end_of_match = location + 1;
	      break;
	    }
	}
      if (start_of_match < 0)
	{
	  printf ("No balanced parens\n");
	}
      while (++location < string_length)
	{
	  int origin, status, earleme_complete_status;
	  Marpa_Symbol_ID paren_token =
	    test_string[location] == '(' ? s_lparen : s_rparen;
	  status = marpa_alternative (r, paren_token, 0, 1);
	  if (status == -1)
	    break;
	  if (status < -1)
	    fatal_r_error ("marpa alternative", r, status);
	  earleme_complete_status = marpa_earleme_complete (r);
	  if (earleme_complete_status < -1)
	    fatal_r_error ("marpa_earleme_complete", r,
			   earleme_complete_status);
	  origin = at_first_balanced_completion (r, location + 1);
	  if (origin >= 0 && origin < start_of_match)
	    {
	      start_of_match = origin;
	      end_of_match = location + 1;
	      break;
	    }
	  if (earleme_complete_status == 0)
	    break;
	}
      if (!was_result_written)
	{
	  printf ("Match at %d-%d\n", start_of_match, end_of_match);
	  was_result_written++;
	}
      marpa_r_free (r);
      marpa_g_free (g);
      g = NULL;
    }
  exit (0);
}
Example #4
0
int
main (int    argc,
      char **argv)
{
  GOptionContext *context;
  GError         *error = NULL;
  const gchar    *abort_message;
  gchar          *basename;
  gint            i;

#if defined (__GNUC__) && defined (_WIN64)
  /* mingw-w64, at least the unstable build from late July 2008,
   * starts subsystem:windows programs in main(), but passes them
   * bogus argc and argv. __argc and __argv are OK, though, so just
   * use them.
   */
  argc = __argc;
  argv = __argv;
#endif

#ifdef G_OS_WIN32
  /* Reduce risks */
  {
    typedef BOOL (WINAPI *t_SetDllDirectoryA) (LPCSTR lpPathName);
    t_SetDllDirectoryA p_SetDllDirectoryA;

    p_SetDllDirectoryA = GetProcAddress (GetModuleHandle ("kernel32.dll"),
					 "SetDllDirectoryA");
    if (p_SetDllDirectoryA)
      (*p_SetDllDirectoryA) ("");
  }
#ifndef _WIN64
  {
    typedef BOOL (WINAPI *t_SetProcessDEPPolicy) (DWORD dwFlags);
    t_SetProcessDEPPolicy p_SetProcessDEPPolicy;

    p_SetProcessDEPPolicy = GetProcAddress (GetModuleHandle ("kernel32.dll"),
					    "SetProcessDEPPolicy");
    if (p_SetProcessDEPPolicy)
      (*p_SetProcessDEPPolicy) (PROCESS_DEP_ENABLE|PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION);
  }
#endif
#endif

#ifdef GIMP_UNSTABLE
  gimp_open_console_window ();
#endif

  gimp_init_malloc ();

  gimp_env_init (FALSE);

  gimp_log_init ();

  gimp_init_i18n ();

  g_set_application_name (GIMP_NAME);

  basename = g_path_get_basename (argv[0]);
  g_set_prgname (basename);
  g_free (basename);

  /* Check argv[] for "--verbose" first */
  for (i = 1; i < argc; i++)
    {
      const gchar *arg = argv[i];

      if (arg[0] != '-')
        continue;

      if ((strcmp (arg, "--verbose") == 0) || (strcmp (arg, "-v") == 0))
        {
          be_verbose = TRUE;
        }
    }

  /* Check argv[] for "--no-interface" before trying to initialize gtk+. */
  for (i = 1; i < argc; i++)
    {
      const gchar *arg = argv[i];

      if (arg[0] != '-')
        continue;

      if ((strcmp (arg, "--no-interface") == 0) || (strcmp (arg, "-i") == 0))
        {
          no_interface = TRUE;
        }
      else if ((strcmp (arg, "--version") == 0) || (strcmp (arg, "-v") == 0))
        {
          gimp_show_version_and_exit ();
        }
#if defined (G_OS_WIN32) && !defined (GIMP_CONSOLE_COMPILATION)
      else if ((strcmp (arg, "--help") == 0) ||
               (strcmp (arg, "-?") == 0) ||
               (strncmp (arg, "--help-", 7) == 0))
        {
          gimp_open_console_window ();
        }
#endif
    }

#ifdef GIMP_CONSOLE_COMPILATION
  no_interface = TRUE;
#endif

  context = g_option_context_new (_("[FILE|URI...]"));
  g_option_context_set_summary (context, GIMP_NAME);

  g_option_context_add_main_entries (context, main_entries, GETTEXT_PACKAGE);

  app_libs_init (context, no_interface);

  if (! g_option_context_parse (context, &argc, &argv, &error))
    {
      if (error)
        {
          gimp_open_console_window ();
          g_print ("%s\n", error->message);
          g_error_free (error);
        }
      else
        {
          g_print ("%s\n",
                   _("Picman could not initialize the graphical user interface.\n"
                     "Make sure a proper setup for your display environment "
                     "exists."));
        }

      app_exit (EXIT_FAILURE);
    }

  if (no_interface || be_verbose || console_messages || batch_commands != NULL)
    gimp_open_console_window ();

  if (no_interface)
    new_instance = TRUE;

#ifndef GIMP_CONSOLE_COMPILATION
  if (! new_instance && gimp_unique_open (filenames, as_new))
    {
      if (be_verbose)
	g_print ("%s\n",
		 _("Another Picman instance is already running."));

      gdk_notify_startup_complete ();

      return EXIT_SUCCESS;
    }
#endif

  abort_message = sanity_check ();
  if (abort_message)
    app_abort (no_interface, abort_message);

  gimp_init_signal_handlers (stack_trace_mode);

  app_run (argv[0],
           filenames,
           system_gimprc,
           user_gimprc,
           session_name,
           batch_interpreter,
           batch_commands,
           as_new,
           no_interface,
           no_data,
           no_fonts,
           no_splash,
           be_verbose,
           use_shm,
           use_cpu_accel,
           console_messages,
           use_debug_handler,
           stack_trace_mode,
           pdb_compat_mode);

  g_option_context_free (context);

  return EXIT_SUCCESS;
}
Example #5
0
int
main (int argc,
      char *argv[])
{
  GOptionContext *context;
  gchar *user = NULL;
  gchar *password = NULL;
  gchar *bind = NULL;
  GError *error = NULL;
  gboolean verbose = FALSE;
  gboolean broken_auth = FALSE;
  gboolean multi_step = FALSE;
  gint port = 0;
  int ret;

  GOptionEntry entries[] = {
    { "user", 0, 0, G_OPTION_ARG_STRING, &user, "User name to expect", "name" },
    { "password", 0, 0, G_OPTION_ARG_STRING, &password, "Password to expect", "xxx" },
    { "bind", 0, 0, G_OPTION_ARG_STRING, &bind, "Address to bind to", "addr" },
    { "port", 'p', 0, G_OPTION_ARG_INT, &port, "Port to bind to", "NN" },
    { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Verbose info", NULL },
    { "multi-step", 'm', 0, G_OPTION_ARG_NONE, &multi_step, "Multi Step Auth", NULL },
    { "broken-auth", 0, 0, G_OPTION_ARG_NONE, &broken_auth, "Break authentication", NULL },
    { NULL }
  };

#ifdef __linux
#include <sys/prctl.h>
  prctl (PR_SET_PDEATHSIG, 15);
#endif

  if (signal (SIGPIPE, SIG_IGN) == SIG_ERR)
    g_assert_not_reached ();

  ssh_init ();

  context = g_option_context_new ("- mock ssh server");
  g_option_context_add_main_entries (context, entries, "");
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("mock-sshd: %s\n", error->message);
      g_error_free (error);
      ret = 2;
    }
  else if (argc != 1)
    {
      g_printerr ("mock-sshd: extra arguments on command line\n");
      ret = 2;
    }
  else
    {
      if (broken_auth)
        auth_methods = SSH_AUTH_METHOD_HOSTBASED;
      if (verbose)
        ssh_set_log_level (SSH_LOG_PROTOCOL);
      ret = mock_ssh_server (bind, port, user, password, multi_step);
    }

  g_option_context_free (context);
  g_free (password);
  g_free (user);
  g_free (bind);

  ssh_finalize ();
  return ret;
}
Example #6
0
int main(int argc, char *argv[])
{
    struct cmd *c;

#if !GLIB_CHECK_VERSION(2, 36, 0)
    g_type_init ();
#endif

    config_dir = DEFAULT_CONFIG_DIR;

    if (argc == 1) {
        usage();
        exit(1);
    }

    GError *error = NULL;
    GOptionContext *context;

    context = g_option_context_new (NULL);
    g_option_context_add_main_entries (context, entries, NULL);
    g_option_context_set_ignore_unknown_options (context, TRUE);
    if (!g_option_context_parse (context, &argc, &argv, &error))
    {
        g_print ("option parsing failed: %s\n", error->message);
        exit (1);
    }

    if (print_version) {
        show_version();
        exit(0);
    }

    if (argc <= 1) {
        usage();
        exit(1);
    }

    c = getcmd (argv[1]);
    if (c == NULL) {
        usage();
        exit(1);
    }
    
    g_log_set_default_handler (ccnet_servtool_log, NULL);

    client = ccnet_client_new ();
    if ( (ccnet_client_load_confdir(client, central_config_dir, config_dir)) < 0 ) {
        fprintf (stderr, "Read config dir error\n");
        exit(1);
    }

    if (ccnet_client_connect_daemon (client, CCNET_CLIENT_SYNC) < 0)
    {
        fprintf(stderr, "Connect to server fail: %s\n", strerror(errno));
        exit(1);
    }

    argc -= 2;
    argv += 2;
    c->handler (argc, argv);

    ccnet_client_disconnect_daemon (client);

    return 0;
}
Example #7
0
/*           Process command arguments           */
GList *
process_args (int argc, char *argv[],
    gboolean * blind, gboolean * fullscreen, gboolean * hide, gboolean * loop,
    gboolean * secret, gchar ** suburi, gboolean * tags,
    GOptionContext * context)
{
  gboolean recent = FALSE, version = FALSE;
  guint c, index, pos = 0;
  GList *uri_list = NULL;

  GOptionEntry entries[] = {
    {"blind", 'b', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, blind,
        "Blind mode", NULL},
    {"fullscreen", 'f', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, fullscreen,
        "Fullscreen mode", NULL},
    {"hide-controls", 'h', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, hide,
        "Hide on screen controls", NULL},
    {"loop", 'l', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, loop,
        "Looping mode", NULL},
    {"media-info", 'i', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, tags,
        "Print media information", NULL},
    {"recent", 'r', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, &recent,
        "Show recently viewed", NULL},
    {"secret", 's', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, secret,
        "Views not saved in recently viewed history", NULL},
    {"subtitles", 't', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_FILENAME,
        suburi, "Use this subtitle file", NULL},
    {"version", 'v', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, &version,
        "Shows snappy's version", NULL},
    {NULL}
  };
  GError *err = NULL;

  g_option_context_add_main_entries (context, entries, NULL);
  g_option_context_add_group (context, gst_init_get_option_group ());
  g_option_context_add_group (context, clutter_get_option_group ());

  /* Check command arguments and update entry variables */
  if (!g_option_context_parse (context, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", err->message);
    g_error_free (err);
    return NULL;
  }

  /* Recently viewed uris */
  if (recent) {
    gchar **recent = NULL;
    recent = get_recently_viewed ();

    if (recent) {
      g_print ("These are the recently viewed URIs: \n\n");

      for (c = 0; recent[c] != NULL; c++) {
        if (c < 9)
          g_print ("0%d: %s \n", c + 1, recent[c]);
        else
          g_print ("%d: %s \n", c + 1, recent[c]);
      }
    } else {
      g_print ("ERROR: Can't find history of recently viewed URIs\n");
    }

    return NULL;
  }

  /* Show snappy's version */
  if (version) {
    g_print ("snappy version %s\n", VERSION);
    return NULL;
  }

  /* Check that at least one URI has been introduced */
  if (argc > 1) {
    /* Save uris in the file glist */
    for (index = 1; index < argc; index++) {
      g_print ("Adding file: %s\n", argv[index]);
      uri_list = g_list_append (uri_list, clean_uri (argv[index]));
      pos++;
    }
  } else {
    /* If no files passed by user display help */
    g_print ("Opening snappy without content.\n\n");
    g_print ("%s", g_option_context_get_help (context, TRUE, NULL));
  }

  return uri_list;
}
Example #8
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *err = NULL;
	guint signal;

	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;
	}

	bluetooth_start_timeout = g_timeout_add_seconds(STARTUP_GRACE_SECONDS,
							quit_eventloop, NULL);
	if (bluetooth_start_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(bluetooth_start_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 (bluetooth_start_timeout > 0)
		g_source_remove(bluetooth_start_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();

	return EXIT_SUCCESS;
}
Example #9
0
int
main (int argc, char *argv[])
{
	GOptionContext *context;
	GError *error = NULL;
	TrackerExtract *extract;
	TrackerDecorator *decorator;
	TrackerExtractController *controller;
	gchar *log_filename = NULL;
	GMainLoop *my_main_loop;

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

	/* Translators: this message will appear immediately after the  */
	/* usage string - Usage: COMMAND [OPTION]... <THIS_MESSAGE>     */
	context = g_option_context_new (_("- Extract file meta data"));

	g_option_context_add_main_entries (context, entries, NULL);
	g_option_context_parse (context, &argc, &argv, &error);

	if (!filename && mime_type) {
		gchar *help;

		g_printerr ("%s\n\n",
		            _("Filename and mime type must be provided together"));

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

		return EXIT_FAILURE;
	}

	if (force_internal_extractors && force_module) {
		gchar *help;

		g_printerr ("%s\n\n",
		            _("Options --force-internal-extractors and --force-module can't be used together"));

		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);

	if (version) {
		g_print ("\n" ABOUT "\n" LICENSE "\n");
		return EXIT_SUCCESS;
	}

	initialize_signal_handler ();

	g_set_application_name ("tracker-extract");

	setlocale (LC_ALL, "");

	config = tracker_config_new ();

	/* Set conditions when we use stand alone settings */
	if (filename) {
		return run_standalone (config);
	}

	/* Initialize subsystems */
	initialize_directories ();

	/* Extractor command line arguments */
	if (verbosity > -1) {
		tracker_config_set_verbosity (config, verbosity);
	}

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

	sanity_check_option_values (config);

	/* This makes sure we don't steal all the system's resources */
	initialize_priority_and_scheduling (tracker_config_get_sched_idle (config),
	                                    tracker_db_manager_get_first_index_done () == FALSE);
	tracker_memory_setrlimits ();

	extract = tracker_extract_new (TRUE,
	                               force_internal_extractors,
	                               force_module);

	if (!extract) {
		g_object_unref (config);
		tracker_log_shutdown ();
		return EXIT_FAILURE;
	}

	decorator = tracker_extract_decorator_new (extract, NULL, &error);

	if (error) {
		g_critical ("Could not start decorator: %s\n", error->message);
		g_object_unref (config);
		tracker_log_shutdown ();
		return EXIT_FAILURE;
	}

#ifdef THREAD_ENABLE_TRACE
	g_debug ("Thread:%p (Main) --- Waiting for extract requests...",
	         g_thread_self ());
#endif /* THREAD_ENABLE_TRACE */

	tracker_locale_init ();

	if (!media_art_init ()) {
		g_warning ("Could not initialize media art, will not be available");
	}

	controller = tracker_extract_controller_new (decorator);
	tracker_miner_start (TRACKER_MINER (decorator));

	/* Main loop */
	main_loop = g_main_loop_new (NULL, FALSE);
	g_main_loop_run (main_loop);

	my_main_loop = main_loop;
	main_loop = NULL;
	g_main_loop_unref (my_main_loop);

	tracker_miner_stop (TRACKER_MINER (decorator));

	/* Shutdown subsystems */
	media_art_shutdown ();
	tracker_locale_shutdown ();

	g_object_unref (extract);
	g_object_unref (decorator);
	g_object_unref (controller);

	tracker_log_shutdown ();

	g_object_unref (config);

	return EXIT_SUCCESS;
}
Example #10
0
int
main (int argc, gchar **argv)
{
	GOptionContext *context;
	GError *error = NULL;
	struct event_base *ev_base;
	GString *b32_key;
	pid_t *sfd;
	rspamd_inet_addr_t *addr;
	struct event term_ev, int_ev;
	struct in_addr ina = {INADDR_ANY};

	rspamd_init_libs ();

	context = g_option_context_new (
			"rspamd-http-server - test server for benchmarks");
	g_option_context_set_summary (context,
			"Summary:\n  Rspamd test HTTP server "
					RVERSION
					"\n  Release id: "
					RID);
	g_option_context_add_main_entries (context, entries, NULL);

	if (!g_option_context_parse (context, &argc, &argv, &error)) {
		rspamd_fprintf (stderr, "option parsing failed: %s\n", error->message);
		g_error_free (error);
		exit (1);
	}

	maps = g_hash_table_new (g_int_hash, g_int_equal);

	if (key == NULL) {
		server_key = rspamd_keypair_new (RSPAMD_KEYPAIR_KEX,
				openssl_mode ? RSPAMD_CRYPTOBOX_MODE_NIST : RSPAMD_CRYPTOBOX_MODE_25519);
		b32_key = rspamd_keypair_print (server_key,
				RSPAMD_KEYPAIR_PUBKEY | RSPAMD_KEYPAIR_BASE32);
		rspamd_printf ("key: %v\n", b32_key);
	}
	else {
		/* TODO: add key loading */
	}

	if (cache_size > 0) {
		c = rspamd_keypair_cache_new (cache_size);
	}

	sfd = g_alloca (sizeof (*sfd) * nworkers);
	addr = rspamd_inet_address_new (AF_INET, &ina);
	rspamd_inet_address_set_port (addr, port);
	rspamd_http_start_servers (sfd, addr);

	/* Just wait for workers */
	ev_base = event_init ();

	event_set (&term_ev, SIGTERM, EV_SIGNAL, rspamd_http_server_term, sfd);
	event_base_set (ev_base, &term_ev);
	event_add (&term_ev, NULL);
	event_set (&int_ev, SIGINT, EV_SIGNAL, rspamd_http_server_term, sfd);
	event_base_set (ev_base, &int_ev);
	event_add (&int_ev, NULL);

	event_base_loop (ev_base, 0);

	return 0;
}
Example #11
0
int
main (int argc, char **argv)
{
	GOptionContext *context;
	GError *error = NULL;
	GDBusConnection *bus;
	GDBusProxy *mpris;
	GDBusProxy *queue;
	GApplication *app;
	gboolean loaded;
	gboolean scanned;
	GVariant *state;

#ifdef ENABLE_NLS
	/* initialize i18n */
	bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif
	/* setup */
	setlocale (LC_ALL, "");
	g_type_init ();
	g_set_prgname ("rhythmbox-client");

	/* parse arguments */
	context = g_option_context_new (NULL);
	g_option_context_add_main_entries (context, args, NULL);
	g_option_context_parse (context, &argc, &argv, &error);
	if (annoy (&error))
		exit (1);

	rb_debug_init (debug);

	app = g_application_new ("org.gnome.Rhythmbox3", G_APPLICATION_IS_LAUNCHER);
	if (g_application_register (app, NULL, &error) == FALSE) {
		if (check_running) {
			rb_debug ("no running instance found");
			exit (2);
		} else if (quit) {
			rb_debug ("no existing instance to quit");
			exit (0);
		}

		rb_debug ("uh.. what?");
		exit (0);
	}


	/* are we just checking if it's running? */
	if (check_running) {
		rb_debug ("running instance found");
		exit (0);
	}

	/* wait until it's ready to accept control */
	state = g_action_group_get_action_state (G_ACTION_GROUP (app), "LoadURI");
	if (state == NULL) {
		rb_debug ("couldn't get app startup state");
		exit (0);
	}

	bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
	g_variant_get (state, "(bb)", &loaded, &scanned);
	if ((loaded && scanned) == FALSE) {
		GMainLoop *loop;
		GDBusProxy *app_proxy;

		rb_debug ("waiting for app startup");
		loop = g_main_loop_new (NULL, FALSE);
		g_signal_connect (app, "action-state-changed", G_CALLBACK (state_changed_cb), loop);

		/* dbus implementation of GApplication doesn't do action state updates yet */
		app_proxy = g_dbus_proxy_new_sync (bus, G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START, NULL,
						   "org.gnome.Rhythmbox3",
						   "/org/gnome/Rhythmbox3",
						   "org.gtk.Actions",
						   NULL,
						   &error);
		if (app_proxy == NULL || proxy_has_name_owner (app_proxy) == FALSE) {
			g_warning ("unable to wait for app startup: %s", error->message);
			g_clear_error (&error);
		} else {
			g_object_set_data (G_OBJECT (app_proxy), "actual-app", app);
			g_signal_connect (app_proxy, "g-signal", G_CALLBACK (state_changed_signal_cb), loop);
			g_main_loop_run (loop);
			rb_debug ("app is now started enough");
		}
	}

	/* create proxies */
	mpris = g_dbus_proxy_new_sync (bus,
				       G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START,
				       NULL,
				       "org.mpris.MediaPlayer2.rhythmbox",
				       "/org/mpris/MediaPlayer2",
				       "org.mpris.MediaPlayer2.Player",
				       NULL,
				       &error);
	if (mpris == NULL || proxy_has_name_owner (mpris) == FALSE) {
		g_warning ("MPRIS D-Bus interface not available, some things won't work");
		if (next || previous || (seek != 0) || play || do_pause || play_pause || stop || volume_up || volume_down || (set_volume > -0.01)) {
			exit (1);
		}
	}

	queue = g_dbus_proxy_new_sync (bus,
				       G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START,
				       NULL,
				       "org.gnome.Rhythmbox3",
				       "/org/gnome/Rhythmbox3/PlayQueue",
				       "org.gnome.Rhythmbox3.PlayQueue",
				       NULL,
				       &error);
	if (queue == NULL || proxy_has_name_owner (queue) == FALSE) {
		g_warning ("Play queue interface not available, some things won't work");
		if (enqueue || clear_queue) {
			exit (1);
		}
	}

	/* activate or quit */
	if (quit) {
		rb_debug ("quitting existing instance");
		g_action_group_activate_action (G_ACTION_GROUP (app), "Quit", NULL);
		exit (0);
	}

	/* don't present if we're doing something else */
	if (next || previous || (seek != 0) ||
	    clear_queue ||
	    play_uri || other_stuff ||
	    play || do_pause || play_pause || stop || toggle_shuffle ||
	    print_playing || print_playing_format ||
	    (set_volume > -0.01) || volume_up || volume_down || print_volume /*|| mute || unmute*/ || (set_rating > -0.01))
		no_present = TRUE;

	/* present */
	if (!no_present) {
		g_application_activate (app);
	}

	/* set song rating */
	if (set_rating >= 0.0 && set_rating <= 5.0) {
		rb_debug ("rate song");

		rate_song (mpris, set_rating);
	}

	if (toggle_shuffle) {
		rb_debug("toggle shuffle");
		g_action_group_activate_action (G_ACTION_GROUP (app), "ToggleShuffle", NULL);
		annoy(&error);
	}

	/* skip to next or previous track */
	if (next) {
		rb_debug ("next track");
		g_dbus_proxy_call_sync (mpris, "Next", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
		annoy (&error);
	} else if (previous) {
		rb_debug ("previous track");
		g_dbus_proxy_call_sync (mpris, "Previous", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
		annoy (&error);
	}

	/* seek in track */
	if (seek != 0) {
		GHashTable *properties;
		rb_debug ("seek");

		properties = get_playing_song_info (mpris);
		if (properties != NULL) {
			GVariant *v = g_hash_table_lookup (properties, "mpris:trackid");
			if (v != NULL) {
				g_dbus_proxy_call_sync (mpris,
							"SetPosition",
							g_variant_new ("(ox)", g_variant_get_string (v, NULL), seek),
							G_DBUS_CALL_FLAGS_NONE,
							-1,
							NULL,
							&error);
				annoy (&error);
			}
		}
	}

	/* add/enqueue */
	if (clear_queue) {
		g_dbus_proxy_call_sync (queue, "ClearQueue", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
		annoy (&error);
	}
	if (other_stuff) {
		int i;
		for (i = 0; other_stuff[i] != NULL; i++) {
			GFile *file;
			char *fileuri;

			file = g_file_new_for_commandline_arg (other_stuff[i]);
			fileuri = g_file_get_uri (file);
			if (fileuri == NULL) {
				g_warning ("couldn't convert \"%s\" to a URI", other_stuff[i]);
				continue;
			}

			if (enqueue) {
				rb_debug ("enqueueing %s", fileuri);
				g_dbus_proxy_call_sync (queue, "AddToQueue", g_variant_new ("(s)", fileuri), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
				annoy (&error);
			} else {
				rb_debug ("importing %s", fileuri);
				g_action_group_activate_action (G_ACTION_GROUP (app), "LoadURI", g_variant_new ("(sb)", fileuri, FALSE));
			}
			g_free (fileuri);
			g_object_unref (file);
		}
	}

	/* select/activate/play source */
	if (select_source) {
		rb_debug ("selecting source %s", select_source);
		g_action_group_activate_action (G_ACTION_GROUP (app), "ActivateSource", g_variant_new ("(su)", select_source, 0));
	} else if (activate_source) {
		rb_debug ("activating source %s", activate_source);
		g_action_group_activate_action (G_ACTION_GROUP (app), "ActivateSource", g_variant_new ("(su)", activate_source, 1));
	} else if (play_source) {
		rb_debug ("playing source %s", play_source);
		g_action_group_activate_action (G_ACTION_GROUP (app), "ActivateSource", g_variant_new ("(su)", play_source, 2));
	}

	/* play uri */
	if (play_uri) {
		GFile *file;
		char *fileuri;

		file = g_file_new_for_commandline_arg (play_uri);
		fileuri = g_file_get_uri (file);
		if (fileuri == NULL) {
			g_warning ("couldn't convert \"%s\" to a URI", play_uri);
		} else {
			rb_debug ("loading and playing %s", fileuri);
			g_action_group_activate_action (G_ACTION_GROUP (app), "LoadURI", g_variant_new ("(sb)", fileuri, TRUE));
			annoy (&error);
		}
		g_free (fileuri);
		g_object_unref (file);
	}

	/* play/pause/stop */
	if (mpris) {
		GVariant *v;
		gboolean is_playing = FALSE;

		v = g_dbus_proxy_get_cached_property (mpris, "PlaybackStatus");
		if (v != NULL) {
			is_playing = (g_strcmp0 (g_variant_get_string (v, NULL), "Playing") == 0);
			g_variant_unref (v);
		}

		if (play || do_pause || play_pause) {
			if (is_playing != play || play_pause) {
				rb_debug ("calling PlayPause to change playback state");
				g_dbus_proxy_call_sync (mpris, "PlayPause", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
				annoy (&error);
			} else {
				rb_debug ("no need to change playback state");
			}
		} else if (stop) {
			g_warning ("not implemented yet");
		}
	}

	/* get/set volume, mute/unmute */
	if (set_volume > -0.01) {
		g_dbus_proxy_call_sync (mpris,
					"org.freedesktop.DBus.Properties.Set",
					g_variant_new ("(ssv)", "org.mpris.MediaPlayer2.Player", "Volume", g_variant_new_double (set_volume)),
					G_DBUS_CALL_FLAGS_NONE,
					-1,
					NULL,
					&error);
		annoy (&error);
	} else if (volume_up || volume_down) {
		GVariant *v;

		v = g_dbus_proxy_get_cached_property (mpris, "Volume");
		if (v != NULL) {

			set_volume = g_variant_get_double (v) + (volume_up ? 0.1 : -0.1);
			g_dbus_proxy_call_sync (mpris,
						"org.freedesktop.DBus.Properties.Set",
						g_variant_new ("(ssv)", "org.mpris.MediaPlayer2.Player", "Volume", g_variant_new_double (set_volume)),
						G_DBUS_CALL_FLAGS_NONE,
						-1,
						NULL,
						&error);
			annoy (&error);

			g_variant_unref (v);
		}
	}
	/* no mute for now? */
	/*
	} else if (unmute || mute) {
		org_gnome_Rhythmbox_Player_set_mute (player_proxy, unmute ? FALSE : TRUE, &error);
		annoy (&error);
	}
	*/

	if (print_volume) {
		gdouble volume = 1.0;
		GVariant *v = g_dbus_proxy_get_cached_property (mpris, "Volume");
		if (v != NULL) {
			volume = g_variant_get_double (v);
			g_variant_unref (v);
		}
		g_print (_("Playback volume is %f.\n"), volume);
	}

	/* print playing song */
	if (print_playing_format) {
		print_playing_song (mpris, print_playing_format);
	} else if (print_playing) {
		print_playing_song_default (mpris);
	}

	if (mpris) {
		g_object_unref (mpris);
	}

	g_dbus_connection_flush_sync (bus, NULL, NULL);
	g_option_context_free (context);

	return 0;
}
Example #12
0
gboolean
ostree_option_context_parse (GOptionContext *context,
                             const GOptionEntry *main_entries,
                             int *argc,
                             char ***argv,
                             OstreeBuiltinFlags flags,
                             OstreeRepo **out_repo,
                             GCancellable *cancellable,
                             GError **error)
{
  glnx_unref_object OstreeRepo *repo = NULL;
  gboolean success = FALSE;

  /* Entries are listed in --help output in the order added.  We add the
   * main entries ourselves so that we can add the --repo entry first. */

  if (!(flags & OSTREE_BUILTIN_FLAG_NO_REPO))
    g_option_context_add_main_entries (context, repo_entry, NULL);

  if (main_entries != NULL)
    g_option_context_add_main_entries (context, main_entries, NULL);

  g_option_context_add_main_entries (context, global_entries, NULL);

  if (!g_option_context_parse (context, argc, argv, error))
    return FALSE;

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

  if (opt_verbose)
    g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, message_handler, NULL);

  if (opt_repo == NULL && !(flags & OSTREE_BUILTIN_FLAG_NO_REPO))
    {
      GError *local_error = NULL;

      repo = ostree_repo_new_default ();
      if (!ostree_repo_open (repo, cancellable, &local_error))
        {
          if (g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
            {
              g_autofree char *help = NULL;

              g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "Command requires a --repo argument");
              g_error_free (local_error);

              help = g_option_context_get_help (context, FALSE, NULL);
              g_printerr ("%s", help);
            }
          else
            {
              g_propagate_error (error, local_error);
            }
          goto out;
        }
    }
  else if (opt_repo != NULL)
    {
      g_autoptr(GFile) repo_file = g_file_new_for_path (opt_repo);

      repo = ostree_repo_new (repo_file);
      if (!(flags & OSTREE_BUILTIN_FLAG_NO_CHECK))
        {
          if (!ostree_repo_open (repo, cancellable, error))
            goto out;
        }
    }

  if (out_repo)
    *out_repo = g_steal_pointer (&repo);

  success = TRUE;

out:
  return success;
}
Example #13
0
int main(int argc, char *argv[])
{
    gboolean res = TRUE;
    GOptionContext *context;
    setlocale(LC_ALL, "");
    context = g_option_context_new("-- COMMAND [COMMAND_ARG1] [COMMAND_ARG2] [...] - wrapper to execute the given command in a process with some specific layers loaded");
    g_option_context_add_main_entries(context, entries, NULL);
    if (!g_option_context_parse(context, &argc, &argv, NULL)) {
        g_print(g_option_context_get_help(context, TRUE, NULL));
        exit(1);
    }
    if (argc < 2) {
        g_print(g_option_context_get_help(context, TRUE, NULL));
        exit(1);
    }
    layerapi2_init(debug_mode);
    if (empty || empty_env) {
        layerapi2_layers_unload_all(NULL);
    }
    if (empty_env) {
        gchar **env_vars_to_keep = NULL;
        env_vars_to_keep = g_strsplit(empty_env_keeps, ",", 0);
        layerapi2_empty_env(env_vars_to_keep);
    }
    if (layers != NULL) {
        gchar **tmp = g_strsplit(layers, ",", 0);
        guint size = g_strv_length(tmp);
        for (guint i = 0 ; i < size ; i++) {
            if (strlen(tmp[i]) > 0) {
                if (tmp[i][0] == '-') {
                    const gchar *label_or_home = tmp[i] + sizeof(gchar);
                    LayerApi2Layer *tempo = layerapi2_layer_load(label_or_home, force_prepend, NULL);
                    if (tempo != NULL) {
                        layerapi2_layer_free(tempo);
                    }
                } else {
                    LayerApi2Layer *tempo = layerapi2_layer_load(tmp[i], force_prepend, NULL);
                    if (tempo == NULL) {
                        g_warning("impossible to load the layer: %s", tmp[i]);
                        res = FALSE;
                    } else {
                        if ( (i+1) >= size ) {
                            // this is the last layer
                            if (cwd) {
                                g_debug("CHDIR %s", tempo->home);
                                chdir(tempo->home);
                            }
                            if (extra_env_prefix != NULL) {
                                gchar *plugin_name_env = g_strdup_printf("%s_NAME",
                                        extra_env_prefix);
                                gchar *plugin_dir_env = g_strdup_printf("%s_DIR",
                                        extra_env_prefix);
                                gchar *plugin_label_env = g_strdup_printf("%s_LABEL",
                                        extra_env_prefix);
                                g_debug("SETENV %s=%s", plugin_name_env, g_path_get_basename(tempo->home));
                                g_setenv(plugin_name_env,
                                        g_path_get_basename(tempo->home),
                                        TRUE);
                                g_debug("SETENV %s=%s", plugin_dir_env, tempo->home);
                                g_setenv(plugin_dir_env, tempo->home, TRUE);
                                g_debug("SETENV %s=%s", plugin_label_env, tempo->label);
                                g_setenv(plugin_label_env, tempo->label, TRUE);
                            }
                        }
                        layerapi2_layer_free(tempo);
                    }
                }
            }
        }
    }
    if (res) {
        if (prepend_env != NULL) {
            guint prepend_env_size = g_strv_length(prepend_env);
            for (guint i = 0 ; i < prepend_env_size ; i++) {
                gchar *tmp = g_strstrip(g_strdup(prepend_env[i]));
                gchar **tmp2 = g_strsplit(tmp, ",", 0);
                if (g_strv_length(tmp2) != 2) {
                    g_warning("bad prepend_env format: %s", tmp);
                    return 1;
                }
                g_debug("PREPEND_ENV %s with value %s", tmp2[0], tmp2[1]);
                field_prepend_env(tmp2[0], tmp2[1], NULL);
            }
        }
        layerapi2_wrapper(argc, argv);
        return 1;
    } else {
        g_warning("don't launch the command because of at least one layer loading fail");
        return 1;
    }
}
Example #14
0
int main (int argc, char *argv[]) {
    /* set up i18n */
    bindtextdomain (PACKAGE, GUMMI_LOCALES);
    setlocale (LC_ALL, "");
    textdomain (PACKAGE);

    GError* error = NULL;
    GOptionContext* context = g_option_context_new ("files");
    g_option_context_add_main_entries (context, entries, PACKAGE);
    g_option_context_parse (context, &argc, &argv, &error);
    if (error) g_error("%s\n", error->message);

    if (showversion) {
        printf("Gummi %s\n", PACKAGE_VERSION);
        return 0;
    }

    /* initialize GTK */
    g_thread_init (NULL);
    gdk_threads_init ();
    gtk_init (&argc, &argv);
    GError* ui_error = NULL;
    GtkBuilder* builder = gtk_builder_new ();
    gchar* ui = g_build_filename (GUMMI_DATA, "ui", "gummi.glade", NULL);

    // exit program when gummi.glade can not be located:
    if (!g_file_test (ui, G_FILE_TEST_EXISTS)) {
        printf("Could not locate Glade interface file at:\n%s\n", ui);
        return 0;
    }

    gtk_builder_add_from_file (builder, ui, &ui_error);
    if (ui_error) {
        g_error ("%s\n", ui_error->message);
    }
    gtk_builder_set_translation_domain (builder, PACKAGE);
    g_free (ui);

    /* Initialize logging */
    slog_init (debug);
    slog (L_INFO, PACKAGE_NAME" version: "PACKAGE_VERSION"\n");

    /* Initialize configuration */
    gchar* configname = g_build_filename (g_get_user_config_dir (), "gummi",
                                  "gummi.cfg", NULL);
    config_init (configname);
    config_load ();
    g_free (configname);

    /* Initialize signals */
    gummi_signals_register ();

    /* Initialize Classes */
    gchar* snippetsname = g_build_filename (g_get_user_config_dir (), "gummi",
            "snippets.cfg", NULL);

    // why do we not load this from environment, like gui-main does? -A
    GuMotion* motion = motion_init ();
    GuIOFunc* io = iofunctions_init();
    GuLatex* latex = latex_init ();
    GuBiblio* biblio = biblio_init (builder);
    GuTemplate* templ = template_init (builder);
    GuTabmanager* tabm = tabmanager_init ();
    GuProject* proj = project_init ();

    GuSnippets* snippets = snippets_init (snippetsname);
    gummi = gummi_init (motion, io, latex, biblio, templ, snippets, tabm, proj);
    slog (L_DEBUG, "Gummi created!\n");
    g_free (snippetsname);

    /* Initialize GUI */
    gui = gui_init (builder);

    slog_set_gui_parent (gui->mainwindow);
    slog (L_DEBUG, "GummiGui created!\n");

    /* Start compile thread */
    if (external_exists (config_get_value("typesetter"))) {
        typesetter_setup ();
        motion_start_compile_thread (motion);
    }
    else {
        infoscreengui_enable (gui->infoscreengui, "program_error");
        slog (L_ERROR, "Could not locate the typesetter program\n");
    }

    /* Install acceleration group to mainwindow */
    gtk_window_add_accel_group (gui->mainwindow, snippets->accel_group);

    if (argc != 2)
        tabmanager_create_tab (A_DEFAULT, NULL, NULL);
    else {
        if (!g_file_test(argv[1], G_FILE_TEST_EXISTS)) {
            slog(L_ERROR, "Failed to open file '%s': No such file or "
                    "directory\n", argv[1]);
            exit(1);
        }
        tabmanager_create_tab (A_LOAD, argv[1], NULL);
    }

    if (config_get_value ("autosaving")) iofunctions_start_autosave ();

    gui_main (builder);
    config_save ();
    config_clean_up ();
    return 0;
}
Example #15
0
int
main (int argc, char **argv)
{
  GString *str;
  GList *packages = NULL;
  char *search_path;
  char *pcbuilddir;
  gboolean need_newline;
  FILE *log = NULL;
  GError *error = NULL;
  GOptionContext *opt_context;

  /* This is here so that we get debug spew from the start,
   * during arg parsing
   */
  if (getenv ("PKG_CONFIG_DEBUG_SPEW"))
    {
      want_debug_spew = TRUE;
      want_verbose_errors = TRUE;
      want_silence_errors = FALSE;
      debug_spew ("PKG_CONFIG_DEBUG_SPEW variable enabling debug spew\n");
    }


  /* Get the built-in search path */
  init_pc_path ();
  if (pkg_config_pc_path == NULL)
    {
      /* Even when we override the built-in search path, we still use it later
       * to add pc_path to the virtual pkg-config package.
       */
      verbose_error ("Failed to get default search path\n");
      exit (1);
    }

  search_path = getenv ("PKG_CONFIG_PATH");
  if (search_path) 
    {
      add_search_dirs(search_path, G_SEARCHPATH_SEPARATOR_S);
    }
  if (getenv("PKG_CONFIG_LIBDIR") != NULL) 
    {
      add_search_dirs(getenv("PKG_CONFIG_LIBDIR"), G_SEARCHPATH_SEPARATOR_S);
    }
  else
    {
      add_search_dirs(pkg_config_pc_path, G_SEARCHPATH_SEPARATOR_S);
    }

  pcsysrootdir = getenv ("PKG_CONFIG_SYSROOT_DIR");
  if (pcsysrootdir)
    {
      define_global_variable ("pc_sysrootdir", pcsysrootdir);
    }
  else
    {
      define_global_variable ("pc_sysrootdir", "/");
    }

  pcbuilddir = getenv ("PKG_CONFIG_TOP_BUILD_DIR");
  if (pcbuilddir)
    {
      define_global_variable ("pc_top_builddir", pcbuilddir);
    }
  else
    {
      /* Default appropriate for automake */
      define_global_variable ("pc_top_builddir", "$(top_builddir)");
    }

  if (getenv ("PKG_CONFIG_DISABLE_UNINSTALLED"))
    {
      debug_spew ("disabling auto-preference for uninstalled packages\n");
      disable_uninstalled = TRUE;
    }

  /* Parse options */
  opt_context = g_option_context_new (NULL);
  g_option_context_add_main_entries (opt_context, options_table, NULL);
  if (!g_option_context_parse(opt_context, &argc, &argv, &error))
    {
      fprintf (stderr, "%s\n", error->message);
      return 1;
    }

  /* If no output option was set, then --exists is the default. */
  if (!output_opt_set)
    {
      debug_spew ("no output option set, defaulting to --exists\n");
      want_exists = TRUE;
    }

  /* Error printing is determined as follows:
   *     - for --exists, --*-version, --list-all and no options at all,
   *       it's off by default and --print-errors will turn it on
   *     - for all other output options, it's on by default and
   *       --silence-errors can turn it off
   */
  if (want_exists || want_list)
    {
      debug_spew ("Error printing disabled by default due to use of output "
                  "options --exists, --atleast/exact/max-version, "
                  "--list-all or no output option at all. Value of "
                  "--print-errors: %d\n",
                  want_verbose_errors);

      /* Leave want_verbose_errors unchanged, reflecting --print-errors */
    }
  else
    {
      debug_spew ("Error printing enabled by default due to use of output "
                  "options besides --exists, --atleast/exact/max-version or "
                  "--list-all. Value of --silence-errors: %d\n",
                  want_silence_errors);

      if (want_silence_errors && getenv ("PKG_CONFIG_DEBUG_SPEW") == NULL)
        want_verbose_errors = FALSE;
      else
        want_verbose_errors = TRUE;
    }

  if (want_verbose_errors)
    debug_spew ("Error printing enabled\n");
  else
    debug_spew ("Error printing disabled\n");

  if (want_static_lib_list)
    enable_private_libs();
  else
    disable_private_libs();

  /* honor Requires.private if any Cflags are requested or any static
   * libs are requested */

  if (pkg_flags & CFLAGS_ANY || want_requires_private || want_exists ||
      (want_static_lib_list && (pkg_flags & LIBS_ANY)))
    enable_requires_private();

  /* ignore Requires if no Cflags or Libs are requested */

  if (pkg_flags == 0 && !want_requires && !want_exists)
    disable_requires();

  /* Allow errors in .pc files when listing all. */
  if (want_list)
    parse_strict = FALSE;

  if (want_my_version)
    {
      printf ("%s\n", VERSION);
      return 0;
    }

  if (required_pkgconfig_version)
    {
      if (compare_versions (VERSION, required_pkgconfig_version) >= 0)
        return 0;
      else
        return 1;
    }

  package_init ();

  if (want_list)
    {
      print_package_list ();
      return 0;
    }

  /* Collect packages from remaining args */
  str = g_string_new ("");
  while (argc > 1)
    {
      argc--;
      argv++;

      g_string_append (str, *argv);
      g_string_append (str, " ");
    }

  g_option_context_free (opt_context);

  g_strstrip (str->str);

  if (getenv("PKG_CONFIG_LOG") != NULL)
    {
      log = fopen (getenv ("PKG_CONFIG_LOG"), "a");
      if (log == NULL)
	{
	  fprintf (stderr, "Cannot open log file: %s\n",
		   getenv ("PKG_CONFIG_LOG"));
	  exit (1);
	}
    }

  /* find and parse each of the packages specified */
  if (!process_package_args (str->str, &packages, log))
    return 1;

  if (log != NULL)
    fclose (log);

  g_string_free (str, TRUE);

  if (want_exists)
    return 0; /* if we got here, all the packages existed. */

  if (want_variable_list)
    {
      GList *tmp;
      tmp = packages;
      while (tmp != NULL)
        {
          Package *pkg = tmp->data;
          if (pkg->vars != NULL)
            g_hash_table_foreach(pkg->vars,
                                 &print_hashtable_key,
                                 NULL);
          tmp = g_list_next (tmp);
          if (tmp) printf ("\n");
        }
      need_newline = FALSE;
    }

  if (want_uninstalled)
    {
      /* See if > 0 pkgs (including dependencies recursively) were uninstalled */
      GList *tmp;
      tmp = packages;
      while (tmp != NULL)
        {
          Package *pkg = tmp->data;

          if (pkg_uninstalled (pkg))
            return 0;

          tmp = g_list_next (tmp);
        }

      return 1;
    }

  if (want_version)
    {
      GList *tmp;
      tmp = packages;
      while (tmp != NULL)
        {
          Package *pkg = tmp->data;

          printf ("%s\n", pkg->version);

          tmp = g_list_next (tmp);
        }
    }

 if (want_provides)
   {
     GList *tmp;
     tmp = packages;
     while (tmp != NULL)
       {
         Package *pkg = tmp->data;
         char *key;
         key = pkg->key;
         while (*key == '/')
           key++;
         if (strlen(key) > 0)
           printf ("%s = %s\n", key, pkg->version);
         tmp = g_list_next (tmp);
       }
   }

  if (want_requires)
    {
      GList *pkgtmp;
      for (pkgtmp = packages; pkgtmp != NULL; pkgtmp = g_list_next (pkgtmp))
        {
          Package *pkg = pkgtmp->data;
          GList *reqtmp;

          /* process Requires: */
          for (reqtmp = pkg->requires; reqtmp != NULL; reqtmp = g_list_next (reqtmp))
            {
              Package *deppkg = reqtmp->data;
              RequiredVersion *req;
              req = g_hash_table_lookup(pkg->required_versions, deppkg->key);
              if ((req == NULL) || (req->comparison == ALWAYS_MATCH))
                printf ("%s\n", deppkg->key);
              else
                printf ("%s %s %s\n", deppkg->key,
                  comparison_to_str(req->comparison),
                  req->version);
            }
        }
    }
  if (want_requires_private)
    {
      GList *pkgtmp;
      for (pkgtmp = packages; pkgtmp != NULL; pkgtmp = g_list_next (pkgtmp))
        {
          Package *pkg = pkgtmp->data;
          GList *reqtmp;
          /* process Requires.private: */
          for (reqtmp = pkg->requires_private; reqtmp != NULL; reqtmp = g_list_next (reqtmp))
            {

              Package *deppkg = reqtmp->data;
              RequiredVersion *req;

              if (g_list_find (pkg->requires, reqtmp->data))
                continue;

              req = g_hash_table_lookup(pkg->required_versions, deppkg->key);
              if ((req == NULL) || (req->comparison == ALWAYS_MATCH))
                printf ("%s\n", deppkg->key);
              else
                printf ("%s %s %s\n", deppkg->key,
                  comparison_to_str(req->comparison),
                  req->version);
            }
        }
    }
  
  /* Print all flags; then print a newline at the end. */
  need_newline = FALSE;

  if (variable_name)
    {
      char *str = packages_get_var (packages, variable_name);
      printf ("%s", str);
      g_free (str);
      need_newline = TRUE;
    }

  if (pkg_flags != 0)
    {
      char *str = packages_get_flags (packages, pkg_flags);
      printf ("%s", str);
      g_free (str);
      need_newline = TRUE;
    }

  if (need_newline)
    printf ("\n");

  return 0;
}
Example #16
0
int main (int argc, char *argv[])
{
	GOptionGroup *options;
	GOptionContext *context;
	GError *err = NULL;
	GdkPixbuf *pixbuf;
	const char *input, *output;
	ThumbApp app;

	setlocale (LC_ALL, "");
	bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

	context = g_option_context_new ("Thumbnail movies");
	options = gst_init_get_option_group ();
	g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
	g_option_context_add_group (context, options);

	if (g_option_context_parse (context, &argc, &argv, &err) == FALSE) {
		g_print ("couldn't parse command-line options: %s\n", err->message);
		g_error_free (err);
		return 1;
	}

	fcntl (fileno (stdout), F_SETFL, O_NONBLOCK);
	setbuf (stdout, NULL);

	if (raw_output == FALSE && output_size == -1)
		output_size = DEFAULT_OUTPUT_SIZE;

	if (filenames == NULL || g_strv_length (filenames) != 2 ||
	    (second_index != -1 && gallery != -1)) {
		char *help;
		help = g_option_context_get_help (context, FALSE, NULL);
		g_print ("%s", help);
		g_free (help);
		return 1;
	}
	input = filenames[0];
	output = filenames[1];

	g_debug("Initialised libraries, about to create video widget");
	PRINT_PROGRESS (2.0);

	app.input = input;
	app.output = output;

	thumb_app_setup_play (&app);
	thumb_app_set_filename (&app);

	g_debug("Video widget created");
	PRINT_PROGRESS (6.0);

	g_debug("About to open video file");

	if (thumb_app_start (&app) == FALSE) {
		g_print ("totem-video-thumbnailer couldn't open file '%s'\n", input);
		exit (1);
	}
	thumb_app_set_error_handler (&app);

	if (thumb_app_get_has_video (&app) == FALSE) {
		g_debug ("totem-video-thumbnailer couldn't find a video track in '%s'\n", input);
		exit (1);
	}
	thumb_app_set_duration (&app);

	g_debug("Opened video file: '%s'", input);
	PRINT_PROGRESS (10.0);

	assert_duration (&app);
	/* We're producing a gallery of screenshots from throughout the file */
	pixbuf = create_gallery (&app);

	/* Cleanup */
	thumb_app_cleanup (&app);
	PRINT_PROGRESS (92.0);

	if (pixbuf == NULL) {
		g_print ("totem-video-thumbnailer couldn't get a picture from '%s'\n", input);
		exit (1);
	}

	g_debug("Saving captured screenshot to %s", output);
	save_pixbuf (pixbuf, output, input, output_size, FALSE);
	g_object_unref (pixbuf);
	PRINT_PROGRESS (100.0);

	return 0;
}
int main(int argc, char * argv[]){
    int i = 1;

    setlocale(LC_ALL, "");

    GError * error = NULL;
    GOptionContext * context;

    context = g_option_context_new("- generate k mixture model");
    g_option_context_add_main_entries(context, entries, NULL);
    if (!g_option_context_parse(context, &argc, &argv, &error)) {
        g_print("option parsing failed:%s\n", error->message);
        exit(EINVAL);
    }

    SystemTableInfo system_table_info;

    bool retval = system_table_info.load(SYSTEM_TABLE_INFO);
    if (!retval) {
        fprintf(stderr, "load table.conf failed.\n");
        exit(ENOENT);
    }

    PhraseLargeTable2 phrase_table;
    MemoryChunk * chunk = new MemoryChunk;
    chunk->load(SYSTEM_PHRASE_INDEX);
    phrase_table.load(chunk);

    FacadePhraseIndex phrase_index;

    const pinyin_table_info_t * phrase_files =
        system_table_info.get_table_info();

    if (!load_phrase_index(phrase_files, &phrase_index))
        exit(ENOENT);

    KMixtureModelBigram bigram(K_MIXTURE_MODEL_MAGIC_NUMBER);
    bigram.attach(g_k_mixture_model_filename, ATTACH_READWRITE|ATTACH_CREATE);

    while ( i < argc ){
        const char * filename = argv[i];
        FILE * document = fopen(filename, "r");
        if ( NULL == document ){
            int err_saved = errno;
            fprintf(stderr, "can't open file: %s.\n", filename);
            fprintf(stderr, "error:%s.\n", strerror(err_saved));
            exit(err_saved);
        }

        HashofDocument hash_of_document = g_hash_table_new
            (g_direct_hash, g_direct_equal);
        HashofUnigram hash_of_unigram = g_hash_table_new
            (g_direct_hash, g_direct_equal);

        assert(read_document(&phrase_table, &phrase_index, document,
                             hash_of_document, hash_of_unigram));
        fclose(document);
        document = NULL;

        GHashTableIter iter;
        gpointer key, value;

        /* train the document, and convert it to k mixture model. */
        g_hash_table_iter_init(&iter, hash_of_document);
        while (g_hash_table_iter_next(&iter, &key, &value)) {
            phrase_token_t token1 = GPOINTER_TO_UINT(key);
            train_second_word(hash_of_unigram, &bigram,
                              hash_of_document, token1);
        }

        KMixtureModelMagicHeader magic_header;
        assert(bigram.get_magic_header(magic_header));
        magic_header.m_N ++;
        assert(bigram.set_magic_header(magic_header));

        post_processing_unigram(&bigram, hash_of_unigram);

        /* free resources of g_hash_of_document */
        g_hash_table_iter_init(&iter, hash_of_document);
        while (g_hash_table_iter_next(&iter, &key, &value)) {
            HashofSecondWord second_word = (HashofSecondWord) value;
            g_hash_table_iter_steal(&iter);
            g_hash_table_unref(second_word);
        }
        g_hash_table_unref(hash_of_document);
        hash_of_document = NULL;

        g_hash_table_unref(hash_of_unigram);
        hash_of_unigram = NULL;

        ++i;
    }

    return 0;
}
Example #18
0
int
handle_remove (int argc, char *argv[], gboolean do_help)
{
  GOptionContext *context;
  gchar *param;
  GError *error = NULL;
  GFile *file;
  int retval;
  int i;

  g_set_prgname ("gio remove");

  /* Translators: commandline placeholder */
  param = g_strdup_printf ("%s...", _("LOCATION"));
  context = g_option_context_new (param);
  g_free (param);
  g_option_context_set_help_enabled (context, FALSE);
  g_option_context_set_summary (context, _("Delete the given files."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

  if (do_help)
    {
      show_help (context, NULL);
      g_option_context_free (context);
      return 0;
    }

  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      show_help (context, error->message);
      g_error_free (error);
      g_option_context_free (context);
      return 1;
    }

  if (argc == 1)
    {
      show_help (context, _("No locations given"));
      g_option_context_free (context);
      return 1;
    }

  g_option_context_free (context);

  retval = 0;
  for (i = 1; i < argc; i++)
    {
      file = g_file_new_for_commandline_arg (argv[i]);
      if (!g_file_delete (file, NULL, &error))
        {
          if (!force ||
              !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
            {
              print_file_error (file, error->message);
              retval = 1;
            }
          g_clear_error (&error);
        }
      g_object_unref (file);
    }

  return retval;
}
Example #19
0
static void
rspamadm_confighelp (gint argc, gchar **argv)
{
	struct rspamd_config *cfg;
	ucl_object_t *doc_obj;
	const ucl_object_t *elt;
	GOptionContext *context;
	GError *error = NULL;
	module_t *mod, **pmod;
	worker_t **pworker;
	struct module_ctx *mod_ctx;
	gint i = 1, ret = 0, processed_args = 0;

	context = g_option_context_new (
			"confighelp - displays help for the configuration options");
	g_option_context_set_summary (context,
			"Summary:\n  Rspamd administration utility version "
					RVERSION
					"\n  Release id: "
					RID);
	g_option_context_add_main_entries (context, entries, NULL);
	g_option_context_set_ignore_unknown_options (context, TRUE);

	if (!g_option_context_parse (context, &argc, &argv, &error)) {
		rspamd_fprintf (stderr, "option parsing failed: %s\n", error->message);
		g_error_free (error);
		exit (1);
	}

	pworker = &workers[0];
	while (*pworker) {
		/* Init string quarks */
		(void) g_quark_from_static_string ((*pworker)->name);
		pworker++;
	}

	cfg = rspamd_config_new ();
	cfg->compiled_modules = modules;
	cfg->compiled_workers = workers;

	rspamd_rcl_config_init (cfg);

	/* Init modules to get documentation strings */
	for (pmod = cfg->compiled_modules; pmod != NULL && *pmod != NULL; pmod++) {
		mod = *pmod;
		mod_ctx = g_slice_alloc0 (sizeof (struct module_ctx));

		if (mod->module_init_func (cfg, &mod_ctx) == 0) {
			g_hash_table_insert (cfg->c_modules,
					(gpointer) mod->name,
					mod_ctx);
			mod_ctx->mod = mod;
		}
	}
	/* Also init all workers */
	for (pworker = cfg->compiled_workers; *pworker != NULL; pworker ++) {
		(*pworker)->worker_init_func (cfg);
	}

	if (argc > 1) {
		for (i = 1; i < argc; i ++) {
			if (argv[i][0] != '-') {

				if (keyword) {
					doc_obj = rspamadm_confighelp_search_word (cfg->doc_strings,
							argv[i]);
				}
				else {
					doc_obj = ucl_object_typed_new (UCL_OBJECT);
					elt = ucl_object_lookup_path (cfg->doc_strings, argv[i]);

					if (elt) {
						ucl_object_insert_key (doc_obj, ucl_object_ref (elt),
								argv[i], 0, false);
					}
				}

				if (doc_obj != NULL) {
					rspamadm_confighelp_show (cfg, argc, argv, argv[i], doc_obj);
					ucl_object_unref (doc_obj);
				}
				else {
					rspamd_fprintf (stderr,
							"Cannot find help for %s\n",
							argv[i]);
					ret = EXIT_FAILURE;
				}
				processed_args ++;
			}
		}
	}

	if (processed_args == 0) {
		/* Show all documentation strings */
		rspamadm_confighelp_show (cfg, argc, argv, NULL, cfg->doc_strings);
	}

	rspamd_config_free (cfg);

	exit (ret);
}
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},
    {"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}, */
    {"toc", 'c', 0, G_OPTION_ARG_NONE, &show_toc,
        "Output TOC (chapters and editions)", NULL},
    {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
        "Verbose properties", NULL},
    {NULL}
  };
  GOptionContext *ctx;

  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 #21
0
int
main (int argc, char **argv)
{
  GError *error;
  GHashTable *table;
  GHashTable *files;
  gchar *srcfile;
  gboolean show_version_and_exit = FALSE;
  gchar *target = NULL;
  gchar *binary_target = NULL;
  gboolean generate_automatic = FALSE;
  gboolean generate_source = FALSE;
  gboolean generate_header = FALSE;
  gboolean manual_register = FALSE;
  gboolean internal = FALSE;
  gboolean generate_dependencies = FALSE;
  gboolean generate_phony_targets = FALSE;
  char *dependency_file = NULL;
  char *c_name = NULL;
  char *c_name_no_underscores;
  const char *linkage = "extern";
  GOptionContext *context;
  GOptionEntry entries[] = {
    { "version", 0, 0, G_OPTION_ARG_NONE, &show_version_and_exit, N_("Show program version and exit"), NULL },
    { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
    { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &sourcedirs, N_("The directories where files are to be read from (default to current directory)"), N_("DIRECTORY") },
    { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
    { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
    { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
    { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
    { "dependency-file", 0, 0, G_OPTION_ARG_FILENAME, &dependency_file, N_("name of the dependency file to generate"), N_("FILE") },
    { "generate-phony-targets", 0, 0, G_OPTION_ARG_NONE, &generate_phony_targets, N_("Include phony targets in the generated dependency file"), NULL },
    { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don’t automatically create and register resource"), NULL },
    { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don’t export functions; declare them G_GNUC_INTERNAL"), NULL },
    { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
    { NULL }
  };

#ifdef G_OS_WIN32
  gchar *tmp;
#endif

  setlocale (LC_ALL, "");
  textdomain (GETTEXT_PACKAGE);

#ifdef G_OS_WIN32
  tmp = _glib_get_locale_dir ();
  bindtextdomain (GETTEXT_PACKAGE, tmp);
  g_free (tmp);
#else
  bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
#endif

#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif

  context = g_option_context_new (N_("FILE"));
  g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
  g_option_context_set_summary (context,
    N_("Compile a resource specification into a resource file.\n"
       "Resource specification files have the extension .gresource.xml,\n"
       "and the resource file have the extension called .gresource."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

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

  g_option_context_free (context);

  if (show_version_and_exit)
    {
      g_print (PACKAGE_VERSION "\n");
      return 0;
    }

  if (argc != 2)
    {
      g_printerr (_("You should give exactly one file name\n"));
      g_free (c_name);
      return 1;
    }

  if (internal)
    linkage = "G_GNUC_INTERNAL";

  srcfile = argv[1];

  xmllint = g_strdup (g_getenv ("XMLLINT"));
  if (xmllint == NULL)
    xmllint = g_find_program_in_path ("xmllint");
  if (xmllint == NULL)
    g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");

  gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
  if (gdk_pixbuf_pixdata == NULL)
    gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");

  if (target == NULL)
    {
      char *dirname = g_path_get_dirname (srcfile);
      char *base = g_path_get_basename (srcfile);
      char *target_basename;
      if (g_str_has_suffix (base, ".xml"))
	base[strlen(base) - strlen (".xml")] = 0;

      if (generate_source)
	{
	  if (g_str_has_suffix (base, ".gresource"))
	    base[strlen(base) - strlen (".gresource")] = 0;
	  target_basename = g_strconcat (base, ".c", NULL);
	}
      else if (generate_header)
        {
          if (g_str_has_suffix (base, ".gresource"))
            base[strlen(base) - strlen (".gresource")] = 0;
          target_basename = g_strconcat (base, ".h", NULL);
        }
      else
	{
	  if (g_str_has_suffix (base, ".gresource"))
	    target_basename = g_strdup (base);
	  else
	    target_basename = g_strconcat (base, ".gresource", NULL);
	}

      target = g_build_filename (dirname, target_basename, NULL);
      g_free (target_basename);
      g_free (dirname);
      g_free (base);
    }
  else if (generate_automatic)
    {
      if (extension_in_set (target, "c", "cc", "cpp", "cxx", "c++", NULL))
        generate_source = TRUE;
      else if (extension_in_set (target, "h", "hh", "hpp", "hxx", "h++", NULL))
        generate_header = TRUE;
      else if (extension_in_set (target, "gresource", NULL))
        { }
    }

  files = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);

  if ((table = parse_resource_file (srcfile, !generate_dependencies, files)) == NULL)
    {
      g_free (target);
      g_free (c_name);
      return 1;
    }

  /* This can be used in the same invocation
     as other generate commands */
  if (dependency_file != NULL)
    {
      /* Generate a .d file that describes the dependencies for
       * build tools, gcc -M -MF style */
      GString *dep_string;
      GHashTableIter iter;
      gpointer key, data;
      FileData *file_data;
      char *escaped;

      g_hash_table_iter_init (&iter, files);

      dep_string = g_string_new (NULL);
      escaped = escape_makefile_string (srcfile);
      g_string_printf (dep_string, "%s:", escaped);
      g_free (escaped);

      /* First rule: foo.xml: resource1 resource2.. */
      while (g_hash_table_iter_next (&iter, &key, &data))
        {
          file_data = data;
          if (!g_str_equal (file_data->filename, srcfile))
            {
              escaped = escape_makefile_string (file_data->filename);
              g_string_append_printf (dep_string, " %s", escaped);
              g_free (escaped);
            }
        }

      g_string_append (dep_string, "\n");

      /* Optionally include phony targets as it silences `make` but
       * isn't supported on `ninja` at the moment. See also: `gcc -MP`
       */
      if (generate_phony_targets)
        {
					g_string_append (dep_string, "\n");

          /* One rule for every resource: resourceN: */
          g_hash_table_iter_init (&iter, files);
          while (g_hash_table_iter_next (&iter, &key, &data))
            {
              file_data = data;
              if (!g_str_equal (file_data->filename, srcfile))
                {
                  escaped = escape_makefile_string (file_data->filename);
                  g_string_append_printf (dep_string, "%s:\n\n", escaped);
                  g_free (escaped);
                }
            }
        }

      if (g_str_equal (dependency_file, "-"))
        {
          g_print ("%s\n", dep_string->str);
        }
      else
        {
          if (!g_file_set_contents (dependency_file, dep_string->str, dep_string->len, &error))
            {
              g_printerr ("Error writing dependency file: %s\n", error->message);
              g_string_free (dep_string, TRUE);
              g_free (dependency_file);
              g_error_free (error);
              return 1;
            }
        }

      g_string_free (dep_string, TRUE);
      g_free (dependency_file);
    }

  if (generate_dependencies)
    {
      GHashTableIter iter;
      gpointer key, data;
      FileData *file_data;

      g_hash_table_iter_init (&iter, files);

      /* Generate list of files for direct use as dependencies in a Makefile */
      while (g_hash_table_iter_next (&iter, &key, &data))
        {
          file_data = data;
          g_print ("%s\n", file_data->filename);
        }
    }
  else if (generate_source || generate_header)
    {
      if (generate_source)
	{
	  int fd = g_file_open_tmp (NULL, &binary_target, NULL);
	  if (fd == -1)
	    {
	      g_printerr ("Can't open temp file\n");
	      g_free (c_name);
	      return 1;
	    }
	  close (fd);
	}

      if (c_name == NULL)
	{
	  char *base = g_path_get_basename (srcfile);
	  GString *s;
	  char *dot;
	  int i;

	  /* Remove extensions */
	  dot = strchr (base, '.');
	  if (dot)
	    *dot = 0;

	  s = g_string_new ("");

	  for (i = 0; base[i] != 0; i++)
	    {
	      const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
	      const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
	      if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
		g_string_append_c (s, base[i]);
	      else if (base[i] == '-')
		g_string_append_c (s, '_');

	    }

	  c_name = g_string_free (s, FALSE);
	}
    }
  else
    binary_target = g_strdup (target);

  c_name_no_underscores = c_name;
  while (c_name_no_underscores && *c_name_no_underscores == '_')
    c_name_no_underscores++;

  if (binary_target != NULL &&
      !write_to_file (table, binary_target, &error))
    {
      g_printerr ("%s\n", error->message);
      g_free (target);
      g_free (c_name);
      return 1;
    }

  if (generate_header)
    {
      FILE *file;

      file = fopen (target, "w");
      if (file == NULL)
	{
	  g_printerr ("can't write to file %s", target);
	  g_free (c_name);
	  return 1;
	}

      fprintf (file,
	       "#ifndef __RESOURCE_%s_H__\n"
	       "#define __RESOURCE_%s_H__\n"
	       "\n"
	       "#include <gio/gio.h>\n"
	       "\n"
	       "%s GResource *%s_get_resource (void);\n",
	       c_name, c_name, linkage, c_name);

      if (manual_register)
	fprintf (file,
		 "\n"
		 "%s void %s_register_resource (void);\n"
		 "%s void %s_unregister_resource (void);\n"
		 "\n",
		 linkage, c_name, linkage, c_name);

      fprintf (file,
	       "#endif\n");

      fclose (file);
    }
  else if (generate_source)
    {
      FILE *file;
      guint8 *data;
      gsize data_size;
      gsize i;

      if (!g_file_get_contents (binary_target, (char **)&data,
				&data_size, NULL))
	{
	  g_printerr ("can't read back temporary file");
	  g_free (c_name);
	  return 1;
	}
      g_unlink (binary_target);

      file = fopen (target, "w");
      if (file == NULL)
	{
	  g_printerr ("can't write to file %s", target);
	  g_free (c_name);
	  return 1;
	}

      fprintf (file,
	       "#include <gio/gio.h>\n"
	       "\n"
	       "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
	       "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
	       "#else\n"
	       "# define SECTION\n"
	       "#endif\n"
	       "\n"
	       "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;}  %s_resource_data = { {\n",
	       c_name_no_underscores, data_size, c_name);

      for (i = 0; i < data_size; i++) {
	if (i % 8 == 0)
	  fprintf (file, "  ");
	fprintf (file, "0x%2.2x", (int)data[i]);
	if (i != data_size - 1)
	  fprintf (file, ", ");
	if ((i % 8 == 7) || (i == data_size - 1))
	  fprintf (file, "\n");
      }

      fprintf (file, "} };\n");

      fprintf (file,
	       "\n"
	       "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data), NULL, NULL, NULL };\n"
	       "%s GResource *%s_get_resource (void);\n"
	       "GResource *%s_get_resource (void)\n"
	       "{\n"
	       "  return g_static_resource_get_resource (&static_resource);\n"
	       "}\n",
	       c_name, c_name, linkage, c_name, c_name);


      if (manual_register)
	{
	  fprintf (file,
		   "\n"
		   "%s void %s_unregister_resource (void);\n"
		   "void %s_unregister_resource (void)\n"
		   "{\n"
		   "  g_static_resource_fini (&static_resource);\n"
		   "}\n"
		   "\n"
		   "%s void %s_register_resource (void);\n"
		   "void %s_register_resource (void)\n"
		   "{\n"
		   "  g_static_resource_init (&static_resource);\n"
		   "}\n",
		   linkage, c_name, c_name, linkage, c_name, c_name);
	}
      else
	{
	  fprintf (file, "%s", gconstructor_code);
	  fprintf (file,
		   "\n"
		   "#ifdef G_HAS_CONSTRUCTORS\n"
		   "\n"
		   "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
		   "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
		   "#endif\n"
		   "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
		   "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
		   "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
		   "#endif\n"
		   "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
		   "\n"
		   "#else\n"
		   "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
		   "#endif\n"
		   "\n"
		   "static void resource_constructor (void)\n"
		   "{\n"
		   "  g_static_resource_init (&static_resource);\n"
		   "}\n"
		   "\n"
		   "static void resource_destructor (void)\n"
		   "{\n"
		   "  g_static_resource_fini (&static_resource);\n"
		   "}\n");
	}

      fclose (file);

      g_free (data);
    }

  g_free (binary_target);
  g_free (target);
  g_hash_table_destroy (table);
  g_free (xmllint);
  g_free (c_name);

  return 0;
}
Example #22
0
File: args.c Project: CTU-OSP/mc
gboolean
mc_args_parse (int *argc, char ***argv, const char *translation_domain, GError ** error)
{
    const gchar *_system_codepage;
    gboolean ok = TRUE;

    _system_codepage = str_detect_termencoding ();

#ifdef ENABLE_NLS
    if (!str_isutf8 (_system_codepage))
        bind_textdomain_codeset ("mc", "UTF-8");
#endif

    context = g_option_context_new (mc_args_add_usage_info ());

    g_option_context_set_ignore_unknown_options (context, FALSE);

    mc_args_add_extended_info_to_help ();

    main_group = g_option_group_new ("main", _("Main options"), _("Main options"), NULL, NULL);

    g_option_group_add_entries (main_group, argument_main_table);
    g_option_context_set_main_group (context, main_group);
    g_option_group_set_translation_domain (main_group, translation_domain);

    terminal_group = g_option_group_new ("terminal", _("Terminal options"),
                                         _("Terminal options"), NULL, NULL);

    g_option_group_add_entries (terminal_group, argument_terminal_table);
    g_option_context_add_group (context, terminal_group);
    g_option_group_set_translation_domain (terminal_group, translation_domain);

    color_group = mc_args_new_color_group ();

    g_option_group_add_entries (color_group, argument_color_table);
    g_option_context_add_group (context, color_group);
    g_option_group_set_translation_domain (color_group, translation_domain);

    if (!g_option_context_parse (context, argc, argv, error))
    {
        GError *error2 = NULL;

        if (*error == NULL)
            *error = g_error_new (MC_ERROR, 0, "%s\n", _("Arguments parse error!"));
        else
        {
            gchar *help_str;

#if GLIB_CHECK_VERSION(2,14,0)
            help_str = g_option_context_get_help (context, TRUE, NULL);
#else
            help_str = g_strdup ("");
#endif
            if (str_isutf8 (_system_codepage))
                error2 = g_error_new ((*error)->domain, (*error)->code, "%s\n\n%s\n",
                                      (*error)->message, help_str);
            else
            {
                gchar *full_help_str;

                full_help_str =
                    mc_args__convert_help_to_syscharset (_system_codepage, (*error)->message,
                                                         help_str);
                error2 = g_error_new ((*error)->domain, (*error)->code, "%s", full_help_str);
                g_free (full_help_str);
            }

            g_free (help_str);
            g_error_free (*error);
            *error = error2;
        }

        ok = FALSE;
    }

    g_option_context_free (context);
    mc_args_clean_temp_help_strings ();

#ifdef ENABLE_NLS
    if (!str_isutf8 (_system_codepage))
        bind_textdomain_codeset ("mc", _system_codepage);
#endif

    return ok;
}
Example #23
0
int 
main (int argc, char *argv[]) 
{
	int err, i;
	GNOME_Pilot_Survival survive;
	GError *error;
	GList *pilots = NULL;
	GOptionContext *option_context;
        
	bindtextdomain (PACKAGE, GNOMELOCALEDIR);
	textdomain (PACKAGE);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");

	if (argc<2) {
		g_message ("usage : %s [--now|--later] [--pilot PDA] [FILE ...]", argv[0]);
		exit (1);
	}

	option_context = g_option_context_new (PACKAGE);
	g_option_context_add_main_entries (option_context, options, NULL);
	if (!g_option_context_parse(option_context, &argc, &argv, &error)) {
		g_error (_("Error parsing commandline arguments: %s"), error->message);
		exit (1);
	}

	gtk_init (&argc, &argv);

	gpc = GNOME_PILOT_CLIENT (gnome_pilot_client_new ());
	g_object_ref_sink (G_OBJECT (gpc));
	g_signal_connect (G_OBJECT (gpc),"completed_request", G_CALLBACK(gpilotd_request_completed), NULL);
	gnome_pilot_client_connect_to_daemon (gpc);

	if (pilot_arg!=NULL) {
		pilots = g_list_append (pilots, g_strdup (pilot_arg));
	} else {
		err = gnome_pilot_client_get_pilots (gpc, &pilots);
		if (err !=GPILOTD_OK || pilots == NULL) {
			g_warning (_("Unable to get PDA names"));
			show_warning_dialog (_("Unable to get PDA names"));
			exit (1);
		}
	}

	notfailed = failed = handles = NULL;

	survive = GNOME_Pilot_IMMEDIATE;
	if (later) survive = GNOME_Pilot_PERSISTENT;
	
	i=0;

	while (filenames && filenames[i]!=NULL) {
		gint err;
		err = gnome_pilot_client_install_file (gpc,
						       pilots->data, /* get first pilot */
						       filenames[i],
						       survive,
						       0,
						       &handle);
		if (err == GPILOTD_OK) {
			handles = g_slist_prepend (handles,GINT_TO_POINTER(handle));
			notfailed = g_slist_prepend (notfailed, (void *) filenames[i]);
		} else {
			failed = g_slist_prepend (failed, (void *) filenames[i]);
		}
		i++;
	}

	if (!later) {
		gchar *message;
		
		message = NULL;
		if (failed != NULL) {
			GSList *e;
			message = g_strdup (_("Following files failed :\n"));
			for (e=failed;e;e = g_slist_next (e)) {
				gchar *tmp;
				tmp = g_strconcat (message,"\t- ", e->data,"\n", NULL);
				g_free (message);
				message = tmp;
			}
			g_slist_free (failed);
		}
		{
			GSList *e;
			if (message == NULL)
				message = g_strdup_printf (_("Installing to %s:\n"), (char*)pilots->data);
			else {
				gchar *tmp;
				tmp = g_strconcat (message,"\nInstalling to ", 
						   (char*)pilots->data, ":\n", NULL);
				g_free (message);
				message = tmp;
			}
			for (e=notfailed;e;e = g_slist_next (e)) {
				gchar *tmp;
				tmp = g_strconcat (message,"\t- ", e->data,"\n", NULL);
				g_free (message);
				message = tmp;
			}
			g_slist_free (notfailed);
		}
		{
			gchar *tmp;
			gchar *info;

			if (handles == NULL) 
				info = g_strdup (_("No files to install"));
			else {
				
				info = g_strdup (_("Press synchronize on the cradle to install\n" 
						  " or cancel the operation."));
                                err = gnome_pilot_client_conduit (gpc,
                                                            pilots->data,
                                                            "File",
                                                            GNOME_Pilot_CONDUIT_DEFAULT,
                                                            survive,
                                                            0,
                                                            &handle);
			}
						
			tmp = g_strconcat (message==NULL?"":message,
					  "\n",
					  info,
					  NULL);
			g_free (message);
			g_free (info);
			message = tmp;
		}
		dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL,
		    GTK_MESSAGE_OTHER, GTK_BUTTONS_CANCEL, "%s",
		    message);
		gint response = gtk_dialog_run(GTK_DIALOG(dialog));
		if (dialog != NULL) /* if not destroyed by callback */
			gtk_widget_destroy(dialog);
		if (response == GTK_RESPONSE_CANCEL) {
			GSList *e;
			for (e=handles;e;e = g_slist_next (e)) {
				gnome_pilot_client_remove_request
				    (gpc,GPOINTER_TO_INT(e->data));  
			}
			g_slist_free (handles);
		}
		g_free (message);
	}

	g_object_unref (G_OBJECT (gpc));

	return 0;
}
Example #24
0
File: ots.c Project: rohitgec/ots
int main(int argc, char **argv)
{
  char *dictionary_file = "en";	/* if not told otherwise, assume we're using english */
  const char *input_file = NULL;
  char *output_file = NULL;

  FILE *input_stream = stdin;	/*by default read from stdin */
  FILE *output_stream = stdout;	/*by default read from stdout */

  OtsArticle *Art;

  int sumPercent = 20;	 	/* if not told otherwise highlight 20% of the  document */

  int c,n_args=0;

  int html = FALSE;
  int keywords = FALSE;
  int about = FALSE;
  int version = FALSE;
	
  const char *const *args=NULL;

	GOptionContext *context = NULL;
	GError *error = NULL;
	
	const GOptionEntry options[] = {
		{"ratio"   , 'r', 0, G_OPTION_ARG_INT   , &sumPercent, "summarization % [default = 20%]", "<int>"},
		{"dic"     , 'd', 0, G_OPTION_ARG_STRING, &dictionary_file, "dictionary to use", "<string>"},
		{"out"     , 'o', 0, G_OPTION_ARG_STRING, &output_file, "output file [default = stdout]", "<string>"},
		{"html"    , 'h', 0, G_OPTION_ARG_NONE  , &html, "output as html", NULL},
		{"keywords", 'k', 0, G_OPTION_ARG_NONE  , &keywords, "only output keywords", NULL},
		{"about"   , 'a', 0, G_OPTION_ARG_NONE  , &about, "only output the summary", NULL},
		{"version" , 'v', 0, G_OPTION_ARG_NONE  , &version, "show version information", NULL},
		{ G_OPTION_REMAINING, '\0', 0, G_OPTION_ARG_FILENAME_ARRAY, &args, NULL, "[file.txt | stdin]" },
		{NULL}
  };

	context = g_option_context_new(" - Open Text Summarizer");
	g_option_context_add_main_entries(context, options, NULL);

        /* Parse command line */
        if (!g_option_context_parse (context, &argc, &argv, &error))
        {
                g_option_context_free (context);

                g_print ("%s\n", error->message);
                g_error_free (error);
                exit (1);
        }

	/* print version number */
  if (version)
    {
		printf("%s\n", PACKAGE_STRING);
		g_option_context_free(context);
      exit (0);
    }
  
  if(args==NULL) 
    {
       printf("\nInvalid number of arguments. Use --help to see options\n");
       exit(1);
    }
  if (args)
    while (args[n_args] != NULL)
      n_args++;

  if (n_args > 1)
    {
		g_option_context_free(context);
      return 1;
    }

	if (n_args == 1 && g_file_test (args[0], G_FILE_TEST_EXISTS) == TRUE)
    input_file = args[0];

  if (input_file)
    {
      input_stream = fopen (input_file, "r");
      if (!input_stream)
	{
			g_option_context_free(context);
	  perror ("Couldn't load input file");
	  return 1;
	}
    }

  if (output_file)
    {
      output_stream = fopen (output_file, "w");
      if (!output_stream)
	{
	  if (input_file)
	    fclose (input_stream);
			g_option_context_free(context);
	  perror ("Couldn't load output file");
	  return 1;
	}
    }

  Art = ots_new_article ();
	
  if (!ots_load_xml_dictionary (Art, dictionary_file))
    {
   
      ots_free_article (Art);
		if (input_file)
			fclose(input_stream);
		if (output_file)
			fclose(output_stream);
		g_option_context_free(context);
      perror ("Couldn't load dictionary");
      return 1;
    }


  ots_parse_file (input_stream, Art);	/* read article from stdin , put it in struct Article */
  ots_grade_doc (Art);					/* grade each sentence (how relevent is it to the text) */

/*
  int i;

  for (i=0;i<1000000;i++)
  {

    printf("\n word = %s ", ots_word_in_list(Art->ImpWords,i));

  }
*/

  ots_highlight_doc (Art, sumPercent);	/* highlight what we are going to print 0% - 100% of the words */


	if (html)
		ots_print_HTML(output_stream, Art);	/* print article in html form */
	else if (keywords)
		print_keywords(Art, input_file); 
	else if (about)
		print_about(output_stream, Art);
	else
		ots_print_doc(output_stream, Art);	/* print article in text */

  ots_free_article (Art);
 

  if (input_file)
    fclose (input_stream);

  if (output_file)
    fclose (output_stream);

  return 0;
}
int main(int argc, char *argv[])
{
  GstElement *pipeline, *bin, *effect_element, *convert, *sink;
  GstPad *pad, *ghost_pad;
  char *pipeline_str;
  GIOChannel *io_stdin = g_io_channel_unix_new(fileno(stdin));
  CustomData data;
  GstStateChangeReturn ret;
  gboolean list_effects = FALSE;
  gchar *effect_name = NULL;
  GError *error = NULL;
  GstPlugin *gaudiplugin;
  gchar *props_str = NULL;
  GOptionContext *context;
  GOptionEntry options[] = {
    { "list-effects", 'l', 0, G_OPTION_ARG_NONE, &list_effects,
      "list available effects and exits", NULL },
    { "effect", 'e', 0, G_OPTION_ARG_STRING, &effect_name,
      "set the desired effect", NULL },
    { "props", 'p', 0, G_OPTION_ARG_STRING, &props_str,
      "for property setting (-p \"silent,bool,true;adjustement,uint,150\")",
      NULL },
    { NULL }
  };

  setlocale(LC_ALL, "fr_FR.utf8");

  gst_init(&argc, &argv);

  gaudiplugin = gst_registry_find_plugin(GET_PLUGIN_REGISTRY, "gaudieffects");
  if (gaudiplugin == NULL) {
    g_print("Pas de plugin “gaudieffects” trouvé !! :(\n");
    return -1;
  }

  context = g_option_context_new("");
  g_option_context_add_main_entries(context, options, "");
  if (!g_option_context_parse(context, &argc, &argv, &error)) {
    g_print("option parsing failed: %s\n", error->message);
    return -1;
  }
  g_option_context_free(context);

  if (list_effects == TRUE)
    return  list_gaudieffects_features();

  if (argc > 1) {
    if (g_str_has_prefix(argv[1], "http://") ||
	g_str_has_prefix(argv[1], "ftp://"))
      pipeline_str = g_strdup_printf("%s uri=\"%s\"", PLAYBIN, argv[1]);
    else if (argv[1][0] == '~')
      pipeline_str = g_strdup_printf("%s uri=\"file://%s%s\"", PLAYBIN,
				     g_get_home_dir(), argv[1]+1);
    else if (g_file_test(argv[1], G_FILE_TEST_IS_REGULAR))
      pipeline_str = g_strdup_printf("playbin uri=\"file://%s\"", argv[1]);
    else
      pipeline_str = g_strdup_printf("%s uri=%s", PLAYBIN, DEFAULT_URI);
  } else
    pipeline_str = g_strdup_printf("%s uri=%s", PLAYBIN, DEFAULT_URI);

  g_io_add_watch(io_stdin, G_IO_IN, (GIOFunc)handle_keyboard, &data);

  pipeline = gst_parse_launch(pipeline_str, NULL);

  if (gst_plugin_is_loaded(gaudiplugin) == FALSE)
    gst_plugin_load(gaudiplugin);

  if (effect_name == NULL)
    effect_name = "solarize";

  effect_element = gst_element_factory_make(effect_name, effect_name);
  convert = gst_element_factory_make("videoconvert", "convert");
  sink = gst_element_factory_make("autovideosink", "video_sink");
  if (!effect_element || !convert || !sink) {
    g_printerr("Not all elements could be created.\n");
    return -1;
  }

  bin = gst_bin_new("video_sink_bin");
  gst_bin_add_many(GST_BIN(bin), effect_element, convert, sink, NULL);
  gst_element_link_many(effect_element, convert, sink, NULL);
  pad = gst_element_get_static_pad(effect_element, "sink");
  ghost_pad = gst_ghost_pad_new("sink", pad);
  gst_pad_set_active(ghost_pad, TRUE);
  gst_element_add_pad(bin, ghost_pad);
  gst_object_unref(pad);

  g_object_set(GST_OBJECT(pipeline), "video-sink", bin, NULL);

  if (props_str != NULL)
    set_props(effect_element, props_str);

  ret = gst_element_set_state(pipeline, GST_STATE_PLAYING);
  if (ret == GST_STATE_CHANGE_FAILURE) {
    g_printerr("Unable to set the pipeline to the playing state.\n");
    gst_object_unref(pipeline);
    return -1;
  }

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

  g_io_channel_unref(io_stdin);

  gst_element_set_state(pipeline, GST_STATE_NULL);

  gst_object_unref(pipeline);

  return 0;
}
Example #26
0
int
main (int   argc,
      char *argv[])
{
  GtkWidget *win, *vbox, *frame, *group_box;
  GtkWidget *hbox, *label, *chooser, *button;
  GtkSizeGroup *label_group;
  GOptionContext *context;
  gchar *cwd;

  context = g_option_context_new ("- test GtkFileChooserButton widget");
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  g_option_context_add_group (context, gtk_get_option_group (TRUE));
  g_option_context_parse (context, &argc, &argv, NULL);
  g_option_context_free (context);

  gtk_init (&argc, &argv);

  /* to test rtl layout, use "--right-to-left" */
  if (rtl)
    gtk_widget_set_default_direction (GTK_TEXT_DIR_RTL);

  cwd = g_get_current_dir();
  gtk_src_dir = g_path_get_dirname (cwd);
  g_free (cwd);

  win = gtk_dialog_new_with_buttons ("TestFileChooserButton", NULL, 0,
				     "_Quit", GTK_RESPONSE_CLOSE, NULL);
  g_signal_connect (win, "response", G_CALLBACK (gtk_main_quit), NULL);

  vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 18);
  g_object_set (vbox, "margin", 6, NULL);
  gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area (GTK_DIALOG (win))), vbox);

  frame = gtk_frame_new ("<b>GtkFileChooserButton</b>");
  gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_NONE);
  gtk_label_set_use_markup (GTK_LABEL (gtk_frame_get_label_widget (GTK_FRAME (frame))), TRUE);
  gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE);

  gtk_widget_set_halign (frame, GTK_ALIGN_FILL);
  gtk_widget_set_valign (frame, GTK_ALIGN_FILL);
  g_object_set (frame, "margin-top", 6, "margin-start", 12, NULL);

  label_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);

  group_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
  gtk_container_add (GTK_CONTAINER (frame), group_box);

  /* OPEN */
  hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
  gtk_box_pack_start (GTK_BOX (group_box), hbox, FALSE, FALSE);

  label = gtk_label_new_with_mnemonic ("_Open:");
  gtk_size_group_add_widget (GTK_SIZE_GROUP (label_group), label);
  gtk_label_set_xalign (GTK_LABEL (label), 0.0);
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE);

  chooser = gtk_file_chooser_button_new ("Select A File - testfilechooserbutton",
                                         GTK_FILE_CHOOSER_ACTION_OPEN);
  gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_file_chooser_remove_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), chooser);
  g_signal_connect (chooser, "current-folder-changed",
		    G_CALLBACK (chooser_current_folder_changed_cb), NULL);
  g_signal_connect (chooser, "selection-changed", G_CALLBACK (chooser_selection_changed_cb), NULL);
  g_signal_connect (chooser, "file-activated", G_CALLBACK (chooser_file_activated_cb), NULL);
  g_signal_connect (chooser, "update-preview", G_CALLBACK (chooser_update_preview_cb), NULL);
  gtk_box_pack_start (GTK_BOX (hbox), chooser, TRUE, TRUE);

  button = gtk_button_new_with_label ("Tests");
  g_signal_connect (button, "clicked", G_CALLBACK (tests_button_clicked_cb), chooser);
  gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE);

  /* SELECT_FOLDER */
  hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
  gtk_box_pack_start (GTK_BOX (group_box), hbox, FALSE, FALSE);

  label = gtk_label_new_with_mnemonic ("Select _Folder:");
  gtk_size_group_add_widget (GTK_SIZE_GROUP (label_group), label);
  gtk_label_set_xalign (GTK_LABEL (label), 0.0);
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE);

  chooser = gtk_file_chooser_button_new ("Select A Folder - testfilechooserbutton",
                                         GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
  gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_file_chooser_remove_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), chooser);
  g_signal_connect (chooser, "current-folder-changed",
		    G_CALLBACK (chooser_current_folder_changed_cb), NULL);
  g_signal_connect (chooser, "selection-changed", G_CALLBACK (chooser_selection_changed_cb), NULL);
  g_signal_connect (chooser, "file-activated", G_CALLBACK (chooser_file_activated_cb), NULL);
  g_signal_connect (chooser, "update-preview", G_CALLBACK (chooser_update_preview_cb), NULL);
  gtk_box_pack_start (GTK_BOX (hbox), chooser, TRUE, TRUE);

  button = gtk_button_new_with_label ("Tests");
  g_signal_connect (button, "clicked", G_CALLBACK (tests_button_clicked_cb), chooser);
  gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE);

  g_object_unref (label_group);

  gtk_widget_show_all (win);
  gtk_window_present (GTK_WINDOW (win));

  gtk_main ();

  return 0;
}
Example #27
0
/**
 * main:
 **/
int
main (int argc, char *argv[])
{
	CdUtilPrivate *priv;
	gboolean ret = TRUE;
	gboolean verbose = FALSE;
	guint retval = 1;
	g_autoptr(GError) error = NULL;
	g_autofree gchar *cmd_descriptions = NULL;
	g_autofree gchar *locale = NULL;
	g_autoptr(GFile) file = NULL;
	const GOptionEntry options[] = {
		{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
			/* TRANSLATORS: command line option */
			_("Show extra debugging information"), NULL },
		{ "locale", '\0', 0, G_OPTION_ARG_STRING, &locale,
			/* TRANSLATORS: command line option */
			_("The locale to use when setting localized text"), NULL },
		{ NULL}
	};

	setlocale (LC_ALL, "");

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

	/* create helper object */
	priv = g_new0 (CdUtilPrivate, 1);
	priv->rewrite_file = TRUE;
	priv->client = cd_client_new ();

	/* add commands */
	priv->cmd_array = g_ptr_array_new_with_free_func ((GDestroyNotify) cd_util_item_free);
	cd_util_add (priv->cmd_array,
		     "extract-vcgt",
		     /* TRANSLATORS: command description */
		     _("Generate the VCGT calibration of a given size"),
		     cd_util_extract_vcgt);
	cd_util_add (priv->cmd_array,
		     "md-clear",
		     /* TRANSLATORS: command description */
		     _("Clear any metadata in the profile"),
		     cd_util_clear_metadata);
	cd_util_add (priv->cmd_array,
		     "md-init",
		     /* TRANSLATORS: command description */
		     _("Initialize any metadata for the profile"),
		     cd_util_init_metadata);
	cd_util_add (priv->cmd_array,
		     "md-add",
		     /* TRANSLATORS: command description */
		     _("Add a metadata item to the profile"),
		     cd_util_add_metadata);
	cd_util_add (priv->cmd_array,
		     "md-remove",
		     /* TRANSLATORS: command description */
		     _("Remove a metadata item from the profile"),
		     cd_util_remove_metadata);
	cd_util_add (priv->cmd_array,
		     "set-copyright",
		     /* TRANSLATORS: command description */
		     _("Sets the copyright string"),
		     cd_util_set_copyright);
	cd_util_add (priv->cmd_array,
		     "set-description",
		     /* TRANSLATORS: command description */
		     _("Sets the description string"),
		     cd_util_set_description);
	cd_util_add (priv->cmd_array,
		     "set-manufacturer",
		     /* TRANSLATORS: command description */
		     _("Sets the manufacturer string"),
		     cd_util_set_manufacturer);
	cd_util_add (priv->cmd_array,
		     "set-model",
		     /* TRANSLATORS: command description */
		     _("Sets the model string"),
		     cd_util_set_model);
	cd_util_add (priv->cmd_array,
		     "md-fix",
		     /* TRANSLATORS: command description */
		     _("Automatically fix metadata in the profile"),
		     cd_util_set_fix_metadata);
	cd_util_add (priv->cmd_array,
		     "set-version",
		     /* TRANSLATORS: command description */
		     _("Set the ICC profile version"),
		     cd_util_set_version);
	cd_util_add (priv->cmd_array,
		     "export-tag-data",
		     /* TRANSLATORS: command description */
		     _("Export the tag data"),
		     cd_util_export_tag_data);

	/* sort by command name */
	g_ptr_array_sort (priv->cmd_array,
			  (GCompareFunc) cd_sort_command_name_cb);

	/* get a list of the commands */
	priv->context = g_option_context_new (NULL);
	cmd_descriptions = cd_util_get_descriptions (priv->cmd_array);
	g_option_context_set_summary (priv->context, cmd_descriptions);

	/* TRANSLATORS: program name */
	g_set_application_name (_("Color Management"));
	g_option_context_add_main_entries (priv->context, options, NULL);
	ret = g_option_context_parse (priv->context, &argc, &argv, &error);
	if (!ret) {
		/* TRANSLATORS: the user didn't read the man page */
		g_print ("%s: %s\n", _("Failed to parse arguments"),
			 error->message);
		goto out;
	}

	/* use explicit locale */
	priv->locale = g_strdup (locale);

	/* set verbose? */
	if (verbose) {
		g_setenv ("COLORD_VERBOSE", "1", FALSE);
	} else {
		g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
				   cd_util_ignore_cb, NULL);
	}

	/* the first option is always the filename */
	if (argc < 2) {
		g_print ("%s\n", "Filename must be the first argument");
		goto out;
	}

	/* open file */
	file = g_file_new_for_path (argv[1]);
	priv->icc = cd_icc_new ();
	ret = cd_icc_load_file (priv->icc,
				file,
				CD_ICC_LOAD_FLAGS_ALL,
				NULL,
				&error);
	if (!ret) {
		g_print ("%s\n", error->message);
		goto out;
	}

	/* run the specified command */
	ret = cd_util_run (priv, argv[2], (gchar**) &argv[2], &error);
	if (!ret) {
		g_print ("%s\n", error->message);
		goto out;
	}

	/* save file */
	if (priv->rewrite_file) {
		ret = cd_icc_save_file (priv->icc,
					file,
					CD_ICC_SAVE_FLAGS_NONE,
					NULL,
					&error);
		if (!ret) {
			g_print ("%s\n", error->message);
			goto out;
		}
	}

	/* success */
	retval = 0;
out:
	if (priv != NULL) {
		if (priv->cmd_array != NULL)
			g_ptr_array_unref (priv->cmd_array);
		g_option_context_free (priv->context);
		if (priv->icc != NULL)
			g_object_unref (priv->icc);
		g_object_unref (priv->client);
		g_free (priv->locale);
		g_free (priv);
	}
	return retval;
}
Example #28
0
int
main (int argc, char *argv[])
{
  gchar *target_times = NULL;
  gchar *ev_option = NULL;
  gchar *fn_option = NULL;

  GOptionEntry options[] = {
    {"ev-compensation", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_STRING,
          &ev_option,
        "EV compensation for source element GstPhotography interface", NULL},
    {"aperture", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT, &aperture,
          "Aperture (size of lens opening) for source element GstPhotography interface",
        NULL},
    {"flash-mode", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT,
          &flash_mode,
        "Flash mode for source element GstPhotography interface", NULL},
    {"scene-mode", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT,
          &scene_mode,
        "Scene mode for source element GstPhotography interface", NULL},
    {"exposure", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT64,
          &exposure,
          "Exposure time (in ms) for source element GstPhotography interface",
        NULL},
    {"iso-speed", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT,
          &iso_speed,
        "ISO speed for source element GstPhotography interface", NULL},
    {"white-balance-mode", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT,
          &wb_mode,
        "White balance mode for source element GstPhotography interface", NULL},
    {"colour-tone-mode", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT,
          &color_mode,
        "Colour tone mode for source element GstPhotography interface", NULL},
    {"directory", '\0', 0, G_OPTION_ARG_STRING, &fn_option,
        "Directory for capture file(s) (default is current directory)", NULL},
    {"mode", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT, &mode,
        "Capture mode (default = 0 (image), 1 = video)", NULL},
    {"capture-time", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT,
          &capture_time,
        "Time to capture video in seconds (default = 10)", NULL},
    {"capture-total", '\0', 0, G_OPTION_ARG_INT, &capture_total,
        "Total number of captures to be done (default = 1)", NULL},
    {"flags", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT, &flags,
        "Flags for camerabin, (default = 0x9)", NULL},
    {"mute", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_NONE, &mute,
        "Mute audio", NULL},
    {"zoom", '\0', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_INT, &zoom,
        "Zoom (100 = 1x (default), 200 = 2x etc.)", NULL},
    {"audio-src", '\0', 0, G_OPTION_ARG_STRING, &audiosrc_name,
        "Audio source used in video recording", NULL},
    {"audio-bitrate", '\0', 0, G_OPTION_ARG_INT, &audio_bitrate,
        "Audio bitrate (default 128000)", NULL},
    {"audio-samplerate", '\0', 0, G_OPTION_ARG_INT, &audio_samplerate,
        "Audio samplerate (default 48000)", NULL},
    {"audio-channels", '\0', 0, G_OPTION_ARG_INT, &audio_channels,
        "Audio channels (default 1)", NULL},
    {"video-src", '\0', 0, G_OPTION_ARG_STRING, &videosrc_name,
        "Video source used in still capture and video recording", NULL},
    {"audio-enc", '\0', 0, G_OPTION_ARG_STRING, &audioenc_name,
        "Audio encoder used in video recording", NULL},
    {"video-enc", '\0', 0, G_OPTION_ARG_STRING, &videoenc_name,
        "Video encoder used in video recording", NULL},
    {"image-enc", '\0', 0, G_OPTION_ARG_STRING, &imageenc_name,
        "Image encoder used in still capture", NULL},
    {"image-pp", '\0', 0, G_OPTION_ARG_STRING, &imagepp_name,
        "List of image post-processing elements separated with comma", NULL},
    {"video-mux", '\0', 0, G_OPTION_ARG_STRING, &videomux_name,
        "Muxer used in video recording", NULL},
    {"viewfinder-sink", '\0', 0, G_OPTION_ARG_STRING, &vfsink_name,
        "Viewfinder sink (default = fakesink)", NULL},
    {"image-width", '\0', 0, G_OPTION_ARG_INT, &image_width,
        "Width for image capture", NULL},
    {"image-height", '\0', 0, G_OPTION_ARG_INT, &image_height,
        "Height for image capture", NULL},
    {"view-framerate-num", '\0', 0, G_OPTION_ARG_INT, &view_framerate_num,
        "Framerate numerator for viewfinder", NULL},
    {"view-framerate-den", '\0', 0, G_OPTION_ARG_INT, &view_framerate_den,
        "Framerate denominator for viewfinder", NULL},
    {"src-colorspace", '\0', 0, G_OPTION_ARG_STRING, &src_csp,
        "Colorspace format for video source (e.g. YUY2, UYVY)", NULL},
    {"src-format", '\0', 0, G_OPTION_ARG_STRING, &src_format,
        "Video format for video source", NULL},
    {"preview-caps", '\0', 0, G_OPTION_ARG_STRING, &preview_caps_name,
        "Preview caps (e.g. video/x-raw-rgb,width=320,height=240)", NULL},
    {"video-source-filter", '\0', 0, G_OPTION_ARG_STRING, &video_src_filter,
        "Video filter to process all frames from video source", NULL},
    {"viewfinder-filter", '\0', 0, G_OPTION_ARG_STRING, &viewfinder_filter,
        "Filter to process all frames going to viewfinder sink", NULL},
    {"x-width", '\0', 0, G_OPTION_ARG_INT, &x_width,
        "X window width (default = 320)", NULL},
    {"x-height", '\0', 0, G_OPTION_ARG_INT, &x_height,
        "X window height (default = 240)", NULL},
    {"no-xwindow", '\0', 0, G_OPTION_ARG_NONE, &no_xwindow,
        "Do not create XWindow", NULL},
    {NULL}
  };

  GOptionContext *ctx;
  GError *err = NULL;

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

  ctx = g_option_context_new ("\n\ncamerabin command line test application.");
  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 we fail to create xwindow should we care? */
  if (!no_xwindow)
    create_host_window ();

  GST_DEBUG_CATEGORY_INIT (camerabin_test, "camerabin-test", 0,
      "camerabin test");

  /* FIXME: error handling */
  if (ev_option != NULL)
    ev_compensation = strtod (ev_option, (char **) NULL);

  if (vfsink_name == NULL)
    vfsink_name = g_strdup ("fakesink");

  filename = g_string_new (fn_option);
  if (filename->len == 0)
    filename = g_string_append (filename, ".");

  timer = g_timer_new ();

  /* init */
  if (setup_pipeline ()) {
    loop = g_main_loop_new (NULL, FALSE);
    g_idle_add ((GSourceFunc) run_pipeline, NULL);
    g_main_loop_run (loop);
    cleanup_pipeline ();
    g_main_loop_unref (loop);
  }
  /* free */
  g_string_free (filename, TRUE);
  g_free (ev_option);
  g_free (audiosrc_name);
  g_free (videosrc_name);
  g_free (audioenc_name);
  g_free (videoenc_name);
  g_free (imageenc_name);
  g_free (imagepp_name);
  g_free (videomux_name);
  g_free (vfsink_name);
  g_free (src_csp);
  g_free (src_format);
  g_free (target_times);
  g_timer_destroy (timer);

  if (window)
    XDestroyWindow (display, window);

  if (display)
    XCloseDisplay (display);

  return 0;
}
Example #29
0
gint
main(int argc,char *argv[])
{
   GError*  error = NULL;
   gchar*   program_name;
   gboolean mode_1d;

   g_thread_init( NULL );
   eh_init_glib();

   {
      GOptionContext* context = g_option_context_new( "Run hyperpycnal flow model." );

      g_option_context_add_main_entries( context , entries , NULL );

      if ( !g_option_context_parse( context , &argc , &argv , &error ) )
         eh_error( "Error parsing command line arguments: %s" , error->message );
   }

   _day            *= S_SECONDS_PER_DAY;

   if ( _version )
   {
      eh_fprint_version_info( stdout , "sakura" , 0 , 9 , 0 );
      eh_exit(0);
   }

   if ( _debug )
      g_setenv( "SAKURA_DEBUG" , "TRUE" , TRUE );

   program_name = g_path_get_basename( argv[0] );
   if ( strcasecmp( program_name , "sakura")==0 )
   {
      _angle   = 0.;
      mode_1d = TRUE;
   }

   if ( _verbose )
   {
      if ( mode_1d ) eh_info( "Operating in 1D mode (ignoring width information)." );
      else           eh_info( "Operating in 1.5D mode." );

      eh_info( "Duration of flow (days)   : %f" , _day*S_DAYS_PER_SECOND );
      eh_info( "Spreading angle (degrees) : %f" , _angle );
   }

   if ( !error )
   {
      gint i;
      Sakura_param_st*    param         = NULL;
      Sakura_bathy_st*    bathy_data    = NULL;
      Sakura_bathy_st*    bathy_data_0  = NULL;
      Sakura_flood_st**   flood_data    = NULL;
      Sakura_const_st*    const_data    = NULL;
      Sakura_sediment_st* sediment_data = NULL;
      Eh_dbl_grid         deposit;
      Eh_dbl_grid         total_deposit;
      const double        spreading_angle = tan(_angle*G_PI/180.);

      if (    ( param        = sakura_scan_parameter_file( _in_file            , &error ) )==NULL
           || ( flood_data   = sakura_scan_flood_file    ( _flood_file , param , &error ) )==NULL
           || ( bathy_data_0 = sakura_scan_bathy_file    ( _bathy_file , param , &error ) )==NULL )
         eh_error( "%s" , error->message );

      bathy_data    = sakura_copy_bathy_data         ( NULL       , bathy_data_0 );
      const_data    = sakura_set_constant_data       ( param      , bathy_data   );
      const_data    = sakura_set_constant_output_data( const_data , _data_file , _data_id , _data_int );
      sediment_data = sakura_set_sediment_data       ( param );

      deposit       = eh_grid_new( double , sediment_data->n_grains , bathy_data->len );
      total_deposit = eh_grid_new( double , sediment_data->n_grains , bathy_data->len );

      for ( i=0 ; flood_data[i] ; i++ )
      { /* Run each day of the flood */

         /* The width starts at the river width for each day */
         sakura_set_width( bathy_data , flood_data[i]->width , spreading_angle );

         sakura_run_flood( bathy_data , flood_data[i] , sediment_data , const_data , eh_dbl_grid_data(deposit) );

         eh_dbl_grid_add( total_deposit , deposit );

         if ( _data_file   ) sakura_write_data     ( _data_file  , deposit      );
         if ( _reset_bathy ) sakura_copy_bathy_data( bathy_data , bathy_data_0 );
      }

      sakura_write_output( _out_file , bathy_data , eh_dbl_grid_data(total_deposit) , sediment_data->n_grains );

      eh_grid_destroy( total_deposit , TRUE );
      eh_grid_destroy( deposit       , TRUE );
   }
Example #30
0
int
main (int argc,
      char *argv[])
{
  GTestDBus *bus;
  GError *error = NULL;
  GOptionContext *context;
  guint sig_term;
  guint sig_int;
  int i;
  gchar *guid = NULL;
  GDBusServer *direct_dbus_server = NULL;

  GOptionEntry entries[] = {
    { NULL }
  };

  signal (SIGPIPE, SIG_IGN);
  /* avoid gvfs (http://bugzilla.gnome.org/show_bug.cgi?id=526454) */
  g_setenv ("GIO_USE_VFS", "local", TRUE);

  g_setenv ("XDG_DATA_HOME", SRCDIR "/src/bridge/mock-resource/home", TRUE);
  g_setenv ("XDG_DATA_DIRS", SRCDIR "/src/bridge/mock-resource/system", TRUE);

  setup_path (argv[0]);

  g_type_init ();

  g_log_set_always_fatal (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR);

  sig_term = g_unix_signal_add (SIGTERM, on_signal_done, NULL);
  sig_int = g_unix_signal_add (SIGINT, on_signal_done, NULL);

  // System cockpit configuration file should not be loaded
  cockpit_config_file = NULL;

  context = g_option_context_new ("- test dbus json server");
  g_option_context_add_main_entries (context, entries, NULL);
  g_option_context_set_ignore_unknown_options (context, TRUE);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("test-server: %s\n", error->message);
      exit (2);
    }

  /* This isolates us from affecting other processes during tests */
  bus = g_test_dbus_new (G_TEST_DBUS_NONE);
  g_test_dbus_up (bus);
  bus_address = g_test_dbus_get_bus_address (bus);

  guid = g_dbus_generate_guid ();
  direct_dbus_server = g_dbus_server_new_sync ("unix:tmpdir=/tmp/dbus-tests",
                                               G_DBUS_SERVER_FLAGS_NONE,
                                               guid,
                                               NULL,
                                               NULL,
                                               &error);
  if (direct_dbus_server == NULL)
    {
      g_printerr ("test-server: %s\n", error->message);
      exit (3);
    }

  /* Skip the program name */
  argc--;
  argv++;

  /* Null terminate the bridge command line */
  bridge_argv = g_new0 (char *, argc + 2);
  for (i = 0; i < argc; i++)
    bridge_argv[i] = argv[i];
  bridge_argv[i] = "cockpit-bridge";

  loop = g_main_loop_new (NULL, FALSE);

  g_bus_own_name (G_BUS_TYPE_SESSION,
                       "com.redhat.Cockpit.DBusTests.Test",
                       G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT | G_BUS_NAME_OWNER_FLAGS_REPLACE,
                       on_bus_acquired,
                       on_name_acquired,
                       on_name_lost,
                       loop,
                       NULL);

  g_bus_own_name (G_BUS_TYPE_SESSION,
                         "com.redhat.Cockpit.DBusTests.Second",
                         G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT | G_BUS_NAME_OWNER_FLAGS_REPLACE,
                         NULL,
                         on_second_acquired,
                         on_name_lost,
                         loop,
                         NULL);

  g_signal_connect_object (direct_dbus_server,
                           "new-connection",
                           G_CALLBACK (on_new_direct_connection),
                           NULL, 0);
  g_dbus_server_start (direct_dbus_server);
  direct_address = g_dbus_server_get_client_address (direct_dbus_server);

  g_main_loop_run (loop);

  g_source_remove (sig_term);
  g_source_remove (sig_int);

  g_clear_object (&bridge);
  g_clear_object (&exported);
  g_clear_object (&exported_b);
  g_clear_object (&direct_dbus_server);
  g_clear_object (&direct);
  g_clear_object (&direct_b);
  g_main_loop_unref (loop);

  g_test_dbus_down (bus);
  g_object_unref (bus);
  g_free (bridge_argv);
  g_free (guid);

  return exit_code;
}