static void startup(void)
{
	g_type_init();
}
Beispiel #2
0
int main (int argc, char ** argv) {
	g_thread_init (NULL);
	g_type_init ();
	return _vala_main ();
}
Beispiel #3
0
int
main(int argc, char *argv[])
{
    evbase_t *evbase = NULL;
    evhtp_t *htp = NULL;
    int daemon_mode = 1;
    int c;
    char *logfile = NULL;
    char *ccnet_debug_level_str = "info";
    char *http_debug_level_str = "debug";
    const char *debug_str = NULL;
    char *temp_file_dir = NULL;

#ifdef WIN32
    argv = get_argv_utf8 (&argc);
#endif

    config_dir = DEFAULT_CONFIG_DIR;

    while ((c = getopt_long(argc, argv,
                short_opts, long_opts, NULL)) != EOF) {
        switch (c) {
        case 'h':
            usage();
            exit(0);
        case 'v':
            exit(-1);
            break;
        case 'c':
            config_dir = strdup(optarg);
            break;
        case 'd':
            seafile_dir = strdup(optarg);
            break;
        case 't':
            num_threads = atoi(optarg);
            break;
        case 'f':
            daemon_mode = 0;
            break;
        case 'l':
            logfile = g_strdup(optarg);
            break;
        case 'g':
            ccnet_debug_level_str = optarg;
            break;
        case 'G':
            http_debug_level_str = optarg;
            break;
        case 'D':
            debug_str = optarg;
            break;
        case 'k':
            temp_file_dir = optarg;
            break;
        case 'P':
            pidfile = optarg;
            break;
        default:
            usage();
            exit(-1);
        }
    }

#ifndef WIN32
    if (daemon_mode)
        daemon(1, 0);
#else
    WSADATA     wsadata;
    WSAStartup(0x0101, &wsadata);
#endif

    g_type_init();

    if (!debug_str)
        debug_str = g_getenv("SEAFILE_DEBUG");
    seafile_debug_set_flags_string (debug_str);

    if (seafile_dir == NULL)
        seafile_dir = g_build_filename (config_dir, "seafile-data", NULL);
    if (logfile == NULL)
        logfile = g_build_filename (seafile_dir, "http.log", NULL);

    if (seafile_log_init (logfile, ccnet_debug_level_str,
                          http_debug_level_str) < 0) {
        g_warning ("Failed to init log.\n");
        exit (1);
    }

    ccnet_client = ccnet_client_new();
    if ((ccnet_client_load_confdir(ccnet_client, config_dir)) < 0) {
        g_warning ("Read config dir error\n");
        return -1;
    }

    seaf = seafile_session_new (seafile_dir, ccnet_client);
    if (!seaf) {
        g_warning ("Failed to create seafile session.\n");
        exit (1);
    }
    if (seafile_session_init(seaf) < 0)
        exit (1);

    if (temp_file_dir == NULL)
        seaf->http_temp_dir = g_build_filename (seaf->seaf_dir, "httptemp", NULL);
    else
        seaf->http_temp_dir = g_strdup(temp_file_dir);

    seaf->client_pool = ccnet_client_pool_new (config_dir);

    load_httpserver_config (seaf);
    if (use_https) {
        seaf_message ("port = %d, https = true, pemfile = %s, privkey = %s\n",
                      bind_port, pemfile, privkey);
    } else {
        seaf_message ("port = %d, https = false\n", bind_port);
    }

    evbase = event_base_new();
    htp = evhtp_new(evbase, NULL);

    if (pemfile != NULL) {
        evhtp_ssl_cfg_t scfg;

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

        scfg.pemfile        = pemfile;
        scfg.privfile       = privkey;
        scfg.scache_type    = evhtp_ssl_scache_type_internal;
        scfg.scache_timeout = 5000;

        evhtp_ssl_init (htp, &scfg);
    }

    if (access_file_init (htp) < 0)
        exit (1);

    if (upload_file_init (htp) < 0)
        exit (1);

    evhtp_set_gencb(htp, default_cb, NULL);

    evhtp_use_threads(htp, NULL, num_threads, NULL);

    if (evhtp_bind_socket(htp, bind_addr, bind_port, 128) < 0) {
        g_warning ("Could not bind socket: %s\n", strerror(errno));
        exit(-1);
    }

    if (pidfile) {
        if (write_pidfile (pidfile) < 0) {
            seaf_message ("Failed to write pidfile\n");
            return -1;
        }
    }
    
    atexit (on_httpserver_exit);

    event_base_loop(evbase, 0);

    return 0;
}
Beispiel #4
0
int main(int argc, char *argv[])
{
    g_type_init ();

    dbg_init ();

    // initialize application state and zero out memory
    g_self = (state_t*) calloc( 1, sizeof(state_t) );
    state_t *self = g_self;



    // run the main loop
    self->loop = g_main_loop_new(NULL, FALSE);

    getopt_t *gopt = getopt_create();

    getopt_add_bool  (gopt, 'h',   "help",    0,        "Show this help");
    getopt_add_bool  (gopt, 'v',   "verbose",    0,     "Be verbose");

    if (!getopt_parse(gopt, argc, argv, 1) || getopt_get_bool(gopt,"help")) {
        printf("Usage: %s [options]\n\n", argv[0]);
        getopt_do_usage(gopt);
        return 0;
    }

    self->verbose = getopt_get_bool(gopt, "verbose");

    self->lcm = lcm_create(NULL);
    if (!self->lcm)
        return 1;

    // read config file
    if (!(self->config = read_config_file ())) {
        dbg (DBG_ERROR, "[viewer] failed to read config file.");
        return -1;
    }


    // attach lcm to main loop
    glib_mainloop_attach_lcm (self->lcm);

    // publish cam settings every now and then
    // g_timeout_add_seconds (2, &publish_log_info_data, self);
    // g_timeout_add_seconds (2, &dump_to_index_file, self);

    // listen to tablet event
    navlcm_log_info_t_subscribe (self->lcm, "LOG_INFO", on_log_info_set_event, self);

    list_files (self);

    publish_log_info_data (self);

    // connect to kill signal
    signal_pipe_glib_quit_on_kill (self->loop);

    // run main loop
    g_main_loop_run (self->loop);

    // cleanup
    g_main_loop_unref (self->loop);

    return 0;
}
Beispiel #5
0
  NiceConnection::NiceConnection(MediaType med, const std::string &transport_name,NiceConnectionListener* listener, 
      unsigned int iceComponents, const IceConfig& iceConfig, std::string username, std::string password)
     : mediaType(med), agent_(NULL), listener_(listener), candsDelivered_(0), context_(NULL), iceState_(NICE_INITIAL), iceComponents_(iceComponents) {

    localCandidates.reset(new std::vector<CandidateInfo>());
    transportName.reset(new std::string(transport_name));
    for (unsigned int i = 1; i<=iceComponents_; i++) {
      comp_state_list_[i] = NICE_INITIAL;
    }
    
    g_type_init();
    context_ = g_main_context_new();
    g_main_context_set_poll_func(context_,timed_poll);
    ELOG_DEBUG("Creating Agent");
    nice_debug_enable( FALSE );
    // Create a nice agent
    agent_ = nice_agent_new(context_, NICE_COMPATIBILITY_RFC5245);
    GValue controllingMode = { 0 };
    g_value_init(&controllingMode, G_TYPE_BOOLEAN);
    g_value_set_boolean(&controllingMode, false);
    g_object_set_property(G_OBJECT( agent_ ), "controlling-mode", &controllingMode);

    GValue checks = { 0 };
    g_value_init(&checks, G_TYPE_UINT);
    g_value_set_uint(&checks, 100);
    g_object_set_property(G_OBJECT( agent_ ), "max-connectivity-checks", &checks);


    if (iceConfig.stunServer.compare("") != 0 && iceConfig.stunPort!=0){
      GValue val = { 0 }, val2 = { 0 };
      g_value_init(&val, G_TYPE_STRING);
      g_value_set_string(&val, iceConfig.stunServer.c_str());
      g_object_set_property(G_OBJECT( agent_ ), "stun-server", &val);

      g_value_init(&val2, G_TYPE_UINT);
      g_value_set_uint(&val2, iceConfig.stunPort);
      g_object_set_property(G_OBJECT( agent_ ), "stun-server-port", &val2);

      ELOG_DEBUG("Setting STUN server %s:%d", iceConfig.stunServer.c_str(), iceConfig.stunPort);
    }

    // Connect the signals
    g_signal_connect( G_OBJECT( agent_ ), "candidate-gathering-done",
        G_CALLBACK( cb_candidate_gathering_done ), this);
    g_signal_connect( G_OBJECT( agent_ ), "component-state-changed",
        G_CALLBACK( cb_component_state_changed ), this);
    g_signal_connect( G_OBJECT( agent_ ), "new-selected-pair",
        G_CALLBACK( cb_new_selected_pair ), this);
    g_signal_connect( G_OBJECT( agent_ ), "new-candidate",
        G_CALLBACK( cb_new_candidate ), this);

    // Create a new stream and start gathering candidates
    ELOG_DEBUG("Adding Stream... Number of components %d", iceComponents_);
    nice_agent_add_stream(agent_, iceComponents_);
    gchar *ufrag = NULL, *upass = NULL;
    nice_agent_get_local_credentials(agent_, 1, &ufrag, &upass);
    ufrag_ = std::string(ufrag); g_free(ufrag);
    upass_ = std::string(upass); g_free(upass);

    // Set our remote credentials.  This must be done *after* we add a stream.
    if (username.compare("")!=0 && password.compare("")!=0){
      ELOG_DEBUG("Setting remote credentials in constructor");
      this->setRemoteCredentials(username, password);
    }
    // Set Port Range ----> If this doesn't work when linking the file libnice.sym has to be modified to include this call
    if (iceConfig.minPort!=0 && iceConfig.maxPort!=0){
      ELOG_DEBUG("Setting port range: %d to %d\n", iceConfig.minPort, iceConfig.maxPort);
      nice_agent_set_port_range(agent_, (guint)1, (guint)1, (guint)iceConfig.minPort, (guint)iceConfig.maxPort);
    }

    if (iceConfig.turnServer.compare("") != 0 && iceConfig.turnPort!=0){
        ELOG_DEBUG("Setting TURN server %s:%d", iceConfig.turnServer.c_str(), iceConfig.turnPort);
        ELOG_DEBUG("Setting TURN credentials %s:%s", iceConfig.turnUsername.c_str(), iceConfig.turnPass.c_str());

        for (unsigned int i = 1; i <= iceComponents_ ; i++){
          nice_agent_set_relay_info     (agent_,
              1,
              i,
              iceConfig.turnServer.c_str(),      // TURN Server IP
              iceConfig.turnPort,    // TURN Server PORT
              iceConfig.turnUsername.c_str(),      // Username
              iceConfig.turnPass.c_str(),      // Pass
              NICE_RELAY_TYPE_TURN_UDP);
        }
    }
    
    if(agent_){
      for (unsigned int i = 1; i<=iceComponents_; i++){
        nice_agent_attach_recv(agent_, 1, i, context_, cb_nice_recv, this);
      }
      running_ = true;
    }
    else{
      running_=false;
    }
  m_Thread_ = boost::thread(&NiceConnection::init, this);
}
Beispiel #6
0
int
main (int argc, char **argv)
{
	GOptionContext *context;
	GError *error = NULL;
	GDBusConnection *bus;
	GDBusProxy *mpris;
	GDBusProxy *queue;
	GApplication *app;
	gboolean loaded;
	gboolean scanned;
	GVariant *state;

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

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

	rb_debug_init (debug);

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

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


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

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

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

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

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

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

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

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

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

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

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

		rate_song (mpris, set_rating);
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	if (mpris) {
		g_object_unref (mpris);
	}

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

	return 0;
}
Beispiel #7
0
int
main (int argc, char **argv)
{
  GOptionContext *ctx;
  GError *error = NULL;
  int ecode;
  TpDebugSender *sender;

  g_type_init ();

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

  ctx = meta_get_option_context ();
  g_option_context_add_main_entries (ctx, gnome_shell_options, GETTEXT_PACKAGE);
  if (!g_option_context_parse (ctx, &argc, &argv, &error))
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      exit (1);
    }

  g_option_context_free (ctx);

  meta_plugin_manager_set_plugin_type (gnome_shell_plugin_get_type ());

  /* Prevent meta_init() from causing gtk to load gail and at-bridge */
  g_setenv ("NO_AT_BRIDGE", "1", TRUE);
  meta_init ();
  g_unsetenv ("NO_AT_BRIDGE");

  /* FIXME: Add gjs API to set this stuff and don't depend on the
   * environment.  These propagate to child processes.
   */
  g_setenv ("GJS_DEBUG_OUTPUT", "stderr", TRUE);
  g_setenv ("GJS_DEBUG_TOPICS", "JS ERROR;JS LOG", TRUE);

  shell_dbus_init (meta_get_replace_current_wm ());
  shell_a11y_init ();
  shell_perf_log_init ();
  shell_prefs_init ();
  shell_introspection_init ();

  /* Turn on telepathy-glib debugging but filter it out in
   * default_log_handler. This handler also exposes all the logs over D-Bus
   * using TpDebugSender. */
  tp_debug_set_flags ("all");

  sender = tp_debug_sender_dup ();
  g_log_set_default_handler (default_log_handler, sender);

  /* Initialize the global object */
  if (session_mode == NULL)
    session_mode = is_gdm_mode ? "gdm" : "user";

  _shell_global_init ("session-mode", session_mode, NULL);

  ecode = meta_run ();

  if (g_getenv ("GNOME_SHELL_ENABLE_CLEANUP"))
    {
      g_printerr ("Doing final cleanup...\n");
      g_object_unref (shell_global_get ());
    }

  g_object_unref (sender);

  return ecode;
}
Beispiel #8
0
Datei: main.c Projekt: hsgg/quark
int
main (int argc, char **argv)
{
#ifdef USE_GCONF
    GConfClient *gconf;
#endif

    char *dir;
    struct sigaction action;
    sigset_t sigset;

    main_status = QUARK_STARTING;

    /* initialize the locale */
    if (!setlocale(LC_ALL, ""))
	g_warning("Couldn't set locale from environment.\n");
    bindtextdomain(PACKAGE_NAME, LOCALEDIR);
    bind_textdomain_codeset(PACKAGE_NAME, "UTF-8");
    textdomain(PACKAGE_NAME);

    /* set up signal handler */
    sigemptyset (&sigset);
    action.sa_handler = signal_handler;
    action.sa_mask = sigset;
    action.sa_flags = SA_NOCLDSTOP;
    sigaction (SIGTERM, &action, (struct sigaction *) NULL);
    sigaction (SIGINT, &action, (struct sigaction *) NULL);
    sigaction (SIGHUP, &action, (struct sigaction *) NULL);

    g_type_init ();
    gnome_vfs_init ();

#ifdef USE_GCONF
    gconf = gconf_client_get_default ();
    gconf_client_add_dir (gconf, QUARK_GCONF_ROOT,
                          GCONF_CLIENT_PRELOAD_RECURSIVE, NULL);
    gconf_client_notify_add (gconf, QUARK_GCONF_ROOT, config_changed, NULL,
                             NULL, NULL);
#endif

    /* make the directory we use in ~ */
    dir = g_build_filename (g_get_home_dir(), ".quark", NULL);
    mkdir (dir, S_IRWXU|S_IRWXG|S_IRWXO);
    g_free (dir);

    loop = g_main_loop_new (NULL, FALSE);

    if (!fifo_open ()) {
        g_critical("failed to open fifo");
        return 1;
    }

    music_init ();

    g_static_mutex_lock (&main_mutex);
    playlist_init ();
#ifdef USE_GCONF
    config_load (gconf);
#endif
    main_status = QUARK_RUNNING;
    g_static_mutex_unlock (&main_mutex);

    g_main_loop_run (loop);

    g_static_mutex_lock (&main_mutex);
    main_status = QUARK_EXITING;
#ifdef USE_GCONF
    config_save (gconf);
#endif
    playlist_destroy ();
    g_static_mutex_unlock (&main_mutex);

    music_destroy ();

    fifo_destroy ();
    g_main_loop_unref (loop);
#ifdef USE_GCONF
    g_object_unref (G_OBJECT (gconf));
#endif

    gnome_vfs_shutdown ();

    return 0;
}
static int __process_request()
{
	int ret = -1;
	int mode = PM_DEFAULT;
	pkgmgr_client *pc = NULL;
	switch (data.request) {
	case INSTALL_REQ:
		if (data.pkg_type[0] == '\0' || data.pkg_path[0] == '\0') {
			printf("Please provide the arguments.\n");
			printf("use -h option to see usage\n");
			ret = -1;
			break;
		}
		g_type_init();
		main_loop = g_main_loop_new(NULL, FALSE);
		pc = pkgmgr_client_new(PC_REQUEST);
		if (pc == NULL) {
			printf("PkgMgr Client Creation Failed\n");
			ret = -1;
			break;
		}
		if (data.quiet == 0)
			mode = PM_DEFAULT;
		else
			mode = PM_QUIET;
		if (data.des_path[0] == '\0')
			ret =
			    pkgmgr_client_install(pc, data.pkg_type, NULL,
						  data.pkg_path, NULL, mode,
						  __return_cb, pc);
		else
			ret =
			    pkgmgr_client_install(pc, data.pkg_type,
						  data.des_path, data.pkg_path,
						  NULL, mode, __return_cb, pc);
		if (ret < 0)
			break;
		g_main_loop_run(main_loop);
		ret = data.result;
		break;

	case UNINSTALL_REQ:
		if (data.pkg_type[0] == '\0' || data.pkg_name[0] == '\0') {
			printf("Please provide the arguments.\n");
			printf("use -h option to see usage\n");
			ret = -1;
			break;
		}
		g_type_init();
		main_loop = g_main_loop_new(NULL, FALSE);
		pc = pkgmgr_client_new(PC_REQUEST);
		if (pc == NULL) {
			printf("PkgMgr Client Creation Failed\n");
			ret = -1;
			break;
		}
		if (data.quiet == 0)
			mode = PM_DEFAULT;
		else
			mode = PM_QUIET;
#if 0
		ret = __is_app_installed(data.pkg_name);
		if (ret == -1) {
			printf("package is not installed\n");
			break;
		}
#else
		pkgmgr_pkginfo_h handle;
		ret = pkgmgr_get_pkginfo(data.pkg_name, &handle);
		if(ret < 0) {
			printf("package is not in pkgmgr_info DB\n");
		} else
			pkgmgr_destroy_pkginfo(handle);
#endif
		ret =
		    pkgmgr_client_uninstall(pc, data.pkg_type, data.pkg_name,
					    mode, __return_cb, NULL);
		if (ret < 0)
			break;
		g_main_loop_run(main_loop);
		ret = data.result;
		break;

	case CLEAR_REQ:
		if (data.pkg_type[0] == '\0' || data.pkg_name[0] == '\0') {
			printf("Please provide the arguments.\n");
			printf("use -h option to see usage\n");
			ret = -1;
			break;
		}

		pc = pkgmgr_client_new(PC_REQUEST);
		if (pc == NULL) {
			printf("PkgMgr Client Creation Failed\n");
			ret = -1;
			break;
		}
		if (data.quiet == 0)
			mode = PM_DEFAULT;
		else
			mode = PM_QUIET;
		ret = __is_app_installed(data.pkg_name);
		if (ret == -1) {
			printf("package is not installed\n");
			break;
		}
		ret = pkgmgr_client_clear_user_data(pc, data.pkg_type,
						    data.pkg_name, mode);
		if (ret < 0)
			break;
		ret = data.result;
		break;

	case ACTIVATE_REQ:
		if (data.pkg_type[0] == '\0' || data.pkg_name[0] == '\0') {
			printf("Please provide the arguments.\n");
			printf("use -h option to see usage\n");
			ret = -1;
			break;
		}

		pc = pkgmgr_client_new(PC_REQUEST);
		if (pc == NULL) {
			printf("PkgMgr Client Creation Failed\n");
			ret = -1;
			break;
		}

		ret = pkgmgr_client_activate(pc, data.pkg_type, data.pkg_name);
		if (ret < 0)
			break;
		ret = data.result;

		break;


	case DEACTIVATE_REQ:
		if (data.pkg_type[0] == '\0' || data.pkg_name[0] == '\0') {
			printf("Please provide the arguments.\n");
			printf("use -h option to see usage\n");
			ret = -1;
			break;
		}

		pc = pkgmgr_client_new(PC_REQUEST);
		if (pc == NULL) {
			printf("PkgMgr Client Creation Failed\n");
			ret = -1;
			break;
		}

		ret = pkgmgr_client_deactivate(pc, data.pkg_type, data.pkg_name);
		if (ret < 0)
			break;
		ret = data.result;

		break;

	case LIST_REQ:
		ret = pkgmgr_get_pkg_list(__iter_fn, NULL);
		break;

	case SHOW_REQ:
		if (data.pkg_name[0] != '\0') {
			pkgmgr_info *pkg_info =
			    pkgmgr_info_new(data.pkg_type, data.pkg_name);
			if (pkg_info == NULL) {
				printf("Failed to get pkginfo handle\n");
				ret = -1;
				break;
			}
			__print_pkg_info(pkg_info);
			ret = pkgmgr_info_free(pkg_info);
			break;
		}
		if (data.pkg_path[0] != '\0') {
			pkgmgr_info *pkg_info =
			    pkgmgr_info_new_from_file(data.pkg_type,
						      data.pkg_path);
			if (pkg_info == NULL) {
				printf("Failed to get pkginfo handle\n");
				ret = -1;
				break;
			}
			__print_pkg_info(pkg_info);
			ret = pkgmgr_info_free(pkg_info);
			break;
		}
		printf("Either pkgname or pkgpath should be supplied\n");
		ret = -1;
		break;

	case HELP_REQ:
		__print_usage();
		ret = 0;
		break;

	default:
		printf("Wrong Request\n");
		ret = -1;
		break;
	}

	if (pc) {
		pkgmgr_client_free(pc);
		pc = NULL;
	}
	return ret;
}
Beispiel #10
0
int main(int argc, const char* argv[]) {
    void *options = gopt_sort(&argc, argv, gopt_start(
            gopt_option('h', 0, gopt_shorts('h', '?'), gopt_longs("help", "HELP")),
            gopt_option('m', 0, gopt_shorts('m'), gopt_longs("mute")),
            gopt_option('v', GOPT_REPEAT, gopt_shorts('v'), gopt_longs("verbose")),
            gopt_option('i', GOPT_ARG, gopt_shorts('i'), gopt_longs("icon"))));
    int help = gopt(options, 'h');
    int debug = gopt(options, 'v');
    int muted = gopt(options, 'm');
	const char *icon;

	if (gopt_arg(options, 'i', &icon) == 0) {
		icon = "speaker";
	}

    gopt_free(options);

    if (help)
        print_usage(argv[0], FALSE);  

    gint volume;
    if (muted) {
        if (argc > 2) {
            print_usage(argv[0], TRUE);
        } else if (argc == 2) {
            if (sscanf(argv[1], "%d", &volume) != 1)
                print_usage(argv[0], TRUE);

            if (volume > 100 || volume < 0)
                print_usage(argv[0], TRUE);
        } else {
            volume = 0;
        }
    } else {
        if (argc != 2)
            print_usage(argv[0], TRUE);

        if (sscanf(argv[1], "%d", &volume) != 1)
            print_usage(argv[0], TRUE);

        if (volume > 100 || volume < 0)
            print_usage(argv[0], TRUE);
    }

    // round volume
    volume = (int)(round(volume / 5.0) * 5.0);

    DBusGConnection *bus = NULL;
    DBusGProxy *proxy = NULL;
    GError *error = NULL;

    // initialize GObject
    g_type_init();

    // connect to D-Bus
    print_debug("Connecting to D-Bus...", debug);
    bus = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
    if (error != NULL)
        handle_error("Couldn't connect to D-Bus",
                    error->message,
                    TRUE);
    print_debug_ok(debug);

    // get the proxy
    print_debug("Getting proxy...", debug);
    proxy = dbus_g_proxy_new_for_name(bus,
                                      VALUE_SERVICE_NAME,
                                      VALUE_SERVICE_OBJECT_PATH,
                                      VALUE_SERVICE_INTERFACE);
    if (proxy == NULL)
        handle_error("Couldn't get a proxy for D-Bus",
                    "Unknown(dbus_g_proxy_new_for_name)",
                    TRUE);
    print_debug_ok(debug);

    print_debug("Sending volume...", debug);
    uk_ac_cam_db538_VolumeNotification_notify(proxy, volume, muted, icon, &error);
    if (error !=  NULL) {
        handle_error("Failed to send notification", error->message, FALSE);
        g_clear_error(&error);
        return EXIT_FAILURE;
    }
    print_debug_ok(debug);

    return EXIT_SUCCESS;
}
Beispiel #11
0
int main (int argc, char ** argv) {
	g_type_init ();
	return _vala_main (argv, argc);
}
Beispiel #12
0
static void init_gconf_client (void)
{
  g_type_init ();
  client = gconf_client_get_default ();
}
Beispiel #13
0
int main(int argc, char *argv[]) {
	
	GMappedFile *program_file=0;
	gchar* prog_ptr=0;
	const gchar* ssk_sig=SSK_SIGNATURE;
	GError *error=0;
	bool isFound=0;
	int i,j;
	g_type_init();
	if(argc!=3) {
		USAGE;
		exit(1);
	}
		
	program_file = g_mapped_file_new(argv[1], /* writable */ 1, &error);
	if( !program_file ) {
		g_printf("Can not open file: %s", error->message);
		g_error_free(error);
		USAGE;
		exit(2);
	}
	prog_ptr=g_mapped_file_get_contents(program_file);
	for(i=0; i<g_mapped_file_get_length(program_file) && !isFound; i++)	{
		if(prog_ptr[i]==ssk_sig[0]) {
			for(j=0; j<sizeof(SSK_SIGNATURE); j++)	{
				if(ssk_sig[j]==0) {
					isFound=1;
					break;
				}
				if(prog_ptr[i+j]!=ssk_sig[j]) {
					break;
				}
			}
		}
	}
	i+=sizeof(SSK_SIGNATURE)-2;
	if(!isFound) {
		g_printf("Can not find special signature in program.\n");
		USAGE;
		exit(3);
	}
	
	GPtrArray* serials = get_serial_array(&error);
	if( !serials ) {
		g_printf("%s\n", error->message);
		g_error_free(error);
		exit(4);
	}

	gchar* first_ser = g_ptr_array_index(serials,0);
		
	// select key here;
	for(j=0; first_ser[j]!=0; j++)	{
		prog_ptr[i+j]= first_ser[j];
	}
	prog_ptr[i+j]=0;
	FILE* outprog=fopen(argv[2], "w");
	if(!outprog) {
		g_printf("open file %s failed\n",argv[2]);
		exit(5);
	}
	fwrite(prog_ptr, 1, g_mapped_file_get_length(program_file), outprog);
	fclose(outprog);
	g_mapped_file_free(program_file);
	
	return 0;
}
Beispiel #14
0
int
fe_args (int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;

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

	context = g_option_context_new (NULL);
	g_option_context_add_main_entries (context, gopt_entries, GETTEXT_PACKAGE);
	g_option_context_parse (context, &argc, &argv, &error);
	
	g_type_init ();

	if (error)
	{
		if (error->message)
			printf ("%s\n", error->message);
		return 1;
	}

	g_option_context_free (context);

	if (arg_show_version)
	{
		printf (PACKAGE_TARNAME" "PACKAGE_VERSION"\n");
		return 0;
	}

	if (arg_show_autoload)
	{
#ifdef WIN32
		/* see the chdir() below */
		char *sl, *exe = strdup (argv[0]);
		sl = strrchr (exe, '\\');
		if (sl)
		{
			*sl = 0;
			printf ("%s\\plugins\n", exe);
		}
		free (exe);
#else
		printf ("%s\n", HEXCHATLIBDIR"/plugins");
#endif
		return 0;
	}

	if (arg_show_config)
	{
		printf ("%s\n", get_xdir ());
		return 0;
	}

	if (arg_cfgdir)	/* we want filesystem encoding */
	{
		if (xdir)
			g_free (xdir);
		xdir = strdup (arg_cfgdir);
		if (xdir[strlen (xdir) - 1] == '/')
			xdir[strlen (xdir) - 1] = 0;
		g_free (arg_cfgdir);
	}

	return -1;
}
Beispiel #15
0
static gboolean
get_device_info (const char            *path,
		 int                   *vendor_id,
		 int                   *product_id,
		 char                 **name,
		 WacomBusType          *bus,
		 WacomIntegrationFlags *integration_flags,
		 WacomError            *error)
{
	GUdevClient *client;
	GUdevDevice *device;
	const char * const subsystems[] = { "input", NULL };
	gboolean retval;
	char *bus_str;
	const char *devname;

#if NEED_G_TYPE_INIT
	g_type_init();
#endif

	retval = FALSE;
	/* The integration flags from device info are unset by default */
	*integration_flags = WACOM_DEVICE_INTEGRATED_UNSET;
	*name = NULL;
	bus_str = NULL;
	client = g_udev_client_new (subsystems);
	device = g_udev_client_query_by_device_file (client, path);
	if (device == NULL) {
		libwacom_error_set(error, WERROR_INVALID_PATH, "Could not find device '%s' in udev", path);
		goto out;
	}

	/* Touchpads are only for the "Finger" part of Bamboo devices */
	if (!is_tablet_or_touchpad(device)) {
		GUdevDevice *parent;

		parent = g_udev_device_get_parent(device);
		if (!parent || !is_tablet_or_touchpad(parent)) {
			libwacom_error_set(error, WERROR_INVALID_PATH, "Device '%s' is not a tablet", path);
			g_object_unref (parent);
			goto out;
		}
		g_object_unref (parent);
	}

	/* Is the device integrated in display? */
	devname = g_udev_device_get_name (device);
	if (devname != NULL) {
		char *sysfs_path, *contents;

		sysfs_path = g_build_filename ("/sys/class/input", devname, "device/properties", NULL);
		if (g_file_get_contents (sysfs_path, &contents, NULL, NULL)) {
			int flag;

			flag = atoi(contents);
			flag &= (1 << INPUT_PROP_DIRECT) | (1 << INPUT_PROP_POINTER);
			/*
			 * To ensure we are dealing with a screen tablet, need
			 * to check that it has DIRECT and non-POINTER (DIRECT
			 * alone is not sufficient since it's set for drawing
			 * tablets as well)
			 */
			if (flag == (1 << INPUT_PROP_DIRECT))
				*integration_flags = WACOM_DEVICE_INTEGRATED_DISPLAY;
			else
				*integration_flags = WACOM_DEVICE_INTEGRATED_NONE;

			g_free (contents);
		}
		g_free (sysfs_path);
	}

	*name = g_strdup (g_udev_device_get_sysfs_attr (device, "name"));
	/* Try getting the name from the parent if that fails */
	if (*name == NULL) {
		GUdevDevice *parent;

		parent = g_udev_device_get_parent (device);
		if (!parent)
			goto out;
		*name = g_strdup (g_udev_device_get_sysfs_attr (parent, "name"));
		g_object_unref (parent);
	}

	/* Parse the PRODUCT attribute (for Bluetooth, USB, I2C) */
	retval = get_bus_vid_pid (device, bus, vendor_id, product_id, error);
	if (retval)
		goto out;

	bus_str = get_bus (device);
	*bus = bus_from_str (bus_str);

	if (*bus == WBUSTYPE_SERIAL) {
		/* The serial bus uses 0:0 as the vid/pid */
		*vendor_id = 0;
		*product_id = 0;
		retval = TRUE;
	} else {
		libwacom_error_set(error, WERROR_UNKNOWN_MODEL, "Unsupported bus '%s'", bus_str);
	}

out:
	if (bus_str != NULL)
		g_free (bus_str);
	if (retval == FALSE)
		g_free (*name);
	if (device != NULL)
		g_object_unref (device);
	if (client != NULL)
		g_object_unref (client);
	return retval;
}
Beispiel #16
0
int main(int argc, char **argv)
{
	XmrApp *app;
	GOptionContext *context;
	GError *error = NULL;
	PlayerAction player_action = ActionNone;

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

	// !!! glib manual says since version 2.36
	// but ubuntu 13.04 !!!
#if !GLIB_CHECK_VERSION(2, 35, 7)
	g_type_init();
#endif
	
	// to make non-installed schemas loadable
	{
		gchar *schema_dir;
		schema_dir = g_build_filename(xmr_app_dir(), "glib-2.0/schemas", NULL);
		if (g_file_test(schema_dir, G_FILE_TEST_EXISTS))
			g_setenv("GSETTINGS_SCHEMA_DIR", schema_dir, TRUE);

		g_free(schema_dir);
	}

	setlocale(LC_ALL, NULL);

#ifdef ENABLE_NLS
	/* initialize i18n */
	{
		gchar *locale_dir = g_build_filename(xmr_app_dir(), "locale", NULL);
		if (g_file_test(locale_dir, G_FILE_TEST_EXISTS) &&
			g_file_test(locale_dir, G_FILE_TEST_IS_DIR))
		{
			bindtextdomain(GETTEXT_PACKAGE, locale_dir);
		}
		else
		{
			bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
		}
		bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
		
		g_free(locale_dir);
	}

	textdomain(GETTEXT_PACKAGE);
#endif
	
	context = g_option_context_new(NULL);

	g_option_context_add_main_entries(context, options, GETTEXT_PACKAGE);

	g_option_context_add_group(context, gtk_get_option_group(TRUE));
	g_option_context_add_group(context, gst_init_get_option_group());

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE)
	{
		g_print(_("%s\nRun '%s --help' to see a full list of available command line options.\n"),
			 error->message, argv[0]);
		g_error_free(error);
		g_option_context_free(context);
		exit(1);
	}

	g_option_context_free(context);

	if (action_play){
		player_action = ActionPlay;
	}else if (action_pause){
		player_action = ActionPause;
	}else if(action_next){
		player_action = ActionNext;
	}else if(action_love){
		player_action = ActionLove;
	}else if(action_hate){
		player_action = ActionHate;
	}

	if (player_action != ActionNone)
	{
		DBusConnection *bus;
		DBusError dbus_error;
		dbus_error_init(&dbus_error);
		bus = dbus_bus_get(DBUS_BUS_SESSION, &dbus_error);
		if (!bus)
		{
			g_warning ("Failed to connect to the D-BUS daemon: %s", dbus_error.message);
			dbus_error_free(&dbus_error);
			exit(1);
		}
		
		dbus_connection_setup_with_g_main(bus, NULL);

		send_action(bus, player_action);

		xmr_utils_cleanup();

		// exit directly
		return 0;
	}

	xmr_debug_enable(debug);

	gst_init(&argc, &argv);

	curl_global_init(CURL_GLOBAL_ALL);

	// this make our XmrRadio always works
	g_object_set(gtk_settings_get_default(),
				"gtk-button-images", TRUE,
				NULL);

	app = xmr_app_instance();

	init_icon_theme();

	g_application_run(G_APPLICATION(app), argc, argv);

	// remove ...
	list_file(xmr_tmp_dir(), FALSE, remove_file, NULL);

	g_object_unref(app);

	curl_global_cleanup();
	xmr_utils_cleanup();

	return 0;
}
int
main (int argc, char **argv)
{
  GError *error;
  GHashTable *table;
  gchar *srcfile;
  gchar *target = NULL;
  gchar *binary_target = NULL;
  gboolean generate_automatic = FALSE;
  gboolean generate_source = FALSE;
  gboolean generate_header = FALSE;
  gboolean manual_register = FALSE;
  gboolean generate_dependencies = FALSE;
  char *c_name = NULL;
  char *c_name_no_underscores;
  GOptionContext *context;
  GOptionEntry entries[] = {
    { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
    { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &sourcedirs, N_("The directories where files are to be read from (default to current directory)"), N_("DIRECTORY") },
    { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
    { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
    { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
    { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
    { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
    { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
    { NULL }
  };

#ifdef G_OS_WIN32
  extern gchar *_glib_get_locale_dir (void);
  gchar *tmp;
#endif

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

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

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

  g_type_init ();

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

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

  g_option_context_free (context);

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

  srcfile = argv[1];

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

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

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

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

      target = g_build_filename (dirname, target_basename, NULL);
      g_free (target_basename);
      g_free (dirname);
      g_free (base);
    }
  else if (generate_automatic)
    {
      if (g_str_has_suffix (target, ".c"))
        generate_source = TRUE;
      else if (g_str_has_suffix (target, ".h"))
        generate_header = TRUE;
      else if (g_str_has_suffix (target, ".gresource"))
        ;
    }

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

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

      g_hash_table_iter_init (&iter, table);
      while (g_hash_table_iter_next (&iter, &key, &data))
        {
          file_data = data;
          g_print ("%s\n",file_data->filename);
        }
    }
  else if (generate_source || generate_header)
    {
      if (generate_source)
	{
	  int fd = g_file_open_tmp (NULL, &binary_target, NULL);
	  if (fd == -1)
	    {
	      g_printerr ("Can't open temp file\n");
	      return 1;
	    }
	  close (fd);
	}

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

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

	  s = g_string_new ("");

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

	    }

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

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

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

  if (generate_header)
    {
      FILE *file;

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

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

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

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

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

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

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

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

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

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

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


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

      fclose (file);

      g_free (data);
    }

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

  return 0;
}
int
main (int argc, char *argv[])
{
	GOptionContext *context = NULL;  /* owned */
	ExitStatus retval = EXIT_SUCCESS;
	guint i;
	GPtrArray/*<owned WblSchema>*/ *schemas = NULL;  /* owned */
	WblSchema *meta_schema = NULL;  /* owned */
	WblMetaSchemaType meta_schema_type;
	const gchar *meta_schema_name;
	GError *error = NULL;

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

	setlocale (LC_ALL, "");

	/* Redirect debug output to stderr so that stdout is purely useful. */
	g_log_set_default_handler (wbl_log, NULL);

	/* Command line parsing. */
	context = g_option_context_new (_("— validate JSON schemas"));
	g_option_context_set_summary (context,
	                              _("Validate one or more JSON Schemas, "
	                                "checking for well-formedness, and "
	                                "validating against a JSON "
	                                "meta-schema.\n\nThere are two "
	                                "meta-schemas:\n • meta-schema: Used "
	                                "for schemas written for pure "
	                                "validation.\n • hyper-meta-schema: "
	                                "Used for schemas written for "
	                                "validation and hyper-linking.\n\nThe "
	                                "hyper-meta-schema is used by default, "
	                                "and is a superset of meta-schema.\n\n"
	                                "Read about JSON Schema here: "
	                                "http://json-schema.org/."));
	g_option_context_add_main_entries (context, entries, PACKAGE_NAME);

	if (!g_option_context_parse (context, &argc, &argv, &error)) {
		gchar *message;

		message = g_strdup_printf (_("Option parsing failed: %s"),
		                           error->message);
		g_printerr ("%s: %s\n", argv[0], message);
		g_free (message);

		g_clear_error (&error);

		retval = EXIT_INVALID_OPTIONS;
		goto done;
	}

	/* Load the schemas. */
	schemas = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);

	for (i = 0;
	     option_schema_filenames != NULL && option_schema_filenames[i] != NULL;
	     i++) {
		WblSchema *schema = NULL;  /* owned */

		schema = wbl_schema_new ();
		wbl_schema_load_from_file (schema, option_schema_filenames[i],
		                           &error);

		/* Print error or other messages from validation. */
		wbl_print_validate_messages (schema,
		                             TRUE  /* use colour */);

		if (error != NULL) {
			if (!option_quiet) {
				gchar *message;

				message = g_strdup_printf (_("Invalid JSON schema ‘%s’: %s"),
				                           option_schema_filenames[i],
				                           error->message);
				g_printerr ("%s: %s\n", argv[0], message);
				g_free (message);
			}

			if (retval == EXIT_SUCCESS) {
				retval = EXIT_INVALID_SCHEMA;
			}
			g_clear_error (&error);

			if (!option_ignore_errors) {
				g_object_unref (schema);
				goto done;
			} else {
				g_object_unref (schema);
				continue;
			}
		}

		g_object_set_data (G_OBJECT (schema),
		                   "filename", option_schema_filenames[i]);
		g_ptr_array_add (schemas, schema);  /* transfer */
	}

	/* Choose which meta-schema to use. */
	if (option_no_hyper) {
		meta_schema_type = WBL_META_SCHEMA_META_SCHEMA;
		meta_schema_name = "meta-schema";
	} else {
		meta_schema_type = WBL_META_SCHEMA_HYPER_META_SCHEMA;
		meta_schema_name = "hyper-meta-schema";
	}

	meta_schema = wbl_meta_schema_load_schema (meta_schema_type, &error);
	g_assert_no_error (error);

	/* Validate each of the JSON schemas against the meta-schema. */
	for (i = 0; i < schemas->len; i++) {
		WblSchema *schema;  /* unowned */
		const gchar *schema_filename;
		WblSchemaNode *schema_root;  /* unowned */
		JsonNode *schema_root_node = NULL;  /* owned */
		JsonObject *schema_root_object;  /* unowned */

		schema = schemas->pdata[i];
		schema_filename = g_object_get_data (G_OBJECT (schema),
		                                     "filename");

		if (!option_quiet) {
			gchar *message;

			message = g_strdup_printf (_("Validating ‘%s’ against %s…"),
			                           schema_filename,
			                           meta_schema_name);
			g_print ("%s ", message);
			g_free (message);
		}

		/* Try applying the meta-schema to the schema. */
		schema_root = wbl_schema_get_root (schema);
		schema_root_object = wbl_schema_node_get_root (schema_root);

		schema_root_node = json_node_alloc ();
		json_node_init_object (schema_root_node, schema_root_object);
		wbl_schema_apply (meta_schema, schema_root_node, &error);
		json_node_free (schema_root_node);

		if (!option_quiet) {
			g_print ("%s",
			         (error == NULL) ? _("OK") : _("FAIL"));
			g_print ("\n");
		}

		if (error != NULL) {
			if (!option_quiet) {
				gchar *message;

				message = g_strdup_printf (_("Validation error for ‘%s’ against %s: %s"),
				                           schema_filename,
				                           meta_schema_name,
				                           error->message);
				g_printerr ("%s: %s\n", argv[0], message);
				g_free (message);
			}

			if (retval == EXIT_SUCCESS) {
				retval = EXIT_SCHEMA_VALIDATION_FAILED;
			}
			g_clear_error (&error);

			if (!option_ignore_errors) {
				goto done;
			}
		}
	}

done:
	if (context != NULL) {
		g_option_context_free (context);
	}
	if (schemas != NULL) {
		g_ptr_array_unref (schemas);
	}
	g_clear_object (&meta_schema);

	return retval;
}
Beispiel #19
0
void hw_init(void)
{
    g_thread_init(NULL);
    g_type_init();
}
Beispiel #20
0
GtkWidget* cw_window_new()
{
	g_type_init();
	return g_object_new(cw_window_get_type(), NULL);
}
Beispiel #21
0
int
luaopen_lgi_corelgilua51 (lua_State* L)
{
  LgiStateMutex *mutex;

  /* Try to make itself resident.  This is needed because this dynamic
     module is 'statically' linked with glib/gobject, and these
     libraries are not designed to be unloaded.  Once they are
     unloaded, they cannot be safely loaded again into the same
     process.  To avoid problems when repeately opening and closing
     lua_States and loading lgi into them, we try to make the whole
     'core' module resident. */
  set_resident (L);

  /* Early GLib initializations. Make sure that following fundamental
     G_TYPEs are already initialized. */
  g_type_init ();
  volatile GType unused;
  unused = G_TYPE_DATE;
  unused = G_TYPE_REGEX;
  unused = G_TYPE_DATE_TIME;
  unused = G_TYPE_VARIANT_TYPE;
  unused = G_TYPE_STRV;
  unused = unused;

  /* Register 'guard' metatable. */
  luaL_newmetatable (L, UD_GUARD);
  lua_pushcfunction (L, guard_gc);
  lua_setfield (L, -2, "__gc");
  lua_pop (L, 1);

  /* Register 'module' metatable. */
  luaL_newmetatable (L, UD_MODULE);
  luaL_register (L, NULL, module_reg);
  lua_pop (L, 1);

  /* Register 'call-mutex' metatable. */
  lua_pushlightuserdata (L, &call_mutex_mt);
  lua_newtable (L);
  lua_pushcfunction (L, call_mutex_gc);
  lua_setfield (L, -2, "__gc");
  lua_rawset (L, LUA_REGISTRYINDEX);

  /* Create call mutex guard, keep it locked initially (it is unlocked
     only when we are calling out to GObject-C code) and store it into
     the registry. */
  lua_pushlightuserdata (L, &call_mutex);
  mutex = lua_newuserdata (L, sizeof (*mutex));
  mutex->mutex = &mutex->state_mutex;
  g_static_rec_mutex_init (&mutex->state_mutex);
  g_static_rec_mutex_lock (&mutex->state_mutex);
  lua_pushlightuserdata (L, &call_mutex_mt);
  lua_rawget (L, LUA_REGISTRYINDEX);
  lua_setmetatable (L, -2);
  lua_rawset (L, LUA_REGISTRYINDEX);

  /* Register 'lgi.core' interface. */
  lua_newtable (L);
  luaL_register (L, NULL, lgi_reg);

  /* Create repo and index table. */
  create_repo_table (L, "index", &repo_index);
  create_repo_table (L, "repo", &repo);

  /* Initialize modules. */
  lgi_buffer_init (L);
  lgi_gi_init (L);
  lgi_marshal_init (L);
  lgi_record_init (L);
  lgi_object_init (L);
  lgi_callable_init (L);

  /* Return registration table. */
  return 1;
}
Beispiel #22
0
int
main (int argc,
      char *argv[])
{
  gint ret = 1;
  CockpitWebServer *server = NULL;
  GOptionContext *context;
  CockpitHandlerData data;
  GTlsCertificate *certificate = NULL;
  GError *local_error = NULL;
  GError **error = &local_error;
  gchar **roots = NULL;
  gchar *cert_path = NULL;
  GMainLoop *loop = NULL;

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

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

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

  g_type_init ();

  ssh_threads_set_callbacks (ssh_threads_get_pthread());
  ssh_init ();

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

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

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

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

  cockpit_set_journal_logging (NULL, !isatty (2));

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

  loop = g_main_loop_new (NULL, FALSE);

  data.os_release = cockpit_system_load_os_release ();
  data.auth = cockpit_auth_new (opt_local_ssh);
  roots = calculate_static_roots (data.os_release);
  data.static_roots = (const gchar **)roots;

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

  if (cockpit_web_server_get_socket_activated (server))
    g_signal_connect_swapped (data.auth, "idling", G_CALLBACK (g_main_loop_quit), loop);

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

  g_signal_connect (server,
                    "handle-resource::/login",
                    G_CALLBACK (cockpit_handler_login),
                    &data);

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

  g_signal_connect (server, "handle-resource::/",
                    G_CALLBACK (cockpit_handler_resource), &data);
  g_signal_connect (server, "handle-resource::/cockpit/",
                    G_CALLBACK (cockpit_handler_resource), &data);

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

  g_main_loop_run (loop);

  ret = 0;

out:
  if (loop)
    g_main_loop_unref (loop);
  if (local_error)
    {
      g_printerr ("cockpit-ws: %s\n", local_error->message);
      g_error_free (local_error);
    }
  g_clear_object (&server);
  g_clear_object (&data.auth);
  if (data.os_release)
    g_hash_table_unref (data.os_release);
  g_clear_object (&certificate);
  g_free (cert_path);
  g_strfreev (roots);
  cockpit_conf_cleanup ();
  return ret;
}
Beispiel #23
0
int gt_backend_init(const char *program_name, enum gt_option_flags flags)
{
	enum gt_backend_type backend_type;
	GError *err = NULL;

	if (strcmp(program_name, "gt") == 0)
		backend_type = GT_BACKEND_LIBUSBG;
	else if (strcmp(program_name, "gadgetctl") == 0)
		backend_type = GT_BACKEND_GADGETD;
	else if (strcmp(program_name, "gt-parse-test") == 0)
		backend_type = GT_BACKEND_NOT_IMPLEMENTED;
	else
		backend_type = GT_BACKEND_AUTO;

	if (backend_type == GT_BACKEND_NOT_IMPLEMENTED) {
		backend_ctx.backend = &gt_backend_not_implemented;
		return 0;
	}

	if (backend_type == GT_BACKEND_GADGETD || backend_type == GT_BACKEND_AUTO) {
		GDBusConnection *conn;

		backend_ctx.backend = &gt_backend_gadgetd;

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

		conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
		if (err) {
			fprintf(stderr, "Unable to connect to d-bus: %s\n", err->message);
			goto out_gadgetd;
		}

		g_dbus_connection_call_sync(conn,
					    "org.usb.gadgetd",
					    "/",
					    "org.freedesktop.DBus.Peer",
					    "Ping",
					    NULL,
					    NULL,
					    G_DBUS_CALL_FLAGS_NONE,
					    -1,
					    NULL,
					    &err);
		if (err) {
			/* We omit showing glib-provided error message here
			 * as it's not really that useful for end-users.
			 *
			 * This message could be probably shown in verbose
			 * mode (which we don't have yet).
			 */
			fprintf(stderr, "Unable to initialize gadgetd backend_type\n");
			goto out_gadgetd;
		}

		backend_ctx.backend_type = GT_BACKEND_GADGETD;
		backend_ctx.gadgetd_conn = conn;
		return 0;

	}

out_gadgetd:
	if (err && backend_type == GT_BACKEND_GADGETD)
		return -1;

	if (backend_type == GT_BACKEND_LIBUSBG || backend_type == GT_BACKEND_AUTO) {
		usbg_state *s = NULL;
		int r;

		backend_ctx.backend = &gt_backend_libusbg;

		r = usbg_init("/sys/kernel/config", &s);
		if (r != USBG_SUCCESS) {
			fprintf(stderr, "Unable to initialize libusbg backend_type: %s\n", usbg_strerror(r));
			goto out_libusbg;
		}

		backend_ctx.backend_type = GT_BACKEND_LIBUSBG;
		backend_ctx.libusbg_state = s;
		return 0;
	}

out_libusbg:
	return -1;
}
Beispiel #24
0
Datei: svg.c Projekt: clones/kaa
void init_svg()
{
    PyObject *m;
    g_type_init();
    m =  Py_InitModule("_svg", svg_methods);
}
Beispiel #25
0
int
main (int argc, char **argv)
{
        SoupSession *session;
        GError *error = NULL;
        const char *path, *dbpath = NULL;
        guint i;
        GOptionContext *context;
        const GOptionEntry entries[] = {
                { "dbpath", 0, 0, G_OPTION_ARG_STRING, &dbpath, "The directory containing the databases", NULL },
                { NULL }
        };

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

        context = g_option_context_new ("- updates the city and country databases from Maxmind.");
        g_option_context_add_main_entries (context, entries, NULL);
        if (g_option_context_parse (context, &argc, &argv, &error) == FALSE) {
                g_print ("Option parsing failed: %s\n", error->message);
                return 1;
        }

        path = g_getenv ("GEOIP_DATABASE_PATH");
        if (!path) {
                if (dbpath)
                        path = dbpath;
                else
                        path = GEOIP_DATABASE_PATH;
        }

        session = soup_session_new ();

        for (i = 0; i < G_N_ELEMENTS (db_info_map); i++) {
                SoupMessage *msg = NULL;
                const char*db_uri;
                GFile *db_local;
                char *db_path;
                char *db_decompressed_path;
                gboolean needs_update;
                guint status_code;

                g_print ("Updating %s database\n", db_info_map[i].db_name);
                db_uri = db_info_map[i].uri;

                db_path = g_build_filename (path, db_info_map[i].db_gz_name, NULL);
                db_local = g_file_new_for_path (db_path);
                g_free (db_path);

                if (local_db_needs_update (session, db_uri, db_local, &needs_update, &error) == FALSE) {
                        g_print ("Could not update the database: %s\n", error->message);
                        g_error_free (error);
                        goto end_loop;
                }
                if (!needs_update) {
                        g_print ("Database '%s' up to date\n", db_info_map[i].db_name);
                        goto end_loop;
                }

                msg = soup_message_new ("GET", db_uri);
                status_code = soup_session_send_message (session, msg);
                if (status_code != SOUP_STATUS_OK) {
                        g_set_error (&error,
                                     SOUP_HTTP_ERROR,
                                     status_code,
                                     msg->reason_phrase);
                        g_print ("Could not download the database: %s\n", msg->reason_phrase);
                        goto end_loop;
                }

                if (g_file_replace_contents (db_local,
                                             msg->response_body->data,
                                             msg->response_body->length,
                                             NULL,
                                             FALSE,
                                             0,
                                             NULL,
                                             NULL,
                                             &error) == FALSE) {
                        g_print ("Could not download the database: %s\n", error->message);
                        goto end_loop;
                }

                db_decompressed_path = g_build_filename (path, db_info_map[i].db_name, NULL);
                decompress_db (db_local, db_decompressed_path);
                g_free (db_decompressed_path);

end_loop:
                g_object_unref (db_local);
                g_clear_object (&msg);
                error = NULL;
        }

        g_object_unref (session);

        return 0;
}
Beispiel #26
0
int
main (int argc,
      char *argv[])
{
    GTestDBus *bus;
    GError *error = NULL;
    GOptionContext *context;
    guint sig_term;
    guint sig_int;
    int i;
    gchar *guid = NULL;
    GDBusServer *direct_dbus_server = NULL;

    GOptionEntry entries[] = {
        { NULL }
    };

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

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

    setup_path (argv[0]);

    g_type_init ();

    g_log_set_always_fatal (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR);

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

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

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

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

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

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

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

    loop = g_main_loop_new (NULL, FALSE);

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

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

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

    g_main_loop_run (loop);

    g_source_remove (sig_term);
    g_source_remove (sig_int);

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

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

    return exit_code;
}
Beispiel #27
0
int main(int argc, char *argv[])
{
#ifdef Q_WS_MAC
    if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) {
        // fix Mac OS X 10.9 (mavericks) font issue
        // https://bugreports.qt-project.org/browse/QTBUG-32789
        QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
    }
#endif

#if !GLIB_CHECK_VERSION(2, 35, 0)
    g_type_init();
#endif
#if !GLIB_CHECK_VERSION(2, 31, 0)
    g_thread_init(NULL);
#endif

#ifdef Q_WS_MAC
    Application app(argc, argv);
#else
    QApplication app(argc, argv);
#endif

    QDir::setCurrent(QApplication::applicationDirPath());

    // initialize i18n
    QTranslator qtTranslator;
#if defined(Q_WS_WIN)
    qtTranslator.load("qt_" + QLocale::system().name());
#else
    qtTranslator.load("qt_" + QLocale::system().name(),
                      QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
    app.installTranslator(&qtTranslator);

    QTranslator myappTranslator;
#if QT_VERSION >= 0x040800 && not defined(Q_WS_MAC)
    myappTranslator.load(QLocale::system(), // locale
                         "",                // file name
                         "seafile_",        // prefix
                         ":/i18n/",         // folder
                         ".qm");            // suffix
#else
    myappTranslator.load(QString(":/i18n/seafile_%1.qm").arg(QLocale::system().name()));
#endif

    app.installTranslator(&myappTranslator);

    static const char *short_options = "KXc:d:";
    static const struct option long_options[] = {
        { "config-dir", required_argument, NULL, 'c' },
        { "data-dir", required_argument, NULL, 'd' },
        { "stop", no_argument, NULL, 'K' },
        { "remove-user-data", no_argument, NULL, 'X' },
        { "stdout", no_argument, NULL, 'l' },
        { NULL, 0, NULL, 0, },
    };

    char c;
    while ((c = getopt_long (argc, argv, short_options,
                             long_options, NULL)) != EOF) {
        switch (c) {
        case 'c':
            g_setenv ("CCNET_CONF_DIR", optarg, 1);
            break;
        case 'd':
            g_setenv ("SEAFILE_DATA_DIR", optarg, 1);
            break;
        case 'l':
            g_setenv ("LOG_STDOUT", "", 1);
            break;
        case 'K':
            do_stop();
            exit(0);
        case 'X':
            do_remove_user_data();
            exit(0);
        default:
            exit(1);
        }
    }

    if (count_process(APPNAME) > 1) {
        QMessageBox::warning(NULL, getBrand(),
                             QObject::tr("%1 is already running").arg(getBrand()),
                             QMessageBox::Ok);
        return -1;
    }

    app.setQuitOnLastWindowClosed(false);

    // see QSettings documentation
    QCoreApplication::setOrganizationName(getBrand());
    QCoreApplication::setOrganizationDomain("seafile.com");
    QCoreApplication::setApplicationName(QString("%1 Client").arg(getBrand()));

    awesome = new QtAwesome(qApp);
    awesome->initFontAwesome();

    seafApplet = new SeafileApplet;
    seafApplet->start();

    return app.exec();
}
Beispiel #28
0
int
main(int argc, char **argv)
{
  static const char opt_s[] = "hVdl:L:X:w:t:";

  static const struct option opt_l[] =
  {
    {"help",          0, 0, 'h'},
    {"usage",         0, 0, 'h'},
    {"version",       0, 0, 'V'},
    {"daemon",        0, 0, 'd'},
    {"log-level",     1, 0, 'L'},
    {"log-target",    1, 0, 'l'},
    {"limbo-control", 1, 0, 'w'},
    {"limbo-timeout", 1, 0, 't'},
    {0,               0, 0,  0 }
  };

  int log_driver = LOG_TO_SYSLOG;
  int log_level  = LOG_WARNING;
  int opt_daemon = 0;
  int opt;

  progname = *argv = basename(*argv);

  if( access("/root/alarmd.verbose", F_OK) == 0 )
  {
    //log_driver = LOG_TO_STDERR;
    log_level  = LOG_DEBUG;
  }

  // libconic uses gobjects
  g_type_init();

  while( (opt = getopt_long(argc, argv, opt_s, opt_l, 0)) != -1 )
  {
    switch( opt )
    {
    case 'h':
      show_usage();
      exit(0);
    case 'V':
      printf("%s\n", VERS);
      break;

    case 'L':
      log_level = log_parse_level(optarg);
      break;

    case 'l':
      log_driver = log_parse_driver(optarg);
      break;

    case 'd':
      opt_daemon = 1;
      break;
    case 't':
      server_limbo_set_timeout(strtol(optarg,0,0));
      break;

    case 'w':
      if( cmp_flag(optarg, "disabled") )
      {
        server_limbo_set_control(DESKTOP_WAIT_DISABLED);
      }
      else if( cmp_flag(optarg, "home") )
      {
        server_limbo_set_control(DESKTOP_WAIT_HOME);
      }
      else if( cmp_flag(optarg, "hildon") )
      {
        server_limbo_set_control(DESKTOP_WAIT_HOME);
      }
      else if( cmp_flag(optarg, "startup") )
      {
        server_limbo_set_control(DESKTOP_WAIT_HOME);
      }
      else
      {
        server_limbo_set_control(strtol(optarg,0,0));
      }
      break;

    case 'X':
      if( !strcmp(optarg, "cud") )
      {
        exit( clear_user_data() == -1 ? EXIT_FAILURE : EXIT_SUCCESS);
      }
      else if( !strcmp(optarg, "rfs") )
      {
        exit(restore_factory_settings() == -1 ? EXIT_FAILURE : EXIT_SUCCESS);
      }
      else
      {
        fprintf(stderr, "Unknwon option: -X%s\n", optarg);
      }
      exit(EXIT_FAILURE);
      break;

    case '?':
      fprintf(stderr, "%s: (use -h for usage)\n", *argv);
      exit(1);

    default:
      abort ();
    }
  }

  if( opt_daemon && daemon(0,0) )
  {
    perror("daemon"); exit(1);
  }

  log_set_level(log_level);
  log_open("alarmd", log_driver, 1);

  log_info("-- startup --\n");
  int xc = mainloop_run();
  log_info("-- exit %d --\n", xc);
  log_close();
  return xc;
}
Beispiel #29
0
int
main (int argc, char *argv[])
{
	GtkWidget *dialog;
	char *ret;
	const char *message;
	GOptionContext *ctx;

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

	/* Option parsing */
	ctx = g_option_context_new ("- New mdm login");
	g_option_context_add_main_entries (ctx, options, _("main options"));
	g_option_context_parse (ctx, &argc, &argv, NULL);
	g_option_context_free (ctx);

	mdm_log_init ();
	mdm_log_set_debug (debug_in);

	if (send_command != NULL) {
		if ( ! mdmcomm_is_daemon_running (FALSE)) {
			mdm_common_error (_("Error: MDM (MDM Display Manager) is not running."));
			mdm_common_error (_("You might be using a different display manager."));
			return 1;
		}
	} else {
		/*
		 * The --command argument does not display anything, so avoid
		 * running gtk_init until it finishes.  Sometimes the
		 * --command argument is used when there is no display so it
		 * will fail and cause the program to exit, complaining about
		 * "no display".
		 */
		gtk_init (&argc, &argv);

		if ( ! mdmcomm_is_daemon_running (TRUE)) {
			return 1;
		}
	}
	
	mdmcomm_open_connection_to_daemon ();

	/* Process --command option */

	g_type_init ();

	if (send_command != NULL) {

		/* gdk_init is needed for cookie code to get display */
		gdk_init (&argc, &argv);
		if (authenticate)
			auth_cookie = mdmcomm_get_auth_cookie ();

		/*
		 * If asking for a translatable config value, then try to get
		 * the translated value first.  If this fails, then go ahead
		 * and call the normal sockets command.
		 */
		if (strncmp (send_command, MDM_SUP_GET_CONFIG " ",
		    strlen (MDM_SUP_GET_CONFIG " ")) == 0) {
			gchar *value = NULL;
			const char *key = &send_command[strlen (MDM_SUP_GET_CONFIG " ")];

			if (is_key (MDM_KEY_WELCOME, key)) {
				value = mdm_config_get_translated_string ((gchar *)key);
				if (value != NULL) {
					ret = g_strdup_printf ("OK %s", value);
				}
			}

			/*
			 * If the above didn't return a value, then must be a
			 * different key, so call the daemon.
			 */
			if (value == NULL)
				ret = mdmcomm_send_cmd_to_daemon_with_args (send_command, auth_cookie, 5);
		} else {
			ret = mdmcomm_send_cmd_to_daemon_with_args (send_command, auth_cookie, 5);
		}

		/* At this point we are done using the socket, so close it */
		mdmcomm_close_connection_to_daemon ();

		if (ret != NULL) {
			g_print ("%s\n", ret);
			return 0;
		} else {
			dialog = hig_dialog_new (NULL /* parent */,
						 GTK_DIALOG_MODAL /* flags */,
						 GTK_MESSAGE_ERROR,
						 GTK_BUTTONS_OK,
						 _("Cannot communicate with MDM "
						   "(The MDM Display Manager)"),
						 _("Perhaps you have an old version "
						   "of MDM running."));
			gtk_widget_show_all (dialog);
			gtk_dialog_run (GTK_DIALOG (dialog));
			gtk_widget_destroy (dialog);
			return 1;
		}
	}

	/*
	 * Always attempt to get cookie and authenticate.  On remote
	 * servers
	 */
	auth_cookie = mdmcomm_get_auth_cookie ();
	
	/* check for other displays/logged in users */
	check_for_users ();

	if (auth_cookie == NULL) {

		/* At this point we are done using the socket, so close it */
		mdmcomm_close_connection_to_daemon ();

		dialog = hig_dialog_new (NULL /* parent */,
					 GTK_DIALOG_MODAL /* flags */,
					 GTK_MESSAGE_ERROR,
					 GTK_BUTTONS_OK,
					 _("You do not seem to be logged in on the "
					   "console"),
					 _("Starting a new login only "
					   "works correctly on the console."));
		gtk_dialog_set_has_separator (GTK_DIALOG (dialog),
					      FALSE);
		gtk_widget_show_all (dialog);
		gtk_dialog_run (GTK_DIALOG (dialog));
		gtk_widget_destroy (dialog);
		return 1;
	}
	
	ret = mdmcomm_send_cmd_to_daemon_with_args (MDM_SUP_FLEXI_XSERVER, auth_cookie, 5);

	g_free (auth_cookie);
	g_strfreev (args_remaining);

	/* At this point we are done using the socket, so close it */
	mdmcomm_close_connection_to_daemon ();

	if (ret != NULL &&
	    strncmp (ret, "OK ", 3) == 0) {

		/* if we switched to a different screen as a result of this,
		 * lock the current screen */
		if ( ! no_lock ) {
			maybe_lock_screen ();
		}

		/* all fine and dandy */
		g_free (ret);
		return 0;
	}

	message = mdmcomm_get_error_message (ret);

	dialog = hig_dialog_new (NULL /* parent */,
				 GTK_DIALOG_MODAL /* flags */,
				 GTK_MESSAGE_ERROR,
				 GTK_BUTTONS_OK,
				 _("Cannot start new display"),
				 message);

	gtk_widget_show_all (dialog);
	gtk_dialog_run (GTK_DIALOG (dialog));
	gtk_widget_destroy (dialog);
	g_free (ret);

	return 1;
}
Beispiel #30
0
/**
 * main:
 **/
int
main (int argc, char *argv[])
{
	gboolean ret = TRUE;
	gboolean disable_timer = FALSE;
	gboolean version = FALSE;
	gboolean timed_exit = FALSE;
	gboolean immediate_exit = FALSE;
	gboolean keep_environment = FALSE;
	gchar *backend_name = NULL;
	gchar *conf_filename = NULL;
	PkEngine *engine = NULL;
	GKeyFile *conf = NULL;
	GError *error = NULL;
	GOptionContext *context;
	guint timer_id = 0;

	const GOptionEntry options[] = {
		{ "backend", '\0', 0, G_OPTION_ARG_STRING, &backend_name,
		  /* TRANSLATORS: a backend is the system package tool, e.g. yum, apt */
		  _("Packaging backend to use, e.g. dummy"), NULL },
		{ "disable-timer", '\0', 0, G_OPTION_ARG_NONE, &disable_timer,
		  /* TRANSLATORS: if we should not monitor how long we are inactive for */
		  _("Disable the idle timer"), NULL },
		{ "version", '\0', 0, G_OPTION_ARG_NONE, &version,
		  /* TRANSLATORS: show version */
		  _("Show version and exit"), NULL },
		{ "timed-exit", '\0', 0, G_OPTION_ARG_NONE, &timed_exit,
		  /* TRANSLATORS: exit after we've started up, used for user profiling */
		  _("Exit after a small delay"), NULL },
		{ "immediate-exit", '\0', 0, G_OPTION_ARG_NONE, &immediate_exit,
		  /* TRANSLATORS: exit straight away, used for automatic profiling */
		  _("Exit after the engine has loaded"), NULL },
		{ "keep-environment", '\0', 0, G_OPTION_ARG_NONE, &keep_environment,
		  /* TRANSLATORS: don't unset environment variables, used for debugging */
		  _("Don't clear environment on startup"), NULL },
		{ NULL }
	};

	setlocale (LC_ALL, "");
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
	openlog ("PackageKit", LOG_NDELAY, LOG_USER);

#if (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 35)
	g_type_init ();
#endif

	/* TRANSLATORS: describing the service that is running */
	context = g_option_context_new (_("PackageKit service"));
	g_option_context_add_main_entries (context, options, NULL);
	g_option_context_add_group (context, pk_debug_get_option_group ());
	g_option_context_parse (context, &argc, &argv, NULL);
	g_option_context_free (context);

	if (version) {
		g_print ("Version %s\n", VERSION);
		goto exit_program;
	}

	/* we don't actually need to do this, except it rules out the
	 * 'it works from the command line but not service activation' bugs */
#ifdef HAVE_CLEARENV
	if (!keep_environment)
		clearenv ();
#endif

	/* get values from the config file */
	conf = g_key_file_new ();
	conf_filename = pk_main_get_config_filename ();
	ret = g_key_file_load_from_file (conf, conf_filename,
					 G_KEY_FILE_NONE, &error);
	if (!ret) {
		g_print ("Failed to load config file: %s", error->message);
		g_error_free (error);
		goto out;
	}
	g_key_file_set_boolean (conf, "Daemon", "KeepEnvironment", keep_environment);

	/* log the startup */
	syslog (LOG_DAEMON | LOG_DEBUG, "daemon start");

	/* after how long do we timeout? */
	exit_idle_time = g_key_file_get_integer (conf, "Daemon", "ShutdownTimeout", NULL);
	g_debug ("daemon shutdown set to %i seconds", exit_idle_time);

	/* override the backend name */
	if (backend_name != NULL) {
		g_key_file_set_string (conf,
				       "Daemon",
				       "DefaultBackend",
				       backend_name);
	}

	/* resolve 'auto' to an actual name */
	backend_name = g_key_file_get_string (conf, "Daemon", "DefaultBackend", NULL);
	if (g_strcmp0 (backend_name, "auto") == 0) {
		ret  = pk_main_set_auto_backend (conf, &error);
		if (!ret) {
			g_print ("Failed to resolve auto: %s",
				 error->message);
			g_error_free (error);
			goto out;
		}
	}

	loop = g_main_loop_new (NULL, FALSE);

	/* create a new engine object */
	engine = pk_engine_new (conf);
	g_signal_connect (engine, "quit",
			  G_CALLBACK (pk_main_quit_cb), loop);

	/* do stuff on ctrl-c */
	g_unix_signal_add_full (G_PRIORITY_DEFAULT,
				SIGINT,
				pk_main_sigint_cb,
				loop,
				NULL);

	/* load the backend */
	ret = pk_engine_load_backend (engine, &error);
	if (!ret) {
		/* TRANSLATORS: cannot load the backend the user specified */
		g_print ("Failed to load the backend: %s",
			 error->message);
		g_error_free (error);
		goto out;
	}

	/* Only timeout and close the mainloop if we have specified it
	 * on the command line */
	if (timed_exit)
		g_timeout_add_seconds (20, (GSourceFunc) timed_exit_cb, loop);

	/* only poll when we are alive */
	if (exit_idle_time != 0 && !disable_timer) {
		timer_id = g_timeout_add_seconds (5, (GSourceFunc) pk_main_timeout_check_cb, engine);
		g_source_set_name_by_id (timer_id, "[PkMain] main poll");
	}

	/* immediatly exit */
	if (immediate_exit)
		g_timeout_add (50, (GSourceFunc) timed_exit_cb, loop);

	/* run until quit */
	g_main_loop_run (loop);
out:
	/* log the shutdown */
	syslog (LOG_DAEMON | LOG_DEBUG, "daemon quit");
	closelog ();

	if (timer_id > 0)
		g_source_remove (timer_id);

	if (loop != NULL)
		g_main_loop_unref (loop);
	g_key_file_unref (conf);
	if (engine != NULL)
		g_object_unref (engine);
	g_free (backend_name);
	g_free (conf_filename);

exit_program:
	return 0;
}