Exemple #1
0
void
parse_command_line(gint argc, gchar *argv[])
{
  GOptionContext *context;
  GOptionGroup *watcher;
  GError *error = NULL;
  gchar *help;
  gchar *current_dir, *file;
  gchar *config_file = NULL;
  gboolean verbose = FALSE;
  gint show_version = 0;
  gchar *watcher_path = NULL;
  gboolean watcher_recursive = CONFIG_KEY_WATCHER_RECURSIVE_DEFAULT;
  gint watcher_maxdepth = CONFIG_KEY_WATCHER_MAXDEPTH_DEFAULT;
  gchar *watcher_event = NULL;
  gboolean watcher_mount = CONFIG_KEY_WATCHER_MOUNT_DEFAULT;
  gboolean watcher_readable = CONFIG_KEY_WATCHER_READABLE_DEFAULT;
  gboolean watcher_writable = CONFIG_KEY_WATCHER_WRITABLE_DEFAULT;
  gboolean watcher_executable = CONFIG_KEY_WATCHER_EXECUTABLE_DEFAULT;
  gchar *watcher_size = NULL;
  gchar *watcher_type = NULL;
  gchar *watcher_user = NULL;
  gchar *watcher_group = NULL;
  gchar *watcher_include = NULL;
  gchar *watcher_exclude = NULL;
  gchar *watcher_exec = NULL;
  gboolean watcher_print = FALSE;
  gboolean watcher_print0 = FALSE;

  GOptionEntry main_entries[] =
    {
      { "file", 'f', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_FILENAME, &config_file,
          N_("Read configuration from file"), N_("FILE") },
      { "verbose", 'v', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, &verbose,
          N_("Set verbose output") },
      { "version", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_NONE, &show_version,
          N_("Show version information"), NULL },
      { NULL } };
  GOptionEntry watcher_entries[] =
    {
      { "path", 0, 0, G_OPTION_ARG_FILENAME, &watcher_path,
          N_("Path to watch for events"), N_("PATH") },
      { "recursive", 0, 0, G_OPTION_ARG_NONE, &watcher_recursive,
          N_("Enable recursive mode"), NULL },
      { "maxdepth", 0, 0, G_OPTION_ARG_INT, &watcher_maxdepth,
          N_("Maximum depth of recursion"), N_("LEVEL") },
      { "event", 0, 0, G_OPTION_ARG_STRING, &watcher_event,
          N_("Event to watch"), N_("EVENT") },
      { "mount", 0, 0, G_OPTION_ARG_NONE, &watcher_mount,
          N_("Don't descend directories on other filesystems"), NULL },
      { "readable", 0, 0, G_OPTION_ARG_NONE, &watcher_readable,
          N_("Matches files which are readable"), NULL },
      { "writable", 0, 0, G_OPTION_ARG_NONE, &watcher_writable,
          N_("Matches files which are writable"), NULL },
      { "executable", 0, 0, G_OPTION_ARG_NONE, &watcher_executable,
          N_("Matches files which are executable and directories which are searchable"), NULL },
      { "size", 0, 0, G_OPTION_ARG_STRING, &watcher_size,
          N_("Matches files using given size"), N_("N") },
      { "type", 0, 0, G_OPTION_ARG_STRING, &watcher_type,
          N_("Check file type"), N_("TYPE") },
      { "user", 0, 0, G_OPTION_ARG_STRING, &watcher_user,
          N_("Check owner user"), N_("NAME") },
      { "group", 0, 0, G_OPTION_ARG_STRING, &watcher_group,
          N_("Check owner group"), N_("NAME") },
      { "include", 0, 0, G_OPTION_ARG_STRING, &watcher_include,
          N_("Include files list"), N_("LIST") },
      { "exclude", 0, 0, G_OPTION_ARG_STRING, &watcher_exclude,
          N_("Exclude files list"), N_("LIST") },
      { "exec", 0, 0, G_OPTION_ARG_STRING, &watcher_exec,
          N_("Execute command on event"), N_("COMMAND") },
      { "print", 0, 0, G_OPTION_ARG_NONE, &watcher_print,
          N_("Print filename on event, followed by a newline") },
      { "print0", 0, 0, G_OPTION_ARG_NONE, &watcher_print0,
          N_("Print filename on event, followed by a null character") },
      { NULL } };

  context = g_option_context_new(N_("[WATCHER]"));

  watcher = g_option_group_new(N_("watcher"), N_("Watcher Options"),
      N_("Show all watcher options"), NULL, NULL);
  g_option_group_add_entries(watcher, watcher_entries);
  g_option_context_add_group(context, watcher);

  g_option_context_add_main_entries(context, main_entries, PACKAGE);

  g_option_context_parse(context, &argc, &argv, &error);
  if (error)
    {
      g_error_free(error);
      error = NULL;

      help = g_option_context_get_help(context, TRUE, NULL);
      g_print("%s", help);

      g_free(help);
      g_option_context_free(context);

      exit(1);
    }

  g_option_context_free(context);

  if (show_version == 1)
    {
      version();

      exit(0);
    }

  if (watcher_path)
    {
      app->settings = g_key_file_new();

      g_key_file_set_boolean(app->settings, CONFIG_GROUP_MAIN,
          CONFIG_KEY_MAIN_DAEMONIZE, CONFIG_KEY_MAIN_DAEMONIZE_NO);

      g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_PATH, watcher_path);
      g_key_file_set_boolean(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_RECURSIVE, watcher_recursive);
      g_key_file_set_integer(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_MAXDEPTH, watcher_maxdepth);

      if (watcher_event)
        g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
            CONFIG_KEY_WATCHER_EVENTS, watcher_event);

      g_key_file_set_boolean(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_MOUNT, watcher_mount);

      g_key_file_set_boolean(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_READABLE, watcher_readable);

      g_key_file_set_boolean(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_WRITABLE, watcher_writable);

      g_key_file_set_boolean(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_EXECUTABLE, watcher_executable);

      if (watcher_size)
        g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
            CONFIG_KEY_WATCHER_SIZE, watcher_size);

      if (watcher_type)
        g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
            CONFIG_KEY_WATCHER_TYPE, watcher_type);

      if (watcher_user)
        g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
            CONFIG_KEY_WATCHER_USER, watcher_user);

      if (watcher_group)
        g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
            CONFIG_KEY_WATCHER_GROUP, watcher_group);

      if (watcher_include)
        g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
            CONFIG_KEY_WATCHER_INCLUDE, watcher_include);

      if (watcher_exclude)
        g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
            CONFIG_KEY_WATCHER_EXCLUDE, watcher_exclude);

      if (watcher_exec)
        g_key_file_set_string(app->settings, CONFIG_GROUP_WATCHER,
            CONFIG_KEY_WATCHER_EXEC, watcher_exec);

      g_key_file_set_boolean(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_PRINT, watcher_print);

      g_key_file_set_boolean(app->settings, CONFIG_GROUP_WATCHER,
          CONFIG_KEY_WATCHER_PRINT0, watcher_print0);
    }
  else
    {
      if (config_file && !g_path_is_absolute(config_file))
        {
          current_dir = g_get_current_dir();
          file = g_build_filename(current_dir, config_file, NULL);

          g_free(current_dir);
          g_free(config_file);

          config_file = file;
        }

      app->config_file = get_default_config_file(config_file);
      if (!app->config_file)
        {
          g_printerr("%s\n",
              N_("The configuration file doesn't exist or cannot be read."));

          exit(1);
        }
    }

  app->verbose = verbose;
}
Exemple #2
0
int
main( int argc, char **argv )
{
	GOptionContext *context;
	GOptionGroup *main_group;
	GError *error = NULL;
	int i;
	int result;

	if( VIPS_INIT( argv[0] ) )
	        vips_error_exit( "unable to start VIPS" );
	textdomain( GETTEXT_PACKAGE );
	setlocale( LC_ALL, "" );

        context = g_option_context_new( _( "- thumbnail generator" ) );

	main_group = g_option_group_new( NULL, NULL, NULL, NULL, NULL );
	g_option_group_add_entries( main_group, options );
	vips_add_option_entries( main_group ); 
	g_option_group_set_translation_domain( main_group, GETTEXT_PACKAGE );
	g_option_context_set_main_group( context, main_group );

	if( !g_option_context_parse( context, &argc, &argv, &error ) ) {
		if( error ) {
			fprintf( stderr, "%s\n", error->message );
			g_error_free( error );
		}

		vips_error_exit( "try \"%s --help\"", g_get_prgname() );
	}

	g_option_context_free( context );

	if( sscanf( thumbnail_size, "%d x %d", 
		&thumbnail_width, &thumbnail_height ) != 2 ) {
		if( sscanf( thumbnail_size, "%d", &thumbnail_width ) != 1 ) 
			vips_error_exit( "unable to parse size \"%s\" -- "
				"use eg. 128 or 200x300", thumbnail_size );

		thumbnail_height = thumbnail_width;
	}

	if( rotate_image ) {
#ifndef HAVE_EXIF
		vips_warn( "vipsthumbnail", "%s",
			_( "auto-rotate disabled: "
			      "libvips built without exif support" ) );
#endif /*!HAVE_EXIF*/
	}

	result = 0;

	for( i = 1; i < argc; i++ ) {
		/* Hang resources for processing this thumbnail off @process.
		 */
		VipsObject *process = VIPS_OBJECT( vips_image_new() ); 

		if( thumbnail_process( process, argv[i] ) ) {
			fprintf( stderr, "%s: unable to thumbnail %s\n", 
				argv[0], argv[i] );
			fprintf( stderr, "%s", vips_error_buffer() );
			vips_error_clear();

			/* We had a conversion failure: return an error code
			 * when we finally exit.
			 */
			result = -1;
		}

		g_object_unref( process );
	}

	vips_shutdown();

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

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

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

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

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

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

        debug_log = g_file_new_for_path(debug_log_filename);

        GError *error = NULL;
        GFileOutputStream *debug_log_stream;

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

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

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

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


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

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

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

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

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

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

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

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

        g_key_file_free(key_file);
    }

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

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

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

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

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

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

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

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

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

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

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

    _j4status_core_start(context);

    if ( one_shot )
        g_idle_add(_j4status_core_source_quit, context);

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

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

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

    j4status_io_free(context->io);

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

    g_hash_table_unref(context->sections_hash);

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

    return retval;
}
Exemple #4
0
GOptionGroup *
gst_init_get_option_group (void)
{
#ifndef GST_DISABLE_OPTION_PARSING
  GOptionGroup *group;
  static const GOptionEntry gst_args[] = {
    {"gst-version", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
        (gpointer) parse_goption_arg, N_("Print the GStreamer version"), NULL},
    {"gst-fatal-warnings", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
        (gpointer) parse_goption_arg, N_("Make all warnings fatal"), NULL},
#ifndef GST_DISABLE_GST_DEBUG
    {"gst-debug-help", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Print available debug categories and exit"),
        NULL},
    {"gst-debug-level", 0, 0, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Default debug level from 1 (only error) to 9 (anything) or "
              "0 for no output"),
        N_("LEVEL")},
    {"gst-debug", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) parse_goption_arg,
          N_("Comma-separated list of category_name:level pairs to set "
              "specific levels for the individual categories. Example: "
              "GST_AUTOPLUG:5,GST_ELEMENT_*:3"),
        N_("LIST")},
    {"gst-debug-no-color", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg, N_("Disable colored debugging output"),
        NULL},
    {"gst-debug-color-mode", 0, 0, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Changes coloring mode of the debug log. "
              "Possible modes: off, on, disable, auto, unix"),
        NULL},
    {"gst-debug-disable", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
        (gpointer) parse_goption_arg, N_("Disable debugging"), NULL},
#endif
    {"gst-plugin-spew", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Enable verbose plugin loading diagnostics"),
        NULL},
    {"gst-plugin-path", 0, 0, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
        N_("Colon-separated paths containing plugins"), N_("PATHS")},
    {"gst-plugin-load", 0, 0, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Comma-separated list of plugins to preload in addition to the "
              "list stored in environment variable GST_PLUGIN_PATH"),
        N_("PLUGINS")},
    {"gst-disable-segtrap", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Disable trapping of segmentation faults during plugin loading"),
        NULL},
    {"gst-disable-registry-update", 0, G_OPTION_FLAG_NO_ARG,
          G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Disable updating the registry"),
        NULL},
    {"gst-disable-registry-fork", 0, G_OPTION_FLAG_NO_ARG,
          G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Disable spawning a helper process while scanning the registry"),
        NULL},
    {NULL}
  };

  group = g_option_group_new ("gst", _("GStreamer Options"),
      _("Show GStreamer Options"), NULL, NULL);
  g_option_group_set_parse_hooks (group, (GOptionParseFunc) init_pre,
      (GOptionParseFunc) init_post);

  g_option_group_add_entries (group, gst_args);
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);

  return group;
#else
  return NULL;
#endif
}
Exemple #5
0
    // ---- command line options
    void gx_process_cmdline_options(int& argc, char**& argv, string* optvar)
    {
      // store shell variable content
      for (int i = 0; i < NUM_SHELL_VAR; i++)
        gx_assign_shell_var(shell_var_name[i], optvar[i]);



      // ---- parse command line arguments
      try
        {
          gboolean version = FALSE;
          GOptionEntry opt_entries[] =
          {
            { "version", 'v', 0, G_OPTION_ARG_NONE, &version, "Print version string and exit", NULL },
            { NULL }
          };
          GError* error = NULL;
          GOptionContext* opt_context = NULL;

          opt_context = g_option_context_new(NULL);
          g_option_context_set_summary(opt_context,
                                       "All parameters are optional. Examples:\n"
                                       "\tjc_gui\n"
                                       "\tjc_gui -i system:capture_3 -i system:capture_2\n"
                                       "\tjc_gui -o system:playback_1 -o system:playback_2");
          g_option_context_add_main_entries(opt_context, opt_entries, NULL);



          // JACK options: input and output ports
          gchar** jack_input = NULL;
          gchar** jack_outputs = NULL;
          GOptionGroup* optgroup_jack = g_option_group_new("jack",
                                        "\033[1;32mJACK configuration options\033[0m",
                                        "\033[1;32mJACK configuration options\033[0m",
                                        NULL, NULL);
          GOptionEntry opt_entries_jack[] =
          {
            { "jack-input", 'i', 0, G_OPTION_ARG_STRING_ARRAY, &jack_input, "Jc_Gui JACK input", "PORT" },
            {"jack-output", 'o', 0, G_OPTION_ARG_STRING_ARRAY, &jack_outputs, "Jc_Gui JACK outputs", "PORT" },
            { NULL }
          };
          g_option_group_add_entries(optgroup_jack, opt_entries_jack);

          // collecting all option groups

          g_option_context_add_group(opt_context, optgroup_jack);

          // parsing command options
          if (!g_option_context_parse(opt_context, &argc, &argv, &error))
            {
              throw string(error->message);
            }
          g_option_context_free(opt_context);


          // ----------- processing user options -----------

          // *** display version if requested
          if (version)
            {
              cout << "Jc_Gui version \033[1;32m"
              << GX_VERSION << endl
              << "\033[0m   Copyright " << (char)0x40 << " 2009 "
              << "Hermman Meyer - James Warden"
              << endl;
              exit(0);
            }


// *** process jack outputs
          if (jack_input != NULL)
            {
              int idx = JACK_INP1;
              unsigned int i = 0;

              while (jack_input[i] != NULL)
                {
                  if (i >= 2)
                    {
                      gx_print_warning("main",
                                       "Warning --> provided more than 2 input ports, ignoring extra ports");
                      break;
                    }
                  optvar[idx] = string(jack_input[i]);
                  i++;
                  idx++;
                }
              g_strfreev(jack_input);
            }
          else
            {
              if (!gx_shellvar_exists(optvar[JACK_INP1])) optvar[JACK_INP1] = "";
              if (!gx_shellvar_exists(optvar[JACK_INP2])) optvar[JACK_INP2] = "";
            }


          // *** process jack outputs
          if (jack_outputs != NULL)
            {
              int idx = JACK_OUT1;
              unsigned int i = 0;

              while (jack_outputs[i] != NULL)
                {
                  if (i >= 2)
                    {
                      gx_print_warning("main",
                                       "Warning --> provided more than 2 output ports, ignoring extra ports");
                      break;
                    }
                  optvar[idx] = string(jack_outputs[i]);
                  i++;
                  idx++;
                }
              g_strfreev(jack_outputs);
            }
          else
            {
              if (!gx_shellvar_exists(optvar[JACK_OUT1])) optvar[JACK_OUT1] = "";
              if (!gx_shellvar_exists(optvar[JACK_OUT2])) optvar[JACK_OUT2] = "";
            }




        }

      // ---- catch exceptions that occured during user option parsing
      catch (string& e)
        {
          string msg = string("Error in user options! try -?  ") + e;
          gx_print_error("main", msg);
          exit(1);
        }
    }
Exemple #6
0
int
main (int argc, char *argv[])
{
	GError *error = NULL;
	GOptionGroup *option_group;
	GOptionContext *context;
	const gchar *simulation_filename, *introspection_filename;
	gchar *simulation_code, *introspection_xml;
	MainData data;
	GPtrArray/*<DfsmObject>*/ *simulated_objects;
	const gchar *test_program_name;
	GPtrArray/*<string>*/ *test_program_argv;
	guint i;
	gchar *time_str, *command_line, *log_header, *seed_str;
	GDateTime *date_time;
	GFile *working_directory_file, *dbus_daemon_config_file;

	/* Set up localisation. */
	setlocale (LC_ALL, "");
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

#if !GLIB_CHECK_VERSION (2, 35, 0)
	g_type_init ();
#endif
	g_set_application_name (_("D-Bus Simulator"));

	/* Take a copy of the command line, for use in printing the log headers later. */
	command_line = g_strjoinv (" ", argv);

	/* Parse command line options */
	context = g_option_context_new (_("[simulation code file] [introspection XML file] -- [executable-file] [arguments]"));
	g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
	g_option_context_set_summary (context, _("Simulates the server in a D-Bus client–server conversation."));
	g_option_context_add_main_entries (context, main_entries, GETTEXT_PACKAGE);

	/* Logging option group */
	option_group = g_option_group_new ("logging", _("Logging Options:"), _("Show help options for output logging"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, logging_entries);
	g_option_context_add_group (context, option_group);

	/* Testing option group */
	option_group = g_option_group_new ("testing", _("Testing Options:"), _("Show help options for test runs and timeouts"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, testing_entries);
	g_option_context_add_group (context, option_group);

	/* Test program option group */
	option_group = g_option_group_new ("test-program", _("Test Program Options:"), _("Show help options for the program under test"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, test_program_entries);
	g_option_context_add_group (context, option_group);

	/* dbus-daemon option group */
	option_group = g_option_group_new ("dbus-daemon", _("D-Bus Daemon Options:"), _("Show help options for the dbus-daemon"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, dbus_daemon_entries);
	g_option_context_add_group (context, option_group);

	if (g_option_context_parse (context, &argc, &argv, &error) == FALSE) {
		g_printerr (_("Error parsing command line options: %s"), error->message);
		g_printerr ("\n");

		print_help_text (context);

		g_error_free (error);
		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	/* Extract the simulation and the introspection filenames. */
	if (argc < 3) {
		g_printerr (_("Error parsing command line options: %s"), _("Simulation and introspection filenames must be provided"));
		g_printerr ("\n");

		print_help_text (context);

		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	simulation_filename = argv[1];
	introspection_filename = argv[2];

	/* Extract the remaining arguments */
	if (argc < 4) {
		g_printerr (_("Error parsing command line options: %s"), _("Test program must be provided"));
		g_printerr ("\n");

		print_help_text (context);

		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	/* Work out where the test program's command line starts. g_option_context_parse() sometimes leaves the ‘--’ in argv. */
	if (strcmp (argv[3], "--") == 0) {
		i = 4;
	} else {
		i = 3;
	}

	test_program_name = argv[i++];
	test_program_argv = g_ptr_array_new_with_free_func (g_free);

	for (; i < (guint) argc; i++) {
		g_ptr_array_add (test_program_argv, g_strdup (argv[i]));
	}

	g_option_context_free (context);

	/* Set up logging. */
	dsim_logging_init (test_program_log_file, test_program_log_fd, dbus_daemon_log_file, dbus_daemon_log_fd, simulator_log_file, simulator_log_fd,
	                   &error);

	if (error != NULL) {
		g_printerr (_("Error setting up logging: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		g_free (command_line);

		exit (STATUS_LOGGING_PROBLEM);
	}

	/* Output a log header to each of the log streams. */
	date_time = g_date_time_new_now_utc ();
	time_str = g_date_time_format (date_time, "%F %TZ");
	g_date_time_unref (date_time);

	log_header = g_strdup_printf (_("Bendy Bus (number %s) left the depot at %s using command line: %s"), PACKAGE_VERSION, time_str, command_line);

	g_log (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, "%s", log_header);
	g_log (dsim_logging_get_domain_name (DSIM_LOG_DBUS_DAEMON), G_LOG_LEVEL_MESSAGE, "%s", log_header);
	g_log (dsim_logging_get_domain_name (DSIM_LOG_TEST_PROGRAM), G_LOG_LEVEL_MESSAGE, "%s", log_header);

	g_free (log_header);
	g_free (time_str);
	g_free (command_line);

	/* Set up the random number generator. */
	if (random_seed == 0) {
		random_seed = g_get_real_time ();
	}

	seed_str = g_strdup_printf ("%" G_GINT64_FORMAT, random_seed);
	g_message (_("Note: Setting random number generator seed to %s."), seed_str);
	g_free (seed_str);

	g_random_set_seed ((guint32) random_seed);

	/* Load the files. */
	g_file_get_contents (simulation_filename, &simulation_code, NULL, &error);

	if (error != NULL) {
		g_printerr (_("Error loading simulation code from file ‘%s’: %s"), simulation_filename, error->message);
		g_printerr ("\n");

		g_error_free (error);

		exit (STATUS_UNREADABLE_FILE);
	}

	g_file_get_contents (introspection_filename, &introspection_xml, NULL, &error);

	if (error != NULL) {
		g_printerr (_("Error loading introspection XML from file ‘%s’: %s"), introspection_filename, error->message);
		g_printerr ("\n");

		g_error_free (error);
		g_free (simulation_code);

		exit (STATUS_UNREADABLE_FILE);
	}

	/* Build the DfsmObjects. */
	simulated_objects = dfsm_object_factory_from_data (simulation_code, introspection_xml, &error);

	g_free (introspection_xml);
	g_free (simulation_code);

	if (error != NULL) {
		g_printerr (_("Error creating simulated DFSMs: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);

		exit (STATUS_INVALID_CODE);
	}

	/* Prepare the main data struct, which will last for the lifetime of the program. */
	data.main_loop = g_main_loop_new (NULL, FALSE);
	data.exit_status = STATUS_SUCCESS;
	data.exit_signal = EXIT_SIGNAL_INVALID;
	data.test_program = NULL;
	data.connection = NULL;
	data.simulated_objects = g_ptr_array_ref (simulated_objects);
	data.outstanding_registration_callbacks = 0;
	data.test_run_inactivity_timeout_id = 0;
	data.test_program_spawn_end_signal = 0;
	data.test_program_process_died_signal = 0;
	data.test_program_sigkill_timeout_id = 0;

	if (run_infinitely == TRUE || (run_iters == 0 && run_time == 0)) {
		data.num_test_runs_remaining = -1;
	} else {
		data.num_test_runs_remaining = run_iters;
	}

	g_ptr_array_unref (simulated_objects);

	/* Store the test program name and argv, since we can only spawn it once we know the bus address. */
	data.test_program_name = g_strdup (test_program_name);
	data.test_program_argv = g_ptr_array_ref (test_program_argv);

	g_ptr_array_unref (test_program_argv);

	/* Set up signal handlers for SIGINT and SIGTERM so that we can close gracefully. */
	g_unix_signal_add (SIGINT, (GSourceFunc) sigint_handler_cb, &data);
	g_unix_signal_add (SIGTERM, (GSourceFunc) sigterm_handler_cb, &data);

	/* Create a working directory. */
	prepare_dbus_daemon_working_directory (&(data.working_directory_file), &working_directory_file, &dbus_daemon_config_file, &error);

	if (error != NULL) {
		g_printerr (_("Error creating dbus-daemon working directory: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		main_data_clear (&data);
		dsim_logging_finalise ();

		exit (STATUS_TMP_DIR_ERROR);
	}

	/* Start up our own private dbus-daemon instance. */
	data.dbus_daemon = dsim_dbus_daemon_new (working_directory_file, dbus_daemon_config_file);
	data.dbus_address = NULL;

	g_object_unref (dbus_daemon_config_file);
	g_object_unref (working_directory_file);

	g_signal_connect (data.dbus_daemon, "process-died", (GCallback) dbus_daemon_died_cb, &data);
	g_signal_connect (data.dbus_daemon, "notify::bus-address", (GCallback) dbus_daemon_notify_bus_address_cb, &data);

	dsim_program_wrapper_spawn (DSIM_PROGRAM_WRAPPER (data.dbus_daemon), &error);

	if (error != NULL) {
		g_printerr (_("Error spawning private dbus-daemon instance: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		main_data_clear (&data);
		dsim_logging_finalise ();

		exit (STATUS_DAEMON_SPAWN_ERROR);
	}

	/* Start the main loop and wait for the dbus-daemon to send us its address. */
	g_main_loop_run (data.main_loop);

	/* Free the main data struct. */
	main_data_clear (&data);
	dsim_logging_finalise ();

	if (data.exit_signal != EXIT_SIGNAL_INVALID) {
		struct sigaction action;

		/* Propagate the signal to the default handler. */
		action.sa_handler = SIG_DFL;
		sigemptyset (&action.sa_mask);
		action.sa_flags = 0;

		sigaction (data.exit_signal, &action, NULL);

		kill (getpid (), data.exit_signal);
	}

	return data.exit_status;
}
Exemple #7
0
gint
main (gint argc, gchar **argv, gchar **env)
{
	GError *error = NULL;
	GOptionContext *context;
	GOptionGroup *og;
	struct rspamd_config *cfg;
	GQuark process_quark;
	gchar **nargv, **targv;
	const gchar *cmd_name;
	const struct rspamadm_command *cmd;
	gint i, nargc, targc;

	ucl_vars = g_hash_table_new_full (rspamd_strcase_hash,
		rspamd_strcase_equal, g_free, g_free);
	process_quark = g_quark_from_static_string ("rspamadm");
	cfg = rspamd_config_new ();
	cfg->libs_ctx = rspamd_init_libs ();
	rspamd_main = g_malloc0 (sizeof (*rspamd_main));
	rspamd_main->cfg = cfg;
	rspamd_main->pid = getpid ();
	rspamd_main->type = process_quark;
	rspamd_main->server_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (),
			"rspamadm");

	cfg->log_level = G_LOG_LEVEL_WARNING;

	cfg->log_type = RSPAMD_LOG_CONSOLE;
	rspamd_set_logger (cfg, process_quark, rspamd_main);
	(void) rspamd_log_open (rspamd_main->logger);
	g_log_set_default_handler (rspamd_glib_log_function, rspamd_main->logger);
	g_set_printerr_handler (rspamd_glib_printerr_function);
	rspamd_config_post_load (cfg, FALSE);

	/* Setup logger */
	if (verbose) {
		cfg->log_level = G_LOG_LEVEL_DEBUG;
	}
	else {
		cfg->log_level = G_LOG_LEVEL_INFO;
	}

	gperf_profiler_init (cfg, "rspamadm");
	setproctitle ("rspamdadm");

	/* Now read options and store everything till the first non-dash argument */
	nargv = g_malloc0 (sizeof (gchar *) * (argc + 1));
	nargv[0] = g_strdup (argv[0]);

	for (i = 1, nargc = 1; i < argc; i ++) {
		if (argv[i] && argv[i][0] == '-') {
			/* Copy to nargv */
			nargv[nargc] = g_strdup (argv[i]);
			nargc ++;
		}
		else {
			break;
		}
	}

	context = g_option_context_new ("command - rspamd administration utility");
	og = g_option_group_new ("global", "global options", "global options",
			NULL, NULL);
	g_option_context_set_help_enabled (context, FALSE);
	g_option_group_add_entries (og, entries);
	g_option_context_set_summary (context,
			"Summary:\n  Rspamd administration utility version "
					RVERSION
					"\n  Release id: "
					RID);
	g_option_context_set_main_group (context, og);

	targv = nargv;
	targc = nargc;
	if (!g_option_context_parse (context, &targc, &targv, &error)) {
		fprintf (stderr, "option parsing failed: %s\n", error->message);
		g_error_free (error);
		exit (1);
	}

	g_strfreev (nargv);

	if (show_version) {
		rspamadm_version ();
		exit (EXIT_SUCCESS);
	}
	if (show_help) {
		rspamadm_usage (context);
		exit (EXIT_SUCCESS);
	}
	if (list_commands) {
		rspamadm_commands ();
		exit (EXIT_SUCCESS);
	}

	cmd_name = argv[nargc];

	if (cmd_name == NULL) {
		cmd_name = "help";
	}

	cmd = rspamadm_search_command (cmd_name);

	if (cmd == NULL) {
		fprintf (stderr, "Invalid command name: %s\n", cmd_name);
		exit (EXIT_FAILURE);
	}

	if (nargc < argc) {
		nargv = g_malloc0 (sizeof (gchar *) * (argc - nargc + 1));
		nargv[0] = g_strdup_printf ("%s %s", argv[0], cmd_name);

		for (i = 1; i < argc - nargc; i ++) {
			nargv[i] = g_strdup (argv[i + nargc]);
		}

		targc = argc - nargc;
		targv = nargv;
		cmd->run (targc, targv);
		g_strfreev (nargv);
	}
	else {
		cmd->run (0, NULL);
	}

	rspamd_log_close (rspamd_main->logger);
	REF_RELEASE (rspamd_main->cfg);
	g_free (rspamd_main);

	return 0;
}
Exemple #8
0
/* return value means the number of successfully loaded plugins */
static int
enumerate_plugins(const gchar *plugin_path, GPtrArray *plugin_array, GOptionContext *ctx)
{
  GDir *dir;
  const gchar *fname;

  dir = g_dir_open(plugin_path, 0, NULL);
  if (!dir)
    {
      ERROR("unable to open plugin directory %s (err=%s)\n", plugin_path, strerror(errno));
      return 0;
    }

  DEBUG("search for plugins in directory %s\n", plugin_path);

  /* add common options to help context: */
  g_option_context_add_main_entries(ctx, loggen_options, 0);

  GModule *module = NULL;
  while ((fname = g_dir_read_name(dir)))
    {
      if (!g_str_has_suffix(fname,G_MODULE_SUFFIX))
        continue;

      gchar *full_lib_path = g_build_filename(plugin_path,fname,NULL);
      module = g_module_open(full_lib_path, G_MODULE_BIND_LAZY);
      if (!module)
        {
          ERROR("error opening plugin module %s (%s)\n", fname, g_module_error());
          continue;
        }

      /* get plugin info from lib file */
      PluginInfo *plugin;
      if (!g_module_symbol(module, LOGGEN_PLUGIN_INFO, (gpointer *) &plugin))
        {
          DEBUG("%s isn't a plugin for loggen. skip it. (%s)\n", fname, g_module_error());
          g_module_close(module);
          continue;
        }

      if (is_plugin_already_loaded(plugin_array, plugin->name))
        {
          DEBUG("plugin %s was already loaded. skip it\n", plugin->name);
          continue;
        }

      if (plugin->set_generate_message)
        plugin->set_generate_message(generate_message);
      else
        ERROR("plugin (%s) doesn't have set_generate_message function\n",plugin->name);

      g_ptr_array_add(plugin_array, (gpointer) plugin);

      /* create sub group for plugin specific parameters: */
      GOptionGroup *group = g_option_group_new(plugin->name, plugin->name, "Show options", NULL, NULL);
      g_option_group_add_entries(group, plugin->get_options_list());
      g_option_context_add_group(ctx, group);

      DEBUG("%s in %s is a loggen plugin\n", plugin->name, fname);
    }

  if (plugin_array->len == 0)
    {
      ERROR("no loggen plugin found in %s\n", plugin_path);
    }

  return plugin_array->len;
}
Exemple #9
0
int
main(int argc, char *argv[])
{
  GPtrArray *plugin_array = g_ptr_array_new();
  GOptionContext *ctx = g_option_context_new(" target port");

  signal(SIGPIPE, signal_callback_handler);

  int plugin_num = enumerate_plugins(SYSLOG_NG_PATH_LOGGEN_PLUGIN_DIR, plugin_array, ctx);
  DEBUG("%d plugin successfuly loaded\n",plugin_num);

  /* create sub group for file reader functions */
  GOptionGroup *group = g_option_group_new("file-reader", "file-reader", "Show options", NULL, NULL);
  g_option_group_add_entries(group, get_file_reader_options());
  g_option_context_add_group(ctx, group);

  GError *error = NULL;
  if (!g_option_context_parse(ctx, &argc, &argv, &error))
    {
      ERROR("option parsing failed: %s\n", error->message);
      g_ptr_array_free(plugin_array,TRUE);
      if (error)
        g_error_free(error);
      return 1;
    }

  /* debug option defined by --debug command line option */
  set_debug_level(debug);

  if (argc>=3)
    {
      global_plugin_option.target = g_strdup(argv[1]);
      global_plugin_option.port = g_strdup(argv[2]);
    }
  else if (argc>=2)
    {
      global_plugin_option.target = g_strdup(argv[1]);
      global_plugin_option.port = NULL;
    }
  else
    {
      global_plugin_option.target = NULL;
      global_plugin_option.port = NULL;
      DEBUG("no port and address specified");
    }

  DEBUG("target=%s port=%s\n",global_plugin_option.target,global_plugin_option.port);

  if (global_plugin_option.message_length > MAX_MESSAGE_LENGTH)
    {
      ERROR("warning: defined message length (%d) is too big. truncated to (%d)\n",global_plugin_option.message_length,
            MAX_MESSAGE_LENGTH);
      global_plugin_option.message_length = MAX_MESSAGE_LENGTH;
    }

  read_from_file = init_file_reader(global_plugin_option.active_connections);
  if (read_from_file < 0)
    {
      ERROR("error while opening input file. exit.\n");
      return 1;
    }

  message_counter_lock = g_mutex_new();

  init_logline_generator(plugin_array);
  init_csv_statistics();

  if (start_plugins(plugin_array) > 0)
    {
      wait_all_plugin_to_finish(plugin_array);
      stop_plugins(plugin_array);
    }

  close_file_reader(global_plugin_option.active_connections);

  if (message_counter_lock)
    g_mutex_free(message_counter_lock);
  g_free((gpointer)global_plugin_option.target);
  g_free((gpointer)global_plugin_option.port);
  g_ptr_array_free(plugin_array,TRUE);
  g_free(thread_stat_count_last);
  g_free(thread_stat_count);
  return 0;
}
int
main (int argc, char **argv)
{
  GOptionContext *context;
  GOptionGroup *group;
  GError* err = NULL;
  int i;
  int args_len;
  mode_t dir_permissions;
  char *basename;

  setlocale (LC_ALL, "");

  basename = g_path_get_basename (argv[0]);
  if (g_strcmp0 (basename, "desktop-file-edit") == 0)
    edit_mode = TRUE;
  g_free (basename);

  context = g_option_context_new ("");
  g_option_context_set_summary (context, edit_mode ? _("Edit a desktop file.") : _("Install desktop files."));
  g_option_context_add_main_entries (context, main_options, NULL);

  if (!edit_mode)
    {
      group = g_option_group_new ("install", _("Installation options for desktop file"), _("Show desktop file installation options"), NULL, NULL);
      g_option_group_add_entries (group, install_options);
      g_option_context_add_group (context, group);
    }

  group = g_option_group_new ("edit", _("Edition options for desktop file"), _("Show desktop file edition options"), NULL, NULL);
  g_option_group_add_entries (group, edit_options);
  g_option_group_set_parse_hooks (group, NULL, post_parse_edit_options_callback);
  g_option_context_add_group (context, group);

  err = NULL;
  g_option_context_parse (context, &argc, &argv, &err);

  if (err != NULL) {
    g_printerr ("%s\n", err->message);
    g_printerr (_("Run '%s --help' to see a full list of available command line options.\n"), argv[0]);
    g_error_free (err);
    return 1;
  }

  if (!edit_mode)
    {
      if (vendor_name == NULL && g_getenv ("DESKTOP_FILE_VENDOR"))
        vendor_name = g_strdup (g_getenv ("DESKTOP_FILE_VENDOR"));

      if (target_dir == NULL && g_getenv ("DESKTOP_FILE_INSTALL_DIR"))
        target_dir = g_strdup (g_getenv ("DESKTOP_FILE_INSTALL_DIR"));

      if (target_dir == NULL)
        {
          if (g_getenv ("RPM_BUILD_ROOT"))
            target_dir = g_build_filename (g_getenv ("RPM_BUILD_ROOT"), DATADIR, "applications", NULL);
          else
            target_dir = g_build_filename (DATADIR, "applications", NULL);
        }

      /* Create the target directory */
      dir_permissions = permissions;

      /* Add search bit when the target file is readable */
      if (permissions & 0400)
        dir_permissions |= 0100;
      if (permissions & 0040)
        dir_permissions |= 0010;
      if (permissions & 0004)
        dir_permissions |= 0001;

      g_mkdir_with_parents (target_dir, dir_permissions);
    }

  args_len = 0;
  for (i = 0; args && args[i]; i++)
    args_len++;

  if (edit_mode)
    {
      if (args_len == 0)
        {
          g_printerr (_("Must specify a desktop file to process.\n"));
          return 1;
        }
      if (args_len > 1)
        {
          g_printerr (_("Only one desktop file can be processed at once.\n"));
          return 1;
        }
    }
  else
    {
      if (args_len == 0)
        {
          g_printerr (_("Must specify one or more desktop files to process.\n"));
          return 1;
        }
    }

  for (i = 0; args && args[i]; i++)
    {
      err = NULL;
      process_one_file (args[i], &err);
      if (err != NULL)
        {
          g_printerr (_("Error on file \"%s\": %s\n"),
                      args[i], err->message);
          g_error_free (err);

          return 1;
        }
    }

#if GLIB_CHECK_VERSION(2,28,0)
  g_slist_free_full (edit_actions, (GDestroyNotify) dfu_edit_action_free);
#else
  g_slist_foreach (edit_actions, (GFunc) dfu_edit_action_free, NULL);
  g_slist_free (edit_actions);
#endif

  g_option_context_free (context);

  return 0;
}
Exemple #11
0
GOptionContext *
yad_create_context (void)
{
  GOptionContext *tmp_ctx;
  GOptionGroup *a_group;

  tmp_ctx = g_option_context_new (_("Yet another dialoging program"));
  g_option_context_add_main_entries (tmp_ctx, rest_options, GETTEXT_PACKAGE);

  /* Adds general option entries */
  a_group = g_option_group_new ("general", _("General options"),
				_("Show general options"), NULL, NULL);
  g_option_group_add_entries (a_group, general_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds calendar option entries */
  a_group = g_option_group_new ("calendar", _("Calendar options"),
				_("Show calendar options"), NULL, NULL);
  g_option_group_add_entries (a_group, calendar_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds color option entries */
  a_group = g_option_group_new ("color", _("Color selection options"),
				_("Show color selection options"), NULL, NULL);
  g_option_group_add_entries (a_group, color_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds dnd option entries */
  a_group = g_option_group_new ("dnd", _("DND options"),
				_("Show drag-n-drop options"), NULL, NULL);
  g_option_group_add_entries (a_group, dnd_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds entry option entries */
  a_group = g_option_group_new ("entry", _("Text entry options"),
				_("Show text entry options"), NULL, NULL);
  g_option_group_add_entries (a_group, entry_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds file selection option entries */
  a_group = g_option_group_new ("file", _("File selection options"),
				_("Show file selection options"), NULL, NULL);
  g_option_group_add_entries (a_group, file_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Add font selection option entries */
  a_group = g_option_group_new ("font", _("Font selection options"),
				_("Show font selection options"), NULL, NULL);
  g_option_group_add_entries (a_group, font_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Add form option entries */
  a_group = g_option_group_new ("form", _("Form options"),
				_("Show form options"), NULL, NULL);
  g_option_group_add_entries (a_group, form_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Add icons option entries */
  a_group = g_option_group_new ("icons", _("Icons box options"),
				_("Show icons box options"), NULL, NULL);
  g_option_group_add_entries (a_group, icons_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds list option entries */
  a_group = g_option_group_new ("list", _("List options"),
				_("Show list options"), NULL, NULL);
  g_option_group_add_entries (a_group, list_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds notification option entries */
  a_group = g_option_group_new ("notification", _("Notification icon options"),
				_("Show notification icon options"), NULL, NULL);
  g_option_group_add_entries (a_group, notification_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds progress option entries */
  a_group = g_option_group_new ("progress", _("Progress options"),
				_("Show progress options"), NULL, NULL);
  g_option_group_add_entries (a_group, progress_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds scale option entries */
  a_group = g_option_group_new ("scale", _("Scale options"),
				_("Show scale options"), NULL, NULL);
  g_option_group_add_entries (a_group, scale_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds text option entries */
  a_group = g_option_group_new ("text", _("Text information options"),
				_("Show text information options"), NULL, NULL);
  g_option_group_add_entries (a_group, text_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds miscellaneous option entries */
  a_group = g_option_group_new ("misc", _("Miscellaneous options"),
				_("Show miscellaneous options"), NULL, NULL);
  g_option_group_add_entries (a_group, misc_options);
  g_option_group_set_translation_domain (a_group, GETTEXT_PACKAGE);
  g_option_context_add_group (tmp_ctx, a_group);

  /* Adds gtk option entries */
  a_group = gtk_get_option_group (TRUE);
  g_option_context_add_group (tmp_ctx, a_group);

  g_option_context_set_help_enabled (tmp_ctx, TRUE);
  g_option_context_set_ignore_unknown_options (tmp_ctx, FALSE);

  return tmp_ctx;
}
Exemple #12
0
BALDE_API void
balde_app_run(balde_app_t *app, gint argc, gchar **argv)
{
    setlocale(LC_ALL, "");
    GError *err = NULL;
    GOptionContext *context = g_option_context_new("- a balde application ;-)");
    g_option_context_add_main_entries(context, entries, NULL);

    GOptionGroup *http_group = g_option_group_new("http", "HTTP Options:",
        "Show HTTP help options", NULL, NULL);
    g_option_group_add_entries(http_group, entries_http);
    g_option_context_add_group(context, http_group);

    GOptionGroup *scgi_group = g_option_group_new("scgi", "SCGI Options:",
        "Show SCGI help options", NULL, NULL);
    g_option_group_add_entries(scgi_group, entries_scgi);
    g_option_context_add_group(context, scgi_group);

    g_option_context_set_help_enabled(context, FALSE);

    if (!g_option_context_parse(context, &argc, &argv, &err)) {
        g_printerr("Option parsing failed: %s\n", err->message);
        exit(1);
    }

    g_log_set_handler(BALDE_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL |
        G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO |
        G_LOG_LEVEL_DEBUG, balde_log_handler,
        GINT_TO_POINTER(balde_get_log_level_flag_from_string(log_level)));

    if (runserver && runscgi) {
        g_printerr("ERROR: --runserver conflicts with --runscgi\n");
        goto clean;
    }

    if (http_host != NULL)
        runserver = TRUE;

    if (scgi_host != NULL)
        runscgi = TRUE;

    if (help) {
        gchar *help_str = g_option_context_get_help(context, FALSE, NULL);
        g_print("%s", help_str);
        g_free(help_str);
    }
    else if (version) {
        g_printerr("%s\n", PACKAGE_STRING);
    }
    else if (runscgi) {
        balde_scgi_run(app, scgi_host, scgi_port, scgi_max_threads);
    }
    else if (runserver) {
        balde_httpd_run(app, http_host, http_port, http_max_threads);
    }
    else if (g_getenv("REQUEST_METHOD") != NULL) {
        balde_cgi_run(app);
    }
    else {
        gchar *help_str = g_option_context_get_help(context, FALSE, NULL);
        g_printerr("%s", help_str);
        g_free(help_str);
    }

clean:
    g_option_context_free(context);

    g_free(http_host);
    g_free(scgi_host);
    g_free(log_level);
}
Exemple #13
0
int
main (int argc, char *argv[])
{
	GError* error = NULL;
	GOptionContext *context;
	GOptionGroup* groupMain;
	GOptionGroup* groupSearch;
	GOptionGroup* groupPoll;


	g_type_init();

	context = g_option_context_new("\nArchive, Download, Parse, and render NEXRAD data");

	groupMain = g_option_group_new("Main", "", "", NULL, NULL);
	g_option_group_add_entries(groupMain, entriesMain);
	g_option_context_add_group(context, groupMain);
	g_option_context_set_ignore_unknown_options(context, TRUE);

	if (!g_option_context_parse(context, &argc, &argv, &error))
	{
		g_error("Failed to parse cli options (phase 1): %s", error->message);
		return 1;
	}

	if (!chrOp)
	{
		g_error("Operation required");
		return 1;
	}

	g_option_context_set_ignore_unknown_options(context, FALSE);

	groupSearch = g_option_group_new("Search", "Search through archived data", "Search through archived data", NULL, NULL);
	g_option_group_add_entries(groupSearch, entriesSearch);

	groupPoll = g_option_group_new("Poll", "Poll data from darxend", "Continually polls for data, archiving it in the process", NULL, NULL);
	g_option_group_add_entries(groupPoll, entriesPoll);

	if (!strcasecmp(chrOp, "search"))
	{
		g_option_context_add_group(context, groupSearch);
	}
	else if (!strcasecmp(chrOp, "poll"))
	{
		g_option_context_add_group(context, groupPoll);
	}
//	else if (!strcasecmp(chrOp, "render"))
//	{
//
//	}
//	else if (!strcasecmp(chrOp, "disp"))
//	{
//
//	}
	else
	{
		printf("Invalid operation: %s\n", chrOp);
	}

	if (!g_option_context_parse(context, &argc, &argv, &error))
	{
		g_error("Failed to parse cli options(phase 2): %s", error->message);
		return 1;
	}

	int res;

	if (!strcasecmp(chrOp, "search"))
	{
		res = main_search();
	}
	else if (!strcasecmp(chrOp, "poll"))
	{
		res = main_poll();
	}
//	else if (!strcasecmp(chrOp, "render"))
//	{
//
//	}
//	else if (!strcasecmp(chrOp, "disp"))
//	{
//
//	}

	//g_option_context_add_main_entries(context, entries, NULL);
	//g_option_context_set_ignore_unknown_options(context, TRUE);

	g_option_group_free(groupSearch);
	g_option_group_free(groupPoll);
	g_option_context_free(context);

	return res;
}
Exemple #14
0
int
main( int argc, char **argv )
{
	GOptionContext *context;
	GOptionGroup *main_group;
	GError *error = NULL;
	IMAGE *im;
	unsigned char header[IM_SIZEOF_HEADER];

	if( VIPS_INIT( argv[0] ) )
	        vips_error_exit( "%s", _( "unable to start VIPS" ) );
	textdomain( GETTEXT_PACKAGE );
	setlocale( LC_ALL, "" );

	context = g_option_context_new( 
		_( "vipsedit - edit vips file header" ) );
	main_group = g_option_group_new( NULL, NULL, NULL, NULL, NULL );
	g_option_group_add_entries( main_group, entries );
	vips_add_option_entries( main_group ); 
	g_option_group_set_translation_domain( main_group, GETTEXT_PACKAGE );
	g_option_context_set_main_group( context, main_group );

	if( !g_option_context_parse( context, &argc, &argv, &error ) ) {
		if( error ) {
			fprintf( stderr, "%s\n", error->message );
		        g_error_free( error );
		}

		exit( -1 );
	}
	if( argc != 2 ) {
		fprintf( stderr, _( "usage: %s [OPTION...] vips-file\n" ), 
			g_get_prgname() );
		exit( -1 );
	}

	if( !(im = im_init( argv[1] )) ||
		(im->fd = im__open_image_file( im->filename )) == -1 ) 
		error_exit( _( "could not open image %s" ), argv[1] );
	if( read( im->fd, header, IM_SIZEOF_HEADER ) != IM_SIZEOF_HEADER ||
		im__read_header_bytes( im, header ) ) 
		error_exit( _( "could not read VIPS header for %s" ), 
			im->filename );

	if( endian ) {
		if( strcmp( endian, "little" ) == 0 )
			im->magic = VIPS_MAGIC_INTEL;
		else if( strcmp( endian, "big" ) == 0 )
			im->magic = VIPS_MAGIC_SPARC;
		else 
			error_exit( _( "bad endian-ness %s, "
				"should be 'big' or 'little'" ), endian );
	}
	if( xsize ) 
		parse_pint( xsize, &im->Xsize );
	if( ysize ) 
		parse_pint( ysize, &im->Ysize );
	if( bands ) 
		parse_pint( bands, &im->Bands );
	if( format ) {
		VipsBandFormat f;

		if( (f = im_char2BandFmt( format )) < 0 )
			error_exit( _( "bad format %s" ), format );
		im->BandFmt = f;
		im->Bbits = im_bits_of_fmt( f );
	}
	if( interpretation ) {
		VipsInterpretation i;

		if( (i = im_char2Type( interpretation )) < 0 )
			error_exit( _( "bad interpretation %s" ), 
				interpretation );
		im->Type = i;
	}
	if( coding ) {
		VipsCoding c;

		if( (c = im_char2Coding( coding )) < 0 )
			error_exit( _( "bad coding %s" ), coding );
		im->Coding = c;
	}
	if( xres ) 
		im->Xres = atof( xres );
	if( yres ) 
		im->Yres = atof( yres );
	if( xoffset ) 
		im->Xoffset = atoi( xoffset );
	if( yoffset ) 
		im->Yoffset = atoi( yoffset );

	if( lseek( im->fd, 0, SEEK_SET ) == (off_t) -1 ) 
		error_exit( _( "could not seek on %s" ), im->filename );
	if( im__write_header_bytes( im, header ) ||
		im__write( im->fd, header, IM_SIZEOF_HEADER ) )
		error_exit( _( "could not write to %s" ), im->filename );

	if( setext ) {
		char *xml;
		size_t size;

		if( !(xml = im__file_read( stdin, "stdin", &size )) )
			error_exit( "%s", _( "could not get ext data" ) );

		/* Strip trailing whitespace ... we can get stray \n at the 
		 * end, eg. "echo | editvips --setext fred.v".
		 */
		while( size > 0 && isspace( xml[size - 1] ) )
			size -= 1;

		if( im__write_extension_block( im, xml, size ) )
			error_exit( "%s", _( "could not set extension" ) );
		im_free( xml );
	}

	im_close( im );

	vips_shutdown();

	return( 0 );
}
Exemple #15
0
int rm_hasher_main(int argc, const char **argv) {
    RmHasherSession tag;

    /* List of paths we got passed (or NULL)   */
    tag.paths = NULL;

    /* Print hashes in the same order as files in command line args */
    tag.print_in_order = TRUE;

    /* Print a hash with builtin identifier */
    tag.print_multihash = FALSE;

    /* Digest type (user option, default SHA1) */
    tag.digest_type = RM_DIGEST_SHA1;
    gint threads = 8;
    gint64 buffer_mbytes = 256;

    ////////////// Option Parsing ///////////////

    /* clang-format off */

    const GOptionEntry entries[] = {
        {"digest-type"    , 'd'  , 0                      , G_OPTION_ARG_CALLBACK        , (GOptionArgFunc)rm_hasher_parse_type  , _("Digest type [SHA1]")                                                            , "[TYPE]"}   ,
        {"num-threads"    , 't'  , 0                      , G_OPTION_ARG_INT             , &threads                              , _("Number of hashing threads [8]")                                                 , "N"}        ,
        {"multihash"      , 'm'  , 0                      , G_OPTION_ARG_NONE            , &tag.print_multihash                  , _("Print hash as self identifying multihash")                                      , NULL}       ,
        {"buffer-mbytes"  , 'b'  , 0                      , G_OPTION_ARG_INT64           , &buffer_mbytes                        , _("Megabytes read buffer [256 MB]")                                                , "MB"}       ,
        {"ignore-order"   , 'i'  , G_OPTION_FLAG_REVERSE  , G_OPTION_ARG_NONE            , &tag.print_in_order                   , _("Print hashes in order completed, not in order entered (reduces memory usage)")  , NULL}       ,
        {""               , 0    , 0                      , G_OPTION_ARG_FILENAME_ARRAY  , &tag.paths                            , _("Space-separated list of files")                                                 , "[FILE…]"}  ,
        {NULL             , 0    , 0                      , 0                            , NULL                                  , NULL                                                                               , NULL}};

    /* clang-format on */

    GError *error = NULL;
    GOptionContext *context = g_option_context_new(_("Hash a list of files"));
    GOptionGroup *main_group =
        g_option_group_new(argv[0], _("Hash a list of files"), "", &tag, NULL);

    char summary[4096];
    memset(summary, 0, sizeof(summary));

    g_snprintf(summary, sizeof(summary),
               _("Multi-threaded file digest (hash) calculator.\n"
                 "\n  Available digest types:"
                 "\n    %s\n"
                 "\n  Versions with different bit numbers:"
                 "\n    %s\n"
                 "\n  Supported, but not useful:"
                 "\n    %s\n"),
               "spooky, city, xxhash, sha{1,256,512}, md5, murmur",
               "spooky{32,64,128}, city{128,256,512}, murmur{512}",
               "farmhash, cumulative, paranoid, ext, bastard");

    g_option_group_add_entries(main_group, entries);
    g_option_context_set_main_group(context, main_group);
    g_option_context_set_summary(context, summary);

    if(!g_option_context_parse(context, &argc, (char ***)&argv, &error)) {
        /* print g_option error message */
        rm_log_error_line("%s", error->message);
        exit(EXIT_FAILURE);
    }

    if(tag.paths == NULL) {
        /* read paths from stdin */
        char path_buf[PATH_MAX];
        char *tokbuf = NULL;
        GPtrArray *paths = g_ptr_array_new();

        while(fgets(path_buf, PATH_MAX, stdin)) {
            char *abs_path = realpath(strtok_r(path_buf, "\n", &tokbuf), NULL);
            g_ptr_array_add(paths, abs_path);
        }

        tag.paths = (char **)g_ptr_array_free(paths, FALSE);
    }

    if(tag.paths == NULL || tag.paths[0] == NULL) {
        rm_log_error_line(_("No valid paths given."));
        exit(EXIT_FAILURE);
    }

    g_option_context_free(context);

    ////////// Implementation //////

    if(tag.print_in_order) {
        /* allocate buffer to collect results */
        tag.completed_digests_buffer =
            g_slice_alloc0((g_strv_length(tag.paths) + 1) * sizeof(RmDigest *));
        tag.path_index = 0;
    }

    /* initialise structures */
    g_mutex_init(&tag.lock);
    RmHasher *hasher = rm_hasher_new(tag.digest_type,
                                     threads,
                                     FALSE,
                                     4096,
                                     1024 * 1024 * buffer_mbytes,
                                     0,
                                     (RmHasherCallback)rm_hasher_callback,
                                     &tag);

    /* Iterate over paths, pushing to hasher threads */
    for(int i = 0; tag.paths && tag.paths[i]; ++i) {
        /* check it is a regular file */

        RmStat stat_buf;
        if(rm_sys_stat(tag.paths[i], &stat_buf) == -1) {
            rm_log_warning_line(_("Can't open directory or file \"%s\": %s"),
                                tag.paths[i], strerror(errno));
        } else if(S_ISDIR(stat_buf.st_mode)) {
            rm_log_warning_line(_("Directories are not supported: %s"), tag.paths[i]);
        } else if(S_ISREG(stat_buf.st_mode)) {
            RmHasherTask *task = rm_hasher_task_new(hasher, NULL, GINT_TO_POINTER(i));
            rm_hasher_task_hash(task, tag.paths[i], 0, 0, FALSE);
            rm_hasher_task_finish(task);
            continue;
        } else {
            rm_log_warning_line(_("%s: Unknown file type"), tag.paths[i]);
        }

        /* dummy callback for failed paths */
        g_free(tag.paths[i]);
        tag.paths[i] = NULL;
        rm_hasher_callback(hasher, NULL, &tag, GINT_TO_POINTER(i));
    }

    /* wait for all hasher threads to finish... */
    rm_hasher_free(hasher, TRUE);

    /* tidy up */
    if(tag.print_in_order) {
        g_slice_free1((g_strv_length(tag.paths) + 1) * sizeof(RmDigest *),
                      tag.completed_digests_buffer);
    }

    g_strfreev(tag.paths);

    return EXIT_SUCCESS;
}
Exemple #16
0
static void
test_g_option_group (void)
{
  g_autoptr(GOptionGroup) val = g_option_group_new ("hello", "world", "helpme", NULL, NULL);
  g_assert (val != NULL);
}
Exemple #17
0
static GSwatSession *
parse_args (int *argc, char ***argv)
{
  GOptionContext *option_context;
  GOptionGroup *group;
  GError *error = NULL;
  GSwatSession *session = NULL;

  option_context = g_option_context_new ("[executable-file "
                                         "[core-file or process-id]]");
  //g_option_context_set_ignore_unknown_options (option_context, TRUE);
  //g_option_context_set_help_enabled (option_context, TRUE);

  group = g_option_group_new ("bosh",
                              _("Bosh Options"),
                              _("Show Bosh options"),
                              NULL, NULL);

  g_option_group_set_parse_hooks (group, pre_parse_hook, NULL);
  g_option_group_add_entries (group, bosh_args);
  //g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);

  g_option_context_set_main_group (option_context, group);

  if (!g_option_context_parse (option_context, argc, argv, &error))
    {
      if (error)
        {
          g_warning ("%s", error->message);
          g_error_free (error);
        }
    }

  /* First we see if the user has described a new session on the command line
   */
  if (pid != -1)
    {
      gchar *target;
      if (!remaining_args)
        {
          g_message ("%s",
                     g_option_context_get_help (option_context, TRUE, NULL));
          exit (1);
        }
      session = gswat_session_new ();
      gswat_session_set_target_type (session, "PID Local");
      target = g_strdup_printf ("pid=%d file=%s", pid, remaining_args[0]);
      gswat_session_set_target (session, target);
      g_free (target);
    }
  else if (remaining_args != NULL)
    {
      int i;
      GString *target;
      session = gswat_session_new ();
      gswat_session_set_target_type (session, "Run Local");
      target = g_string_new (remaining_args[0]);
      for (i=1; remaining_args[i] != NULL; i++)
        {
          g_string_append_printf (target, " %s",
                                 g_shell_quote (remaining_args[i]));
        }
      gswat_session_set_target (session, target->str);
      g_string_free (target, TRUE);
    }

  g_option_context_free (option_context);

  return session;
}
Exemple #18
0
int
main (int argc, char *argv[])
{
    GError *error = NULL;
    GOptionContext *context = NULL;
    gboolean rval = FALSE;
    GumConfig *config = NULL;
    gchar *sysroot = NULL;
    gchar *user_types = NULL;

    gboolean is_user_list_op = FALSE;
    GOptionGroup* user_serv_option = NULL;

    gboolean is_user_add_op = FALSE, is_user_del_op = FALSE;
    gboolean is_user_up_op = FALSE, is_user_get_op = FALSE;
    gboolean is_user_get_by_name_op = FALSE;
    GOptionGroup* user_option = NULL;
    InputUser *user = NULL;
    
    gboolean is_group_add_op = FALSE, is_group_del_op = FALSE;
    gboolean is_group_up_op = FALSE, is_group_get_op = FALSE;
    gboolean is_group_get_by_name_op = FALSE, is_group_add_mem_op = FALSE;
    gboolean is_group_del_mem_op = FALSE;
    gboolean is_write_nfc = FALSE;
    GOptionGroup* group_option = NULL;
    InputGroup *group = NULL;

    user = _create_test_user();
    group = _create_test_group();

    GOptionEntry main_entries[] =
    {
        { "add-user", 'a', 0, G_OPTION_ARG_NONE, &is_user_add_op, "add user"
                " -- username (or nickname) and user_type is mandatory", NULL},
        { "delete-user", 'd', 0, G_OPTION_ARG_NONE, &is_user_del_op,
                "delete user -- uid is mandatory", NULL},
        { "update-user", 'u', 0, G_OPTION_ARG_NONE, &is_user_up_op,
                "update user -- uid is mandatory; possible props that can be "
                "updated are secret, realname, office, officephone, homephone "
                "and shell", NULL},
        { "get-user", 'b', 0, G_OPTION_ARG_NONE, &is_user_get_op, "get user"
                " -- uid is mandatory", NULL},
        { "get-user-by-name", 'c', 0, G_OPTION_ARG_NONE,
                &is_user_get_by_name_op, "get user by name -- username is"
                        " mandatory", NULL},

        { "add-group", 'g', 0, G_OPTION_ARG_NONE, &is_group_add_op, "add group"
                " -- groupname and group_type are mandatory", NULL},
        { "delete-group", 'h', 0, G_OPTION_ARG_NONE, &is_group_del_op,
                "delete group -- gid is mandatory", NULL},
        { "update-group", 'i', 0, G_OPTION_ARG_NONE, &is_group_up_op,
                "update group -- gid is mandatory; possible props that can be "
                "updated are secret", NULL},
        { "get-group", 'j', 0, G_OPTION_ARG_NONE, &is_group_get_op, "get group"
                " -- gid is mandatory",
                NULL},
        { "get-group-by-name", 'k', 0, G_OPTION_ARG_NONE,
                &is_group_get_by_name_op, "get group by name -- groupname"
                        " is mandatory", NULL},
        { "add-member", 'm', 0, G_OPTION_ARG_NONE, &is_group_add_mem_op,
                "group add member -- gid and mem_uid are mandatory", NULL},
        { "delete-member", 'n', 0, G_OPTION_ARG_NONE, &is_group_del_mem_op,
                "group delete member -- gid and mem_uid are mandatory", NULL},
        { "write-nfc", 'p', 0, G_OPTION_ARG_NONE, &is_write_nfc,
                "write username and secret to an NFC tag when creating or"
                " updating a user", NULL},
        { "offline", 'o', 0, G_OPTION_ARG_NONE, &offline_mode,
                "offline mode triggers libgum synchronous APIs without (dbus) "
                "gumd to perform op add/delete/update/get",
                NULL},
        { "sysroot", 'q', 0, G_OPTION_ARG_STRING, &sysroot, "sysroot path "
                "[Offline mode ONLY]", "sysroot"},
        { "user-list", 'r', 0, G_OPTION_ARG_NONE, &is_user_list_op,
                "if usertypes argument is specified, then the calls will "
                "return the specified users only otherwise all the users will "
                "be returned", NULL},
        { NULL }
    };
    
    GOptionEntry user_serv_entries[] =
    {
        { "usertypes", 0, 0, G_OPTION_ARG_STRING, &user_types,
                "valid usertypes can be system or admin or guest or normal."
                "Multiple user types can be specified as comma separated "
                "values e.g. normal,system",
                "type"},
        { NULL }
    };

    GOptionEntry user_entries[] =
    {
        { "username", 0, 0, G_OPTION_ARG_STRING, &user->user_name,
                "user name", "name"},
        { "usertype", 0, 0, G_OPTION_ARG_STRING, &user->user_type,
                "valid user_type can be system or admin or guest or normal.",
                "type"},
        { "uid", 0, 0, G_OPTION_ARG_INT, &user->uid, "user id", "uid"},
        { "ugid", 0, 0, G_OPTION_ARG_INT, &user->gid, "group id", "gid"},
        { "usecret", 0, 0, G_OPTION_ARG_STRING, &user->secret,
                "secret in plain text", "secret"},
        { "nickname", 0, 0, G_OPTION_ARG_STRING, &user->nick_name, "nick name",
                "nick name"},
        { "realname", 0, 0, G_OPTION_ARG_STRING, &user->real_name, "real name",
                "real name"},
        { "office", 0, 0, G_OPTION_ARG_STRING, &user->office, "Office location",
                "office"},
        { "officephone", 0, 0, G_OPTION_ARG_STRING, &user->office_phone,
                "office phone", "phone"},
        { "homephone", 0, 0, G_OPTION_ARG_STRING, &user->home_phone,
                "home phone", "phone"},
        { "homedir", 0, 0, G_OPTION_ARG_STRING, &user->home_dir, "home dir",
                "dir"},
        { "shell", 0, 0, G_OPTION_ARG_STRING, &user->shell, "shell path",
                "shell"},
        { NULL }
    };

    GOptionEntry group_entries[] =
    {
        { "groupname", 0, 0, G_OPTION_ARG_STRING, &group->group_name,
                "group name", "name"},
        { "grouptype", 0, 0, G_OPTION_ARG_STRING, &group->group_type,
                "valid group type can be system or user", "type"},
        { "gid", 0, 0, G_OPTION_ARG_INT, &group->gid, "group id", "gid"},
        { "gsecret", 0, 0, G_OPTION_ARG_STRING, &group->group_secret,
                "group secret in plain text", "secret"},
        { "mem_uid", 0, 0, G_OPTION_ARG_INT, &group->mem_uid, "mem uid",
        		"mem_uid"},
        { NULL }
    };

#if !GLIB_CHECK_VERSION (2, 36, 0)
    g_type_init ();
#endif   
    
    context = g_option_context_new ("\n"
            "  To add user in non-offline mode, gum-utils -a --username=user1 "
            "  --usertype=normal\n"
            "  To delete user in offline mode, gum-utils -o -d --uid=2001\n"
            "  NOTE: Only one command can be run at one time.");
    g_option_context_add_main_entries (context, main_entries, NULL);

    user_serv_option = g_option_group_new("user-service-options", "User service "
            "specific options", "User service specific options", NULL, NULL);
    g_option_group_add_entries(user_serv_option, user_serv_entries);
    g_option_context_add_group (context, user_serv_option);

    user_option = g_option_group_new("user-options", "User specific options",
            "User specific options", NULL, NULL);
    g_option_group_add_entries(user_option, user_entries);
    g_option_context_add_group (context, user_option);

    group_option = g_option_group_new("group-options", "Group specific options",
            "Group specific options", NULL, NULL);
    g_option_group_add_entries(group_option, group_entries);
    g_option_context_add_group (context, group_option);

    rval = g_option_context_parse (context, &argc, &argv, &error);
    g_option_context_free(context);
    if (!rval) {
        INFO ("option parsing failed: %s\n", error->message);
        g_free (user);
        g_free (group);
        exit (1);
    }

    if (!offline_mode && sysroot) {
        INFO ("sysroot is ONLY supported in offline mode\n");
        g_free (sysroot); sysroot = NULL;
    }

    config = gum_config_new (sysroot);
    
    if (is_user_add_op) {
        _handle_user_add (user, is_write_nfc);
    } else if (is_user_del_op) {
    	_handle_user_del (user);
    } else if (is_user_up_op) {
    	_handle_user_up (user, is_write_nfc);
    } else if (is_user_get_op) {
    	_handle_user_get (user);
    } else if (is_user_get_by_name_op) {
    	_handle_user_get_by_name (user);
    } else if (is_user_list_op) {
        _handle_user_get_list (user_types);
    }

    /* group */
    else if (is_group_add_op) {
    	_handle_group_add (group);
    } else if (is_group_del_op) {
    	_handle_group_del (group);
    } else if (is_group_up_op) {
    	_handle_group_up (group);
    } else if (is_group_get_op) {
    	_handle_group_get (group);
    } else if (is_group_get_by_name_op) {
    	_handle_group_get_by_name (group);
    } else if (is_group_add_mem_op) {
    	_handle_group_add_mem (group);
    } else if (is_group_del_mem_op) {
    	_handle_group_del_mem (group);
    } else {
        INFO ("No option specified");
    }

    if (config) g_object_unref (config);
    _free_test_user (user);
    _free_test_group (group);
    g_free (user_types);

    return 0;
}
Exemple #19
0
/**
 * @brief Main entry to the Reversi C endgame solver implementation.
 *
 * @todo Documentation has to be completly developed.
 */
int
main (int argc, char *argv[])
{
  GamePositionDb               *db;
  GamePositionDbSyntaxErrorLog *syntax_error_log;
  FILE                         *fp;
  GError                       *error;
  gchar                        *source;
  int                           number_of_errors;

  GOptionContext *context;
  GOptionGroup   *option_group;

  GamePositionDbEntry *entry;
  int                  solver_index;

  error = NULL;
  entry = NULL;
  solver_index = -1;

  /* GLib command line options and argument parsing. */
  option_group = g_option_group_new("name", "description", "help_description", NULL, NULL);
  context = g_option_context_new("- Solve an endgame position");
  g_option_context_add_main_entries(context, entries, NULL);
  g_option_context_add_group(context, option_group);
  g_option_context_set_description(context, program_documentation_string);
  if (!g_option_context_parse (context, &argc, &argv, &error)) {
    g_print("Option parsing failed: %s\n", error->message);
    return -1;
  }

  /* Checks command line options for consistency. */
  if (input_file) {
    source = g_strdup(input_file);
  } else {
    g_print("Option -f, --file is mandatory.\n.");
    return -2;
  }
  if (solver) {
    for (int index = 0; index < solvers_count; index++) {
      if (g_strcmp0(solver, solvers[index]) == 0)
        solver_index = index;
    }
    if (solver_index == -1) {
      g_print("Option -s, --solver is out of range.\n.");
      return -8;
    }
    if (solver_index == 2) { // solver == random
      if (repeats < 1) {
        g_print("Option -n, --repeats is out of range.\n.");
        return -9;
      }
    }
  } else {
    g_print("Option -s, --solver is mandatory.\n.");
    return -5;
  }

  /* Opens the source file for reading. */
  fp = fopen(source, "r");
  if (!fp) {
    g_print("Unable to open database resource for reading, file \"%s\" does not exist.\n", source);
    return -3;
  }

  /* Loads the game position database. */
  db = gpdb_new(g_strdup(source));
  syntax_error_log = NULL;
  error = NULL;
  gpdb_load(fp, source, db, &syntax_error_log, &error);
  fclose(fp);

  /* Compute the number of errors logged. */
  number_of_errors = gpdb_syntax_error_log_length(syntax_error_log);
  if (number_of_errors != 0) {
    g_print("The database resource, file \"%s\" contains errors, debug it using the gpdb_verify utility.\n", source);
    return -4;
  }

  /* Lookup for a given key. */
  if (lookup_entry) {
    entry = gpdb_lookup(db, lookup_entry);
    if (entry) {
      gchar *tmp = gpdb_entry_print(entry);
      g_print("%s", tmp);
      g_free(tmp);
    } else {
      g_print("Entry %s not found in file %s.\n", lookup_entry, source);
      return -6;
    }
  } else {
    g_print("No entry provided.\n");
    return -7;
  }

  /* Initialize the board module. */
  board_module_init();

  /* Solving the position. */
  GamePosition *gp = entry->game_position;
  ExactSolution *solution = NULL;
  g_print("Solving game position %s, from source %s, using solver %s ...\n", entry->id, source, solvers[solver_index]);
  switch (solver_index) {
  case 0:
    solution = game_position_solve(gp, log_file);
    break;
  case 1:
    solution = game_position_ifes_solve(gp, log_file);
    break;
  case 2:
    solution = game_position_random_sampler(gp, log_file, repeats);
    break;
  case 3:
    solution = game_position_minimax_solve(gp, log_file);
    break;
  case 4:
    solution = game_position_rab_solve(gp, log_file, repeats);
    break;
  case 5:
    solution = game_position_ab_solve(gp, log_file);
    break;
  default:
    g_print("This should never happen! solver_index = %d. Aborting ...\n", solver_index);
    return -9;
  }

  /* Printing results. */
  gchar *solution_to_string = exact_solution_to_string(solution);
  printf("\n%s\n", solution_to_string);
  g_free(solution_to_string);

  /* Frees the resources. */
  g_free(error);
  gpdb_free(db, TRUE);
  if (syntax_error_log)
    gpdb_syntax_error_log_free(syntax_error_log);
  g_option_context_free(context);
  g_free(source);
  exact_solution_free(solution);

  return 0;
}
Exemple #20
0
gint
main (gint argc, gchar ** argv)
{
  gboolean res = FALSE;
  gchar *command = NULL, *input_file_name = NULL;
  BtEditApplication *app;
  GOptionContext *ctx = NULL;
  GOptionGroup *group;
  GError *err = NULL;

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

  bt_setup_for_local_install ();

  GOptionEntry options[] = {
    {"version", '\0', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
        (gpointer) parse_goption_arg, N_("Print application version"), NULL}
    ,
    {"command", 'c', 0, G_OPTION_ARG_STRING, &command, N_("Command name"),
        "{load}"}
    ,
    {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &input_file_name,
        N_("Input file name"), N_("<songfile>")}
    ,
    {NULL}
  };

  // init libraries
  ctx = g_option_context_new (NULL);
  //g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
  group =
      g_option_group_new ("main", _("buzztrax-edit options"),
      _("Show buzztrax-edit options"), argv[0], NULL);
  g_option_group_add_entries (group, options);
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
  g_option_context_set_main_group (ctx, group);

  bt_init_add_option_groups (ctx);
  g_option_context_add_group (ctx, btic_init_get_option_group ());
  g_option_context_add_group (ctx, gtk_get_option_group (TRUE));
  g_option_context_add_group (ctx, clutter_get_option_group_without_init ());
  g_option_context_add_group (ctx, gtk_clutter_get_option_group ());

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

  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "bt-edit", 0,
      "music production environment / editor ui");

  // give some global context info
  g_set_prgname ("buzztrax-edit");
  g_set_application_name ("Buzztrax");
  gtk_window_set_default_icon_name ("buzztrax");
  g_setenv ("PULSE_PROP_media.role", "production", TRUE);

  extern gboolean bt_memory_audio_src_plugin_init (GstPlugin * const plugin);
  gst_plugin_register_static (GST_VERSION_MAJOR,
      GST_VERSION_MINOR,
      "memoryaudiosrc",
      "Plays audio from memory",
      bt_memory_audio_src_plugin_init,
      VERSION, "LGPL", PACKAGE, PACKAGE_NAME, "http://www.buzztrax.org");

  GST_INFO ("starting: thread=%p", g_thread_self ());

  app = bt_edit_application_new ();

  // set a default command, if a file is given
  if (!command && BT_IS_STRING (input_file_name)) {
    command = g_strdup ("l");
  }

  if (command) {
    // depending on the options call the correct method
    if (!strcmp (command, "l") || !strcmp (command, "load")) {
      if (!BT_IS_STRING (input_file_name)) {
        usage (argc, argv, ctx);
        // if commandline options where wrong, just start
        res = bt_edit_application_run (app);
      } else {
        res = bt_edit_application_load_and_run (app, input_file_name);
      }
    } else {
      usage (argc, argv, ctx);
      // if commandline options where wrong, just start
      res = bt_edit_application_run (app);
    }
  } else {
    res = bt_edit_application_run (app);
  }

  // free application
  GST_INFO ("app %" G_OBJECT_REF_COUNT_FMT, G_OBJECT_LOG_REF_COUNT (app));
  g_object_unref (app);

Done:
  g_free (command);
  g_free (input_file_name);
  g_option_context_free (ctx);
  return !res;
}
Exemple #21
0
gboolean
mc_args_parse (int *argc, char ***argv, const char *translation_domain, GError ** mcerror)
{
    const gchar *_system_codepage;
    gboolean ok = TRUE;

    mc_return_val_if_error (mcerror, FALSE);

    _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, mcerror))
    {
        if (*mcerror == NULL)
            mc_propagate_error (mcerror, 0, "%s\n", _("Arguments parse error!"));
        else
        {
            gchar *help_str;

            help_str = g_option_context_get_help (context, TRUE, NULL);

            if (str_isutf8 (_system_codepage))
                mc_replace_error (mcerror, (*mcerror)->code, "%s\n\n%s\n", (*mcerror)->message,
                                  help_str);
            else
            {
                gchar *full_help_str;

                full_help_str =
                    mc_args__convert_help_to_syscharset (_system_codepage, (*mcerror)->message,
                                                         help_str);
                mc_replace_error (mcerror, (*mcerror)->code, "%s", full_help_str);
                g_free (full_help_str);
            }
            g_free (help_str);
        }

        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;
}
Exemple #22
0
GOptionGroup *
gst_init_get_option_group (void)
{
#ifndef GST_DISABLE_OPTION_PARSING
  GOptionGroup *group;
  static const GOptionEntry gst_args[] = {
    {"gst-version", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
        (gpointer) parse_goption_arg, N_("Print the GStreamer version"), NULL},
    {"gst-fatal-warnings", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
        (gpointer) parse_goption_arg, N_("Make all warnings fatal"), NULL},
#ifndef GST_DISABLE_GST_DEBUG
    {"gst-debug-help", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Print available debug categories and exit"),
        NULL},
    {"gst-debug-level", 0, 0, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Default debug level from 1 (only error) to 5 (anything) or "
              "0 for no output"),
        N_("LEVEL")},
    {"gst-debug", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) parse_goption_arg,
          N_("Comma-separated list of category_name:level pairs to set "
              "specific levels for the individual categories. Example: "
              "GST_AUTOPLUG:5,GST_ELEMENT_*:3"),
        N_("LIST")},
    {"gst-debug-no-color", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg, N_("Disable colored debugging output"),
        NULL},
    {"gst-debug-disable", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
        (gpointer) parse_goption_arg, N_("Disable debugging"), NULL},
#endif
    {"gst-plugin-spew", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Enable verbose plugin loading diagnostics"),
        NULL},
    {"gst-plugin-path", 0, 0, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
        N_("Colon-separated paths containing plugins"), N_("PATHS")},
    {"gst-plugin-load", 0, 0, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Comma-separated list of plugins to preload in addition to the "
              "list stored in environment variable GST_PLUGIN_PATH"),
        N_("PLUGINS")},
    {"gst-disable-segtrap", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Disable trapping of segmentation faults during plugin loading"),
        NULL},
    {"gst-disable-registry-update", 0, G_OPTION_FLAG_NO_ARG,
          G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Disable updating the registry"),
        NULL},
    {"gst-disable-registry-fork", 0, G_OPTION_FLAG_NO_ARG,
          G_OPTION_ARG_CALLBACK,
          (gpointer) parse_goption_arg,
          N_("Disable spawning a helper process while scanning the registry"),
        NULL},
    {NULL}
  };

  /* Since GLib 2.23.2 calling g_thread_init() 'late' is allowed and is
   * automatically done as part of g_type_init() */
  if (glib_check_version (2, 23, 3)) {
    /* The GLib threading system must be initialised before calling any other
     * GLib function according to the documentation; if the application hasn't
     * called gst_init() yet or initialised the threading system otherwise, we
     * better issue a warning here (since chances are high that the application
     * has already called other GLib functions such as g_option_context_new() */
    if (!g_thread_get_initialized ()) {
      g_warning ("The GStreamer function gst_init_get_option_group() was\n"
          "\tcalled, but the GLib threading system has not been initialised\n"
          "\tyet, something that must happen before any other GLib function\n"
          "\tis called. The application needs to be fixed so that it calls\n"
          "\t   if (!g_thread_get_initialized ()) g_thread_init(NULL);\n"
          "\tas very first thing in its main() function. Please file a bug\n"
          "\tagainst this application.");
      g_thread_init (NULL);
    }
  } else {
    /* GLib >= 2.23.2 */
  }

  group = g_option_group_new ("gst", _("GStreamer Options"),
      _("Show GStreamer Options"), NULL, NULL);
  g_option_group_set_parse_hooks (group, (GOptionParseFunc) init_pre,
      (GOptionParseFunc) init_post);

  g_option_group_add_entries (group, gst_args);
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);

  return group;
#else
  return NULL;
#endif
}
Exemple #23
0
int main(int argc, char * argv[]) {

    int numargs;            /* number of filename arguments */
    int i;

    GString *inputbuf;
    char *out;              /* string containing processed output */

    FILE *input;
    FILE *output;
    char curchar;
    char *progname = argv[0];

    int output_format = HTML_FORMAT;

    /* Code for command-line option parsing. */

    static gboolean opt_version = FALSE;
    static gchar *opt_output = 0;
    static gchar *opt_to = 0;
    static gboolean opt_smart = FALSE;
    static gboolean opt_notes = FALSE;
    static gboolean opt_filter_html = FALSE;
    static gboolean opt_filter_styles = FALSE;
    static gboolean opt_strike = FALSE;
    static gboolean opt_allext = FALSE;

    static GOptionEntry entries[] =
    {
        { "version", 'v', 0, G_OPTION_ARG_NONE, &opt_version, "print version and exit", NULL },
        { "output", 'o', 0, G_OPTION_ARG_STRING, &opt_output, "send output to FILE (default is stdout)", "FILE" },
        { "to", 't', 0, G_OPTION_ARG_STRING, &opt_to, "convert to FORMAT (default is html)", "FORMAT" },
        { "extensions", 'x', 0, G_OPTION_ARG_NONE, &opt_allext, "use all syntax extensions", NULL },
        { "filter-html", 0, 0, G_OPTION_ARG_NONE, &opt_filter_html, "filter out raw HTML (except styles)", NULL },
        { "filter-styles", 0, 0, G_OPTION_ARG_NONE, &opt_filter_styles, "filter out HTML styles", NULL },
        { NULL }
    };

    /* Options to active syntax extensions.  These appear separately in --help. */
    static GOptionEntry ext_entries[] =
    {
        { "smart",  0, 0, G_OPTION_ARG_NONE, &opt_smart,  "use smart typography extension", NULL },
        { "notes",  0, 0, G_OPTION_ARG_NONE, &opt_notes,  "use notes extension", NULL },
        { "strike", 0, 0, G_OPTION_ARG_NONE, &opt_strike, "use strike-through extension", NULL },
        { NULL }
    };

    GError *error = NULL;
    GOptionContext *context;
    GOptionGroup *ext_group;

    context = g_option_context_new ("[FILE...]");
    g_option_context_add_main_entries (context, entries, NULL);
    ext_group = g_option_group_new ("extensions", "Syntax extensions", "show available syntax extensions", NULL, NULL);
    g_option_group_add_entries (ext_group, ext_entries);
    g_option_context_add_group (context, ext_group);
    g_option_context_set_description (context, "Converts text in specified files (or stdin) from markdown to FORMAT.\n"
                                      "Available FORMATs:  html, latex, groff-mm, odf");
    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        g_print ("option parsing failed: %s\n", error->message);
        exit (1);
    }
    g_option_context_free(context);

    /* Process command-line options and arguments. */

    if (opt_version) {
        version(progname);
        return EXIT_SUCCESS;
    }

    extensions = 0;
    if (opt_allext)
        extensions = 0xFFFFFF;  /* turn on all extensions */
    if (opt_smart)
        extensions = extensions | EXT_SMART;
    if (opt_notes)
        extensions = extensions | EXT_NOTES;
    if (opt_filter_html)
        extensions = extensions | EXT_FILTER_HTML;
    if (opt_filter_styles)
        extensions = extensions | EXT_FILTER_STYLES;
    if (opt_strike)
        extensions = extensions | EXT_STRIKE;

    if (opt_to == NULL)
        output_format = HTML_FORMAT;
    else if (strcmp(opt_to, "html") == 0)
        output_format = HTML_FORMAT;
    else if (strcmp(opt_to, "latex") == 0)
        output_format = LATEX_FORMAT;
    else if (strcmp(opt_to, "groff-mm") == 0)
        output_format = GROFF_MM_FORMAT;
    else if (strcmp(opt_to, "odf") == 0)
        output_format = ODF_FORMAT;
    else {
        fprintf(stderr, "%s: Unknown output format '%s'\n", progname, opt_to);
        exit(EXIT_FAILURE);
    }

    /* we allow "-" as a synonym for stdout here */
    if (opt_output == NULL || strcmp(opt_output, "-") == 0)
        output = stdout;
    else if (!(output = fopen(opt_output, "w"))) {
        perror(opt_output);
        return 1;
    }

    inputbuf = g_string_new("");   /* string for concatenated input */

    /* Read input from stdin or input files into inputbuf */

    numargs = argc - 1;
    if (numargs == 0) {        /* use stdin if no files specified */
        while ((curchar = fgetc(stdin)) != EOF)
            g_string_append_c(inputbuf, curchar);
        fclose(stdin);
    }
    else {                  /* open all the files on command line */
        for (i = 0; i < numargs; i++) {
            if ((input = fopen(argv[i+1], "r")) == NULL) {
                perror(argv[i+1]);
                exit(EXIT_FAILURE);
            }
            while ((curchar = fgetc(input)) != EOF)
                g_string_append_c(inputbuf, curchar);
            fclose(input);
        }
    }

    out = markdown_to_string(inputbuf->str, extensions, output_format);
    fprintf(output, "%s\n", out);
    free(out);

    g_string_free(inputbuf, true);

    return(EXIT_SUCCESS);
}
Exemple #24
0
int
main (int argc, char *argv[])
{
	UniqueApp	*app;
	UniqueMessageData	*msg;
	GError		*error = NULL;
	GOptionContext	*context;
	GOptionGroup	*debug;
	gulong		debug_flags = 0;
	LifereaDBus	*dbus = NULL;
	const gchar	*initial_state = "shown";
	gchar		*feed = NULL;
	int		initialState;
	gboolean	show_tray_icon, start_in_tray;

#ifdef USE_SM
	gchar *opt_session_arg = NULL;
#endif

	GOptionEntry entries[] = {
		{ "mainwindow-state", 'w', 0, G_OPTION_ARG_STRING, &initial_state, N_("Start Liferea with its main window in STATE. STATE may be `shown', `iconified', or `hidden'"), N_("STATE") },
#ifdef USE_SM
		{ "session", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &opt_session_arg, NULL, NULL },
#endif
		{ "version", 'v', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, show_version, N_("Show version information and exit"), NULL },
		{ "add-feed", 'a', 0, G_OPTION_ARG_STRING, &feed, N_("Add a new subscription"), N_("uri") },
		{ NULL }
	};

	GOptionEntry debug_entries[] = {
		{ "debug-all", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of all types"), NULL },
		{ "debug-cache", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages for the cache handling"), NULL },
		{ "debug-conf", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages for the configuration handling"), NULL },
		{ "debug-db", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of the database handling"), NULL },
		{ "debug-gui", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of all GUI functions"), NULL },
		{ "debug-html", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Enables HTML rendering debugging. Each time Liferea renders HTML output it will also dump the generated HTML into ~/.liferea_1.6/output.xhtml"), NULL },
		{ "debug-net", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of all network activity"), NULL },
		{ "debug-parsing", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of all parsing functions"), NULL },
		{ "debug-performance", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages when a function takes too long to process"), NULL },
		{ "debug-trace", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages when entering/leaving functions"), NULL },
		{ "debug-update", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of the feed update processing"), NULL },
		{ "debug-vfolder", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of the search folder matching"), NULL },
		{ "debug-verbose", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print verbose debugging messages"), NULL },
		{ NULL }
	};

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

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

	debug = g_option_group_new ("debug",
				    _("Print debugging messages for the given topic"),
				    _("Print debugging messages for the given topic"),
				    &debug_flags,
				    NULL);
	g_option_group_set_translation_domain(debug, GETTEXT_PACKAGE);
	g_option_group_add_entries (debug, debug_entries);

	context = g_option_context_new (NULL);
	g_option_context_set_summary (context, N_("Liferea, the Linux Feed Reader"));
	g_option_context_set_description (context, N_("For more information, please visit http://liferea.sourceforge.net/"));
	g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
	g_option_context_set_translation_domain(context, GETTEXT_PACKAGE);
	g_option_context_add_group (context, debug);
	g_option_context_add_group (context, gtk_get_option_group (FALSE));

	g_option_context_parse (context, &argc, &argv, &error);
	g_option_context_free (context);
	if (error) {
		g_print ("Error parsing options: %s\n", error->message);
	}

	set_debug_level (debug_flags);

	/* Configuration necessary for network options, so it
	   has to be initialized before update_init() */
	conf_init ();

#ifdef USE_DBUS
	dbus_g_thread_init ();
#endif

	/* We need to do the network initialization here to allow
	   network-manager to be setup before gtk_init() */
	update_init ();

	gtk_init (&argc, &argv);

	/* Single instance checks */
	app = unique_app_new_with_commands ("net.sourceforge.liferea", NULL,
					    "add_feed", COMMAND_ADD_FEED,
					    NULL);
	if (unique_app_is_running (app)) {
		g_print ("Liferea is already running\n");
		unique_app_send_message (app, UNIQUE_ACTIVATE, NULL);
		if (feed) {
			msg = unique_message_data_new ();
			unique_message_data_set_text (msg, feed, -1);
			unique_app_send_message (app, COMMAND_ADD_FEED, msg);
		}
		return 1;
	} else {
		g_signal_connect (app, "message-received", G_CALLBACK (message_received_cb), NULL);
	}

	/* GTK theme support */
	g_set_application_name (_("Liferea"));
	gtk_window_set_default_icon_name ("liferea");

	debug_start_measurement (DEBUG_DB);

	/* order is important! */
	db_init ();			/* initialize sqlite */
	xml_init ();			/* initialize libxml2 */
#ifdef HAVE_LIBNOTIFY
	notification_plugin_register (&libnotify_plugin);
#endif
	social_init ();			/* initialize social bookmarking */
#ifdef USE_DBUS	
	dbus = liferea_dbus_new ();	
#else
	debug0 (DEBUG_GUI, "Compiled without DBUS support.");
#endif

#ifdef USE_AVAHI
	if (conf_get_bool_value (SYNC_AVAHI_ENABLED)) {
		LifereaAvahiPublisher	*avahiPublisher = NULL;

		debug0 (DEBUG_CACHE, "Registering with AVAHI");
		avahiPublisher = liferea_avahi_publisher_new ();
		liferea_avahi_publisher_publish (avahiPublisher, conf_get_str_value (SYNC_AVAHI_SERVICE_NAME), 23632);
	} else {
		debug0 (DEBUG_CACHE, "Avahi support available, but disabled by preferences.");
	}
#else
	debug0 (DEBUG_CACHE, "Compiled without AVAHI support");
#endif

	/* how to start liferea, command line takes precedence over preferences */
	conf_get_bool_value (SHOW_TRAY_ICON, &show_tray_icon);
	conf_get_bool_value (START_IN_TRAY, &start_in_tray);
	if (g_str_equal(initial_state, "iconified")) {
		initialState = MAINWINDOW_ICONIFIED;
	} else if (g_str_equal(initial_state, "hidden") ||
	    (show_tray_icon && start_in_tray)) {
		initialState = MAINWINDOW_HIDDEN;
	} else {
		initialState = MAINWINDOW_SHOWN;
	}

	liferea_shell_create (initialState);
	g_set_prgname ("liferea");
	
#ifdef USE_SM
	/* This must be after feedlist reading because some session
	   managers will tell Liferea to exit if Liferea does not
	   respond to SM requests within a minute or two. This starts
	   the main loop soon after opening the SM connection. */
	session_init (BIN_DIR G_DIR_SEPARATOR_S "liferea", opt_session_arg);
	session_set_cmd (NULL, initialState);
#endif
	signal (SIGTERM, signal_handler);
	signal (SIGINT, signal_handler);
	signal (SIGHUP, signal_handler);

#ifndef G_OS_WIN32
	signal (SIGBUS, fatal_signal_handler);
	signal (SIGSEGV, fatal_signal_handler);
#endif

	/* Note: we explicitely do not use the gdk_thread_*
	   locking in Liferea because it freezes the program
	   when running Flash applets in gtkmozembed */

	runState = STATE_STARTING;
	
	debug_end_measurement (DEBUG_DB, "startup");

	if (feed)
		feedlist_add_subscription (feed, NULL, NULL, 0);

	gtk_main ();
	
	g_object_unref (G_OBJECT (dbus));
	return 0;
}
SSVCommandLine *
ssv_command_line_new (gint *argc, gchar ***argv)
{
  SSVCommandLine *self = g_new (SSVCommandLine, 1);

  // Initialize the contents of the structure we will parse into with
  // default or empty values.  IMPROVEME: this notion of the default
  // cache directory is manually synced with some code in main().
  self->cache_dir = g_string_new (getenv ("HOME"));
  g_string_append (self->cache_dir, "/.ssv_cache");
  const gint default_max_cache_size = 400;
  self->max_cache_size = default_max_cache_size;
  self->pixmaps = pix_maps_spec_new ();
  // If sigmas is negative, we will try to linearly map the whole range.
  const gdouble default_sigmas = 2.0;
  self->sigmas = default_sigmas;
  self->images = g_ptr_array_new ();
  self->x_offsets = g_array_new (FALSE, FALSE, sizeof (gint));
  self->y_offsets = g_array_new (FALSE, FALSE, sizeof (gint));
  gchar *analysis_program = NULL;  // We'll copy into GString in self later.
  self->async_analysis = FALSE;
  const gint default_analysis_tile_size = 51;
  self->analysis_tile_size = default_analysis_tile_size;

  const gint option_type_count = 8;
  // List of uptions (+1 for the 'option' which handles the arguments,
  // +1 for the one with NULL for its long_name which terminated the
  // list).
  GOptionEntry *entries = g_new (GOptionEntry, option_type_count + 1 + 1);

  // Place for the parser to store the cache directory option argument
  // value.  It looks like the option parser automagicly allocates
  // this.
  gchar *cache_dir = NULL;

  // Place for the parser to store the image file names.
  gchar **image_names = NULL;

  // Entry strings, including documentation that gets printed by
  // --help (make sure it still looks good after changes).

  // IMPROVEME: there are little bits in these documentation strings
  // that at the moment need to be manually kept in sync with the
  // defaults and such.

  entries[0].long_name = "cache-dir";
  entries[0].short_name = 'c';
  entries[0].flags = 0;
  entries[0].arg = G_OPTION_ARG_FILENAME;
  entries[0].arg_data  = &cache_dir;
  entries[0].description
    = "\n     Directory to use for pyramid cache (defualt: ~/.ssv_cache)\n";
  entries[0].arg_description = "DIRECTORY";

  entries[1].long_name = "max-cache-size";
  entries[1].short_name = 'm';
  entries[1].flags = 0;
  entries[1].arg = G_OPTION_ARG_INT;
  entries[1].arg_data = &(self->max_cache_size);
  entries[1].description
    = (
"\n     Maximum cache size, in megabytes.  Old (unused) entries start\n"
"     getting deleted when the cache gets this big.  Default is 400.\n");
  entries[1].arg_description = "SIZE";
    
  entries[2].long_name = "pixmap";
  entries[2].short_name = 'p';
  entries[2].flags = 0;
  entries[2].arg = G_OPTION_ARG_CALLBACK;
  entries[2].arg_data = parse_pixmap;
  entries[2].description
    = (
"\n     Pixel remap specification of the form \"[a,b],c\".  Pixels in the \n"
"     range [a,b] (values of \"nan\" or \"inf\" are allowed) are not \n"
"     considerd when computing the image statistics used to map the image \n"
"     into the representable range of pixel values, and are always \n"
"     represented visually as if they have value c.  Note that pixel maps\n"
"     have no effect at all on pixel information, tile analysis, etc.: they\n"
"     only affect how the image data is rendered\n");
  entries[2].arg_description = "SPEC";

  entries[3].long_name = "sigmas";
  entries[3].short_name = 's';
  entries[3].flags = 0;
  entries[3].arg = G_OPTION_ARG_DOUBLE;
  entries[3].arg_data = &(self->sigmas);
  entries[3].description
    = (
"\n     When displaying data, map values within SIGMAS standard deviations\n"
"     of the mean linearly into the displayable range of values, and clamp\n"
"     values outside this region to the endpoints of the displayable range.\n"
"     Note that sufficiently huge or special pixel values will still require\n"
"     the use of pixel maps (see --pixmap option description).  The default\n"
"     value is 2.0.  If SIGMAS is negative, the whole range of pixel values\n"
"     present in the data will be mapped linearly into the displayable\n"
"     range.\n");
  entries[3].arg_description = "SIGMAS";


  entries[4].long_name = "offset";
  entries[4].short_name = 'o';
  entries[4].flags = 0;
  entries[4].arg = G_OPTION_ARG_CALLBACK;
  entries[4].arg_data = parse_offset;
  entries[4].description
    = (
"\n     Image offset specification of the form \"a,b\" where a is \n"
"     counted in whole image pixels rightward and b downward from the top \n"
"     left corner of the first image argument.  The first occurence of this \n"
"     option specifies the offset of the top left corner of the second \n"
"     image, the second occurence the offset of the third image, etc. \n"
"     If any occurences of this option appear in an invocation, the correct \n"
"     number (i.e. one less than the number of images) must be supplied.\n");
  entries[4].arg_description = "SPEC";
  
  entries[5].long_name = "analysis-program";
  entries[5].short_name = 'a';
  entries[5].flags = 0;
  entries[5].arg = G_OPTION_ARG_STRING;
  entries[5].arg_data = &analysis_program;
  entries[5].description
    = (
"\n    Program to run when 'a' key is pressed.  The program is invoked \n"
"    with the following command line arguments:\n"
"\n"
"        tile_count            total number of image tiles to be passed\n"
"        base_name             image file base name\n"
"        tile_width            width of tile in pixels\n"
"        tile_height           height of tile in pixels\n"
"        tile_file_name        name of file containing tile data\n"
"\n"
"    where arguments 2 through 5 in the above list are repeated tile_count\n"
"    times.  The tile_width and tile_height arguments are generally equal to\n"
"    the value specified with the --analysis-tile-size option, but may be\n"
"    smaller (or even zero) if the cursor was near or off the edge of the\n"
"    image when analysis was requested.  The tile_file_name is the name of a\n"
"    file containing the tile data in big endian form.  It's probably\n"
"    easiest to use the float_image_new_from_file method with these\n"
"    arguments.  The base_name argument might be useful if metadata needs to\n"
"    be used or the analysis region needs to be grown algorithmicly.\n");
  entries[5].arg_description = "PROGRAM";

  entries[6].long_name = "async-analysis";
  entries[6].short_name = 0;
  entries[6].flags = 0;
  entries[6].arg = G_OPTION_ARG_NONE;
  entries[6].arg_data = &(self->async_analysis);
  entries[6].description
    = ( 
"\n    Run the analysis program asynchronously (i.e. in background,\n"
"    without waiting for it to complete.\n");
  entries[6].arg_description = "";   // Doesn't take an argument.

  entries[7].long_name = "analysis-tile-size";
  entries[7].short_name = 0;
  entries[7].flags = 0;
  entries[7].arg = G_OPTION_ARG_INT;
  entries[7].arg_data = &(self->analysis_tile_size);
  entries[7].description
    = (
"\n    Dimensions of (square) tiles to analyze (must be odd).  The default\n"
"    size is 51.\n");
  entries[7].arg_description = "TILE_SIZE";

  entries[8].long_name = G_OPTION_REMAINING;
  entries[8].short_name = 0;
  entries[8].flags = 0;
  entries[8].arg = G_OPTION_ARG_FILENAME_ARRAY;
  entries[8].arg_data = &image_names;
  entries[8].description = "YOU_HOPEFULLY_DONT_SEE_ME";
  entries[8].arg_description = "IMAGE_BASE_NAME [IMAGE_BASE_NAME...]";

  entries[9].long_name = NULL;

  GOptionGroup *ssv_group
    = g_option_group_new ("ssv", "ssv Options",
			  "Display help for ssv options.", self, NULL);
  
  g_option_group_add_entries (ssv_group, entries);

  GOptionContext *option_context = g_option_context_new ("");

  g_option_context_set_main_group (option_context, ssv_group);

  // Run the parser.
  GError *err = NULL;
  gboolean parse_results
    = g_option_context_parse (option_context, argc, argv, &err);
  if ( !parse_results ) {
    g_printerr ("%s: option parsing failed: %s\n", g_get_prgname (),
		err->message);
    exit (EXIT_FAILURE);
  }
  else {
    g_assert (err == NULL);
  }

  g_option_context_free (option_context);

  // Vet and copy the cache directory name (if provided) into a new
  // GString instance in self.
  if ( cache_dir != NULL ) {
    GError *err = NULL;
    my_is_writable_directory (cache_dir, &err);
    if ( err != NULL ) {
      g_printerr ("%s: bad -c or --cache-dir option argument '%s': %s\n",
		  g_get_prgname (), cache_dir, err->message);
      exit (EXIT_FAILURE);
    }
    g_string_free (self->cache_dir, TRUE);
    self->cache_dir = g_string_new (cache_dir);
  }

  g_free (cache_dir);

  // Vet and copy the analysis related arguments into their homes in
  // self.
  if ( analysis_program != NULL ) {
    self->analysis_program = g_string_new (analysis_program);
  }
  else {
    self->analysis_program = NULL;
  }
  if ( self->analysis_tile_size % 2 != 1 ) {
    g_printerr ("%s: bad --analysis_tile_size option argument '%d': not odd\n",
		g_get_prgname (), self->analysis_tile_size);
    exit (EXIT_FAILURE);
  }

  // Vet and copy the image name strings into GString instances in the
  // array in self.
  guint ii;
  for ( ii = 0 ; image_names != NULL && image_names[ii] != NULL ; ii++ ) {
    GString *cs = g_string_new (image_names[ii]);

    GError *err = NULL;

    GString *data_name = my_g_string_new_printf ("%s.img", cs->str);
    my_is_readable_file (data_name->str, &err);
    if ( err != NULL ) {
      g_printerr ("%s: file '%s' looks unreadable: %s\n",
		  g_get_prgname (), data_name->str, err->message);
      exit (EXIT_FAILURE);
    }
    my_g_string_free (data_name);

    GString *meta_name = my_g_string_new_printf ("%s.meta", cs->str);
    my_is_readable_file (meta_name->str, &err);
    if ( err != NULL ) {
      g_printerr ("%s: file '%s' looks unreadable: %s\n",
		  g_get_prgname (), meta_name->str, err->message);
      exit (EXIT_FAILURE);
    }
    my_g_string_free (meta_name);

    g_ptr_array_add (self->images, cs);
  }

  g_strfreev (image_names);

  // We require at least one image argument.
  if ( self->images->len < 1 ) {
    g_printerr ("%s: at least one image base name argument must be "
		"provided (try %s --help).\n", g_get_prgname (),
		g_get_prgname ());
    exit (EXIT_FAILURE);
  }

  // We require the corrent number of offset arguments.
  if ( self->x_offsets->len > 0 ) {
    if ( self->x_offsets->len != self->images->len - 1 ) {
      g_printerr ("%s: if any offset options are provided, the number "
		  "provided must be exactly one less than the number of image "
		  "arguments provided\n", g_get_prgname ());
      exit (EXIT_FAILURE);
    }
  }

  // IMPROVEME: Well this restriction has the potential to be very
  // annoying: if more than one image is specified to be loaded,
  // offset options must be specified for each image beyond the first.
  // The sensible thing would be to have default offset of (0, 0) or
  // course.  But it opend a small can or worms if we want and offset
  // for only the third image for example, and I just don't have the
  // time to go through and make everything agree.
  g_assert (self->x_offsets->len == self->images->len - 1);
  g_assert (self->x_offsets->len == self->y_offsets->len);

  self->reference_count = 1;

  return self;
}
Exemple #26
0
int main(int argc, char *argv[]) {

    AppData *app_data = g_slice_new0 (AppData);
    app_data->filename = g_strdup("resultoutputfile.log");
    app_data->outputfile = g_strdup(getenv("OUTPUTFILE"));
    app_data->disable_plugin = g_ptr_array_new_with_free_func (g_free);

    GError *error = NULL;

    gchar *server = NULL;
    SoupURI *result_uri = NULL;

    guint ret = 0;

    SoupMessage *server_msg;
    SoupRequest *request;

    gchar *result_msg = NULL;
    gchar *prefix = NULL;
    gchar *server_recipe_key = NULL;
    gchar *server_recipe = NULL;
    gchar *task_id = NULL;
    gchar *task_id_key = NULL;
    gboolean no_plugins = FALSE;

    gchar *form_data;
    GHashTable *data_table = g_hash_table_new (NULL, NULL);

    GOptionEntry entries[] = {
        {"server", 's', 0, G_OPTION_ARG_STRING, &server,
            "Server to connect to", "URL" },
        { "message", 't', 0, G_OPTION_ARG_STRING, &result_msg,
            "Short 100 characters or less message", "TEXT" },
        { "outputfile", 'o', 0, G_OPTION_ARG_CALLBACK, callback_outputfile,
            "Log to upload with result, $OUTPUTFILE is used by default", "FILE" },
        { "disable-plugin", 'p', 0, G_OPTION_ARG_CALLBACK, callback_disable_plugin,
            "don't run plugin on server side", "PLUGIN" },
        { "no-plugins", 0, 0, G_OPTION_ARG_NONE, &no_plugins,
            "don't run any plugins on server side", NULL },
        { NULL }
    };
    GOptionGroup *option_group = g_option_group_new ("main",
                                                    "Application Options",
                                                    "Various application related options",
                                                    app_data, NULL);

    GOptionContext *context = g_option_context_new("TASK_PATH RESULT SCORE");
    g_option_context_set_summary(context,
            "Report results to lab controller. if you don't specify the\n"
            "the server url you must have RECIPEID and TASKID defined.\n"
            "If HARNESS_PREFIX is defined then the value of that must be\n"
            "prefixed to RECIPEID and TASKID");
    g_option_group_add_entries(option_group, entries);
    g_option_context_set_main_group (context, option_group);

    gboolean parse_succeeded = g_option_context_parse(context, &argc, &argv, &error);

    if (!parse_succeeded) {
        goto cleanup;
    }

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

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

    if (argc < 3 || !server) {
        cmd_usage(context);
        goto cleanup;
    }

    result_uri = soup_uri_new (server);
    if (result_uri == NULL) {
        g_set_error (&error, RESTRAINT_ERROR,
                     RESTRAINT_PARSE_ERROR_BAD_SYNTAX,
                     "Malformed server url: %s", server);
        goto cleanup;
    }
    session = soup_session_new_with_options("timeout", 3600, NULL);

    g_hash_table_insert (data_table, "path", argv[1]);
    g_hash_table_insert (data_table, "result", argv[2]);

    // if AVC_ERROR=+no_avc_check then disable the selinux check plugin
    // This is for legacy rhts tests.. please use --disable-plugin
    gchar *avc_error = getenv("AVC_ERROR");
    if (g_strcmp0 (avc_error, "+no_avc_check") == 0) {
        g_ptr_array_add (app_data->disable_plugin, g_strdup ("10_avc_check"));
    }

    if (app_data->disable_plugin->pdata) {
        g_hash_table_insert (data_table, "disable_plugin",
                             g_strjoinv (" ", (gchar **)app_data->disable_plugin->pdata));
    }
    if (no_plugins)
      g_hash_table_insert (data_table, "no_plugins", &no_plugins);
    if (argc > 3)
      g_hash_table_insert (data_table, "score", argv[3]);
    if (result_msg)
      g_hash_table_insert (data_table, "message", result_msg);

    request = (SoupRequest *)soup_session_request_http_uri (session, "POST", result_uri, &error);
    server_msg = soup_request_http_get_message (SOUP_REQUEST_HTTP (request));
    g_object_unref(request);
    form_data = soup_form_encode_hash (data_table);
    soup_message_set_request (server_msg, "application/x-www-form-urlencoded",
                              SOUP_MEMORY_TAKE, form_data, strlen (form_data));
    g_print ("** %s %s Score:%s\n", argv[1], argv[2], argv[3]);
    ret = soup_session_send_message (session, server_msg);
    if (SOUP_STATUS_IS_SUCCESSFUL (ret)) {
        gchar *location = g_strdup_printf ("%s/logs/",
                                           soup_message_headers_get_one (server_msg->response_headers, "Location"));
        soup_uri_free (result_uri);
        result_uri = soup_uri_new (location);
        g_free (location);
        if (app_data->outputfile != NULL &&
            g_file_test (app_data->outputfile, G_FILE_TEST_EXISTS))
        {
            g_print ("Uploading %s ", app_data->filename);
            if (upload_file (session, app_data->outputfile, app_data->filename, result_uri, &error)) {
                g_print ("done\n");
            } else {
                g_print ("failed\n");
            }
        }
    } else {
       g_warning ("Failed to submit result, status: %d Message: %s\n", ret, server_msg->reason_phrase);
    }
    g_object_unref(server_msg);
    soup_session_abort(session);
    g_object_unref(session);

cleanup:
    if (server != NULL) {
        g_free(server);
    }
    if (result_msg != NULL) {
        g_free(result_msg);
    }
    g_option_context_free(context);
    g_hash_table_destroy(data_table);
    if (result_uri != NULL) {
        soup_uri_free (result_uri);
    }
    restraint_free_appdata(app_data);
    if (error) {
        int retcode = error->code;
        g_printerr("%s [%s, %d]\n", error->message,
                g_quark_to_string(error->domain), error->code);
        g_clear_error(&error);
        return retcode;
    } else {
        return EXIT_SUCCESS;
    }
}
Exemple #27
0
int main(int argc, char *argv[]) {
	struct configuration conf= { NULL, NULL, NULL, 0 };

	GError *error= NULL;
	GOptionContext *context;

	g_thread_init(NULL);

	init_mutex= g_mutex_new();

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

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

	set_verbose(verbose);

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

	MYSQL *conn;
	conn= mysql_init(NULL);
	mysql_options(conn, MYSQL_READ_DEFAULT_GROUP, "myloader");

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

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

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

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

        restore_databases(&conf, conn);

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

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

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

	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
}
Exemple #28
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GOptionGroup *gatt_group, *params_group, *char_rw_group;
	GError *gerr = NULL;
	GIOChannel *chan;

	opt_dst_type = g_strdup("public");
	opt_sec_level = g_strdup("low");

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

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

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

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

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

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

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

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

	event_loop = g_main_loop_new(NULL, FALSE);

	g_main_loop_run(event_loop);

	g_main_loop_unref(event_loop);

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

	if (got_error)
		exit(EXIT_FAILURE);
	else
		exit(EXIT_SUCCESS);
}
int
main (int argc, char **argv)
{
  GOptionContext *context;
  GOptionGroup *group;
  GError* err = NULL;
  int i;
  mode_t dir_permissions;
  
  setlocale (LC_ALL, "");
  
  context = g_option_context_new ("");
  g_option_context_add_main_entries (context, options, NULL);

  group = g_option_group_new ("edit", _("Edition options for desktop file"), _("Show desktop file edition options"), NULL, NULL);
  g_option_group_add_entries (group, edit_options);
  g_option_context_add_group (context, group);

  err = NULL;
  g_option_context_parse (context, &argc, &argv, &err);

  if (err != NULL) {
	  g_printerr ("%s\n", err->message);
	  g_printerr (_("Run '%s --help' to see a full list of available command line options.\n"), argv[0]);
	  g_error_free (err);
	  return 1;
  }

  if (vendor_name == NULL && g_getenv ("DESKTOP_FILE_VENDOR"))
    vendor_name = g_strdup (g_getenv ("DESKTOP_FILE_VENDOR"));
  
  if (copy_generic_name_to_name && copy_name_to_generic_name)
    {
      g_printerr (_("Specifying both --copy-name-to-generic-name and --copy-generic-name-to-name at once doesn't make much sense.\n"));
      return 1;
    }
  
  if (target_dir == NULL && g_getenv ("DESKTOP_FILE_INSTALL_DIR"))
    target_dir = g_strdup (g_getenv ("DESKTOP_FILE_INSTALL_DIR"));

  if (target_dir == NULL)
    target_dir = g_build_filename (DATADIR, "applications", NULL);

  /* Create the target directory */
  dir_permissions = permissions;

  /* Add search bit when the target file is readable */
  if (permissions & 0400)
    dir_permissions |= 0100;
  if (permissions & 0040)
    dir_permissions |= 0010;
  if (permissions & 0004)
    dir_permissions |= 0001;

  g_mkdir_with_parents (target_dir, dir_permissions);
  
  i = 0;
  while (args && args[i])
    {
      err = NULL;
      process_one_file (args[i], &err);
      if (err != NULL)
        {
          g_printerr (_("Error on file \"%s\": %s\n"),
                      args[i], err->message);

          g_error_free (err);
          
          return 1;
        }
      
      ++i;
    }

  if (i == 0)
    {
      g_printerr (_("Must specify one or more desktop files to install\n"));

      return 1;
    }
  
  g_option_context_free (context);

  return 0;
}
Exemple #30
0
/**
 * @brief Main entry to the Reversi C endgame solver implementation.
 *
 * @todo Documentation has to be completly developed.
 */
int
main (int argc, char *argv[])
{
  GamePositionDb *db;
  GamePositionDbSyntaxErrorLog *syntax_error_log;
  FILE *fp;

  GamePositionDbEntry *entry = NULL;
  int solver_index = -1;

  endgame_solver_env_t env =
    { .log_file = NULL,
      .pve_dump_file = NULL,
      .repeats = 0,
      .pv_recording = false,
      .pv_full_recording = false,
      .pv_no_print = false
    };

  /* GLib command line options and argument parsing. */
  GError *error = NULL;
  GOptionGroup *option_group = g_option_group_new("name", "description", "help_description", NULL, NULL);
  GOptionContext *context = g_option_context_new("- Solve an endgame position");
  g_option_context_add_main_entries(context, entries, NULL);
  g_option_context_add_group(context, option_group);
  g_option_context_set_description(context, program_documentation_string);
  if (!g_option_context_parse (context, &argc, &argv, &error)) {
    g_print("Option parsing failed: %s\n", error->message);
    return -1;
  }

  /* Checks command line options for consistency, and selects the solver. */
  if (!input_file) {
    g_print("Option -f, --file is mandatory.\n");
    return -2;
  }
  if (solver_id) {
    solver_index = egs_select_solver(solver_id);
    if (solver_index == -1) {
      g_print("Option -s, --solver is out of range.\n");
      return -8;
    }
    if (strcmp(solvers[solver_index].id, "rand") == 0) {
      if (repeats < 1) {
        g_print("Option -n, --repeats is out of range.\n");
        return -9;
      }
    }
  } else {
    g_print("Option -s, --solver is mandatory.\n");
    return -5;
  }
  const endgame_solver_t *const solver = &solvers[solver_index];
  if (pv_rec && !(!strcmp(solver->id, "es") || !strcmp(solver->id, "es2"))) {
    g_print("Option --pv-rec can be used only with solver \"es\" or \"es2\".\n");
    return -10;
  }
  if (pv_full_rec && !(!strcmp(solver->id, "es") || !strcmp(solver->id, "es2"))) {
    g_print("Option --pv-full-rec can be used only with solver \"es\" or \"es2\".\n");
    return -10;
  }
  if (pv_no_print && (strcmp(solver->id, "es") || !pv_full_rec)) {
    g_print("Option --pv-no-print can be used only with solver \"es\", and when option --pv-full-rec is turned on.\n");
    return -11;
  }

  /* Opens the source file for reading. */
  fp = fopen(input_file, "r");
  if (!fp) {
    g_print("Unable to open database resource for reading, file \"%s\" does not exist.\n", input_file);
    return -3;
  }

  /* Loads the game position database. */
  db = gpdb_new(g_strdup(input_file));
  syntax_error_log = NULL;
  error = NULL;
  gpdb_load(fp, input_file, db, &syntax_error_log, &error);
  fclose(fp);

  /* Compute the number of errors logged. */
  const int number_of_errors = gpdb_syntax_error_log_length(syntax_error_log);
  if (number_of_errors != 0) {
    g_print("The database resource, file \"%s\" contains errors, debug it using the gpdb_verify utility.\n", input_file);
    return -4;
  }

  /* Lookup for a given key. */
  if (lookup_entry) {
    entry = gpdb_lookup(db, lookup_entry);
    if (entry) {
      gchar *tmp = gpdb_entry_print(entry);
      g_print("%s", tmp);
      g_free(tmp);
    } else {
      g_print("Entry %s not found in file %s.\n", lookup_entry, input_file);
      return -6;
    }
  } else {
    g_print("No entry provided.\n");
    return -7;
  }

  /* Initializes the board module. */
  board_module_init();

  /* Sets env structure. */
  env.log_file = log_file;
  env.pve_dump_file = pve_dump_file;
  env.repeats = repeats;
  env.pv_recording = pv_rec || pv_full_rec;
  env.pv_full_recording = pv_full_rec;
  env.pv_no_print = pv_no_print;

  /* Solves the position. */
  //GamePosition *gp = entry->game_position;
  GamePositionX *gpx = game_position_x_gp_to_gpx(entry->game_position);
  ExactSolution *solution = NULL;
  g_print("Solving game position %s, from source %s, using solver %s (%s) ...\n", entry->id, input_file, solver->id, solver->description);
  solution = solver->fn(gpx, &env);

  /* Prints results. */
  gchar *solution_to_string = exact_solution_to_string(solution);
  printf("\n%s\n", solution_to_string);
  g_free(solution_to_string);

  /* Frees the resources. */
  g_free(error);
  gpdb_free(db, TRUE);
  if (syntax_error_log)
    gpdb_syntax_error_log_free(syntax_error_log);
  g_option_context_free(context);
  exact_solution_free(solution);
  free(gpx);

  return 0;
}



/**
 * @cond
 */

/*
 * Internal functions.
 */

/**
 * @brief Ruturns the index in the solvers arry of the endgame solver identified by `id`.
 *
 * @details Compares the `id` parameter with the values in the solvers static array,
 *          if the `id` parameter matches with the solver id field then the solver
 *          position is returned. If no solver matches, a `-1` value is returned.
 *
 * @param [in] id the label of the solver
 * @return        the solver index
 */
static int
egs_select_solver (const char *const id)
{
  g_assert(id);
  for (size_t i = 0; i < solvers_count; i++) {
    endgame_solver_t egs = solvers[i];
    if (strcmp(id, egs.id) == 0) return i;
  }
  return -1;
}