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;
}
Example #2
0
int bt_obex(int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;

	/* Query current locale */
	setlocale(LC_CTYPE, "");

	g_type_init();
	dbus_init();

	context = g_option_context_new(" - a bluetooth OBEX client/server");
	g_option_context_add_main_entries(context, entries, NULL);
	g_option_context_set_summary(context, "Version "PACKAGE_VERSION);
	g_option_context_set_description(context,
			"Server Options:\n"
			"  -s, --server [<path>]\n"
			"  Register self at OBEX server and use given `path` as OPP save directory\n"
			"  If `path` does not specified - use current directory\n\n"
			"OPP Options:\n"
			"  -p, --opp <name|mac> <file>\n"
			"  Send `file` to remote device using Object Push Profile\n\n"
			//"Report bugs to <"PACKAGE_BUGREPORT">."
			"Project home page <"PACKAGE_URL">."
			);

	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("%s: %s\n", g_get_prgname(), error->message);
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	} else if (!server_arg && !opp_arg && (!ftp_arg || strlen(ftp_arg) == 0)) {
		g_print("%s", g_option_context_get_help(context, FALSE, NULL));
		exit(EXIT_FAILURE);
	} else if (server_arg && argc != 1 && (argc != 2 || strlen(argv[1]) == 0)) {
		g_print("%s: Invalid arguments for --server\n", g_get_prgname());
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	} else if (opp_arg && (argc != 3 || strlen(argv[1]) == 0 || strlen(argv[2]) == 0)) {
		g_print("%s: Invalid arguments for --opp\n", g_get_prgname());
		g_print("Try `%s --help` for more information.\n", g_get_prgname());
		exit(EXIT_FAILURE);
	}

	g_option_context_free(context);

	if (!dbus_system_connect(&error)) {
		g_printerr("Couldn't connect to DBus system bus: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	if (!dbus_session_connect(&error)) {
		g_printerr("Couldn't connect to DBus session bus: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	/* Check, that bluetooth daemon is running */
	if (!intf_supported(BLUEZ_DBUS_NAME, MANAGER_DBUS_PATH, MANAGER_DBUS_INTERFACE)) {
		g_printerr("%s: bluez service is not found\n", g_get_prgname());
		g_printerr("Did you forget to run bluetoothd?\n");
		exit(EXIT_FAILURE);
	}

	/* Check, that obexd daemon is running */
	if (!intf_supported(OBEXS_DBUS_NAME, OBEXMANAGER_DBUS_PATH, OBEXMANAGER_DBUS_INTERFACE)) {
		g_printerr("%s: obex service is not found\n", g_get_prgname());
		g_printerr("Did you forget to run obexd?\n");
		exit(EXIT_FAILURE);
	}

	if (server_arg) {
		if (argc == 2) {
			server_path_arg = argv[1];
		}

		/* Check that `path` is valid */
		gchar *root_folder = server_path_arg == NULL ? g_get_current_dir() : g_strdup(server_path_arg);
		if (!is_dir(root_folder, &error)) {
			exit_if_error(error);
		}

		server_transfers = g_hash_table_new(g_str_hash, g_str_equal);

		OBEXManager *manager = g_object_new(OBEXMANAGER_TYPE, NULL);
		g_signal_connect(manager, "SessionCreated", G_CALLBACK(obexmanager_session_created), NULL);
		g_signal_connect(manager, "SessionRemoved", G_CALLBACK(obexmanager_session_removed), NULL);
		g_signal_connect(manager, "TransferStarted", G_CALLBACK(obexmanager_transfer_started), NULL);
		g_signal_connect(manager, "TransferCompleted", G_CALLBACK(obexmanager_transfer_completed), NULL);

		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, "RootFolder", root_folder, NULL);

		g_free(root_folder);

		obexmanager_register_agent(manager, OBEXAGENT_DBUS_PATH, &error);
		exit_if_error(error);

		mainloop = g_main_loop_new(NULL, FALSE);

		/* Add SIGTERM && SIGINT handlers */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sigterm_handler;
		sigaction(SIGTERM, &sa, NULL);
		sigaction(SIGINT, &sa, NULL);

		g_main_loop_run(mainloop);

		/* Waiting for connections... */

		g_main_loop_unref(mainloop);

		/* Stop active transfers */
		GHashTableIter iter;
		gpointer key, value;
		g_hash_table_iter_init(&iter, server_transfers);
		while (g_hash_table_iter_next(&iter, &key, &value)) {
			OBEXTransfer *t = OBEXTRANSFER(value);
			obextransfer_cancel(t, NULL); // skip errors
			g_object_unref(t);
			g_hash_table_iter_remove(&iter);
		}
		g_hash_table_unref(server_transfers);

		obexmanager_unregister_agent(manager, OBEXAGENT_DBUS_PATH, &error);
		g_object_unref(agent);
		g_object_unref(manager);
	} else if (opp_arg) {
		opp_device_arg = argv[1];
		opp_file_arg = argv[2];

		/* Check that `file` is valid */
		if (!is_file(opp_file_arg, &error)) {
			exit_if_error(error);
		}

		gchar * files_to_send[] = {NULL, NULL};
		files_to_send[0] = g_path_is_absolute(opp_file_arg) ? g_strdup(opp_file_arg) : get_absolute_path(opp_file_arg);

		/* Get source address (address of adapter) */
		Adapter *adapter = find_adapter(adapter_arg, &error);
		exit_if_error(error);
		gchar *src_address = g_strdup(adapter_get_address(adapter));

		/* Get destination address (address of remote device) */
		gchar *dst_address = NULL;
		if (g_regex_match_simple("^\\x{2}:\\x{2}:\\x{2}:\\x{2}:\\x{2}:\\x{2}$", opp_device_arg, 0, 0)) {
			dst_address = g_strdup(opp_device_arg);
		} else {
			Device *device = find_device(adapter, opp_device_arg, &error);
			exit_if_error(error);
			dst_address = g_strdup(device_get_address(device));
			g_object_unref(device);
		}

		g_object_unref(adapter);

		/* Build arguments */
		GHashTable *device_dict = g_hash_table_new(g_str_hash, g_str_equal);
		GValue src_v = {0};
		GValue dst_v = {0};
		g_value_init(&src_v, G_TYPE_STRING);
		g_value_init(&dst_v, G_TYPE_STRING);
		g_value_set_string(&src_v, src_address);
		g_value_set_string(&dst_v, dst_address);
		g_hash_table_insert(device_dict, "Source", &src_v);
		g_hash_table_insert(device_dict, "Destination", &dst_v);

		mainloop = g_main_loop_new(NULL, FALSE);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);

		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, NULL);
		g_signal_connect(agent, "AgentReleased", G_CALLBACK(agent_released), mainloop);

		/* Sending file(s) */
		obexclient_send_files(client, device_dict, files_to_send, OBEXAGENT_DBUS_PATH, &error);
		exit_if_error(error);

		/* Add SIGTERM && SIGINT handlers */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = sigterm_handler;
		sigaction(SIGTERM, &sa, NULL);
		sigaction(SIGINT, &sa, NULL);

		g_main_loop_run(mainloop);

		/* Sending files process here ?? */

		g_main_loop_unref(mainloop);

		g_object_unref(agent);
		g_object_unref(client);

		g_value_unset(&src_v);
		g_value_unset(&dst_v);
		g_hash_table_unref(device_dict);

		g_free(src_address);
		g_free(dst_address);
		g_free(files_to_send[0]);
		files_to_send[0] = NULL;
	} else if (ftp_arg) {
		/* Get source address (address of adapter) */
		Adapter *adapter = find_adapter(adapter_arg, &error);
		exit_if_error(error);
		gchar *src_address = g_strdup(adapter_get_address(adapter));

		/* Get destination address (address of remote device) */
		Device *device = find_device(adapter, ftp_arg, &error);
		exit_if_error(error);
		gchar *dst_address = g_strdup(device == NULL ? ftp_arg : device_get_address(device));

		g_object_unref(device);
		g_object_unref(adapter);

		/* Build arguments */
		GHashTable *device_dict = g_hash_table_new(g_str_hash, g_str_equal);
		GValue src_v = {0};
		GValue dst_v = {0};
		GValue target_v = {0};
		g_value_init(&src_v, G_TYPE_STRING);
		g_value_init(&dst_v, G_TYPE_STRING);
		g_value_init(&target_v, G_TYPE_STRING);
		g_value_set_string(&src_v, src_address);
		g_value_set_string(&dst_v, dst_address);
		g_value_set_string(&target_v, "FTP");
		g_hash_table_insert(device_dict, "Source", &src_v);
		g_hash_table_insert(device_dict, "Destination", &dst_v);
		g_hash_table_insert(device_dict, "Target", &target_v);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);
		OBEXAgent *agent = g_object_new(OBEXAGENT_TYPE, NULL);

		/* Create FTP session */
		gchar *session_path = obexclient_create_session(client, device_dict, &error);
		exit_if_error(error);

		OBEXClientFileTransfer *ftp_session = g_object_new(OBEXCLIENT_FILE_TRANSFER_TYPE, "DBusObjectPath", session_path, NULL);
		g_free(session_path);

		g_print("FTP session opened\n");

		while (TRUE) {
			gchar *cmd;
			/*
			cmd = readline("> ");
			if (cmd == NULL) {
				continue;
			} else {
				add_history(cmd);
			}
			*/
			gint f_argc;
			gchar **f_argv;
			/* Parsing command line */
			if (!g_shell_parse_argv(cmd, &f_argc, &f_argv, &error)) {
				g_print("%s\n", error->message);
				g_error_free(error);
				error = NULL;

				g_free(cmd);
				continue;
			}

			/* Execute commands */
			if (g_strcmp0(f_argv[0], "cd") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_change_folder(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "mkdir") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_create_folder(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "ls") == 0) {
				if (f_argc != 1) {
					g_print("invalid arguments\n");
				} else {
					GPtrArray *folders = obexclient_file_transfer_list_folder(ftp_session, &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						for (int i = 0; i < folders->len; i++) {
							GHashTable *el = g_ptr_array_index(folders, i);
							g_print(
									"%s\t%llu\t%s\n",
									g_value_get_string(g_hash_table_lookup(el, "Type")),
									G_VALUE_HOLDS_UINT64(g_hash_table_lookup(el, "Size")) ?
									g_value_get_uint64(g_hash_table_lookup(el, "Size")) :
									0,
									g_value_get_string(g_hash_table_lookup(el, "Name"))
									);
						}
					}

					if (folders) g_ptr_array_unref(folders);

					/*obexclient_remove_session(client, obexclient_file_transfer_get_dbus_object_path(ftp_session), &error);
					exit_if_error(error);
					g_object_unref(ftp_session);
					session_path = obexclient_create_session(client, device_dict, &error);
					exit_if_error(error);
					ftp_session = g_object_new(OBEXCLIENT_FILE_TRANSFER_TYPE, "DBusObjectPath", session_path, NULL);
					g_free(session_path);*/

				}
			} else if (g_strcmp0(f_argv[0], "get") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					gchar *abs_dst_path = get_absolute_path(f_argv[2]);
					gchar *dir = g_path_get_dirname(abs_dst_path);
					if (!is_dir(dir, &error)) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						obexclient_file_transfer_get_file(ftp_session, abs_dst_path, f_argv[1], &error);
						if (error) {
							g_print("%s\n", error->message);
							g_error_free(error);
							error = NULL;
						}
					}
					g_free(dir);
					g_free(abs_dst_path);
				}
			} else if (g_strcmp0(f_argv[0], "put") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					gchar *abs_src_path = get_absolute_path(f_argv[1]);
					if (!is_file(abs_src_path, &error)) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					} else {
						obexclient_file_transfer_put_file(ftp_session, abs_src_path, f_argv[2], &error);
						if (error) {
							g_print("%s\n", error->message);
							g_error_free(error);
							error = NULL;
						}
					}
					g_free(abs_src_path);
				}
			} else if (g_strcmp0(f_argv[0], "cp") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_copy_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "mv") == 0) {
				if (f_argc != 3 || strlen(f_argv[1]) == 0 || strlen(f_argv[2]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_move_file(ftp_session, f_argv[1], f_argv[2], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "rm") == 0) {
				if (f_argc != 2 || strlen(f_argv[1]) == 0) {
					g_print("invalid arguments\n");
				} else {
					obexclient_file_transfer_delete(ftp_session, f_argv[1], &error);
					if (error) {
						g_print("%s\n", error->message);
						g_error_free(error);
						error = NULL;
					}
				}
			} else if (g_strcmp0(f_argv[0], "help") == 0) {
				g_print(
						"help\t\t\tShow this message\n"
						"exit\t\t\tClose FTP session\n"
						"cd <folder>\t\tChange the current folder of the remote device\n"
						"mkdir <folder>\t\tCreate a new folder in the remote device\n"
						"ls\t\t\tList folder contents\n"
						"get <src> <dst>\t\tCopy the src file (from remote device) to the dst file (on local filesystem)\n"
						"put <src> <dst>\t\tCopy the src file (from local filesystem) to the dst file (on remote device)\n"
						"cp <src> <dst>\t\tCopy a file within the remote device from src file to dst file\n"
						"mv <src> <dst>\t\tMove a file within the remote device from src file to dst file\n"
						"rm <target>\t\tDeletes the specified file/folder\n"
						);
			} else if (g_strcmp0(f_argv[0], "exit") == 0 || g_strcmp0(f_argv[0], "quit") == 0) {
				obexclient_remove_session(client, obexclient_file_transfer_get_dbus_object_path(ftp_session), &error);
				exit_if_error(error);

				g_strfreev(f_argv);
				g_free(cmd);
				break;
			} else {
				g_print("invalid command\n");
			}

			g_strfreev(f_argv);
			g_free(cmd);
		}

		g_object_unref(agent);
		g_object_unref(client);
		g_object_unref(ftp_session);

		g_value_unset(&src_v);
		g_value_unset(&dst_v);
		g_value_unset(&target_v);
		g_hash_table_unref(device_dict);

		g_free(src_address);
		g_free(dst_address);
	}

	dbus_disconnect();

	exit(EXIT_SUCCESS);
}
Example #3
0
int
main (int argc, char **argv)
{
	GList *list = NULL;
	GList *categories = NULL;
	GOptionContext *context;
	gboolean prefer_local = FALSE;
	gboolean ret;
	gboolean show_results = FALSE;
	guint64 refine_flags = GS_PLUGIN_REFINE_FLAGS_DEFAULT;
	gint i;
	gint repeat = 1;
	int status = 0;
	_cleanup_error_free_ GError *error = NULL;
	_cleanup_free_ gchar *refine_flags_str = NULL;
	_cleanup_object_unref_ GsApp *app = NULL;
	_cleanup_object_unref_ GsPluginLoader *plugin_loader = NULL;
	_cleanup_object_unref_ GsProfile *profile = NULL;
	const GOptionEntry options[] = {
		{ "show-results", '\0', 0, G_OPTION_ARG_NONE, &show_results,
		  "Show the results for the action", NULL },
		{ "refine-flags", '\0', 0, G_OPTION_ARG_STRING, &refine_flags_str,
		  "Set any refine flags required for the action", NULL },
		{ "repeat", '\0', 0, G_OPTION_ARG_INT, &repeat,
		  "Repeat the action this number of times", NULL },
		{ "prefer-local", '\0', 0, G_OPTION_ARG_NONE, &prefer_local,
		  "Prefer local file sources to AppStream", NULL },
		{ NULL}
	};

	setlocale (LC_ALL, "");
	g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);

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

	gtk_init (&argc, &argv);

	context = g_option_context_new (NULL);
	g_option_context_set_summary (context, "GNOME Software Test Program");
	g_option_context_add_main_entries (context, options, NULL);
	g_option_context_add_group (context, gtk_get_option_group (TRUE));
	ret = g_option_context_parse (context, &argc, &argv, &error);
	if (!ret) {
		g_print ("Failed to parse options: %s\n", error->message);
		goto out;
	}

	/* prefer local sources */
	if (prefer_local)
		g_setenv ("GNOME_SOFTWARE_PREFER_LOCAL", "true", TRUE);

	/* parse any refine flags */
	refine_flags = gs_cmd_parse_refine_flags (refine_flags_str, &error);
	if (refine_flags == G_MAXUINT64) {
		g_print ("Flag unknown: %s\n", error->message);
		goto out;
	}

	profile = gs_profile_new ();
	gs_profile_start (profile, "GsCmd");

	/* load plugins */
	plugin_loader = gs_plugin_loader_new ();
	gs_plugin_loader_set_location (plugin_loader, "./plugins/.libs");
	ret = gs_plugin_loader_setup (plugin_loader, &error);
	if (!ret) {
		g_print ("Failed to setup plugins: %s\n", error->message);
		goto out;
	}
	gs_plugin_loader_dump_state (plugin_loader);

	/* do action */
	if (argc == 2 && g_strcmp0 (argv[1], "installed") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_plugin_list_free (list);
			list = gs_plugin_loader_get_installed (plugin_loader,
							       refine_flags,
							       NULL,
							       &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 3 && g_strcmp0 (argv[1], "search") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_plugin_list_free (list);
			list = gs_plugin_loader_search (plugin_loader,
							argv[2],
							refine_flags,
							NULL,
							&error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 3 && g_strcmp0 (argv[1], "refine") == 0) {
		app = gs_app_new (argv[2]);
		for (i = 0; i < repeat; i++) {
			ret = gs_plugin_loader_app_refine (plugin_loader,
							   app,
							   refine_flags,
							   NULL,
							   &error);
			if (!ret)
				break;
		}
	} else if (argc == 3 && g_strcmp0 (argv[1], "filename-to-app") == 0) {
		app = gs_plugin_loader_filename_to_app (plugin_loader,
							argv[2],
							refine_flags,
							NULL,
							&error);
		if (app == NULL) {
			ret = FALSE;
		} else {
			gs_plugin_add_app (&list, app);
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "updates") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_plugin_list_free (list);
			list = gs_plugin_loader_get_updates (plugin_loader,
							     refine_flags,
							     NULL,
							     &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "sources") == 0) {
		list = gs_plugin_loader_get_sources (plugin_loader,
						     refine_flags,
						     NULL,
						     &error);
		if (list == NULL)
			ret = FALSE;
	} else if (argc == 2 && g_strcmp0 (argv[1], "popular") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_plugin_list_free (list);
			list = gs_plugin_loader_get_popular (plugin_loader,
							     refine_flags,
							     NULL,
							     &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "featured") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_plugin_list_free (list);
			list = gs_plugin_loader_get_featured (plugin_loader,
							      refine_flags,
							      NULL,
							      &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "get-categories") == 0) {
		for (i = 0; i < repeat; i++) {
			if (categories != NULL)
				gs_plugin_list_free (categories);
			categories = gs_plugin_loader_get_categories (plugin_loader,
								      refine_flags,
								      NULL,
								      &error);
			if (categories == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 3 && g_strcmp0 (argv[1], "get-category-apps") == 0) {
		_cleanup_object_unref_ GsCategory *category = NULL;
		_cleanup_strv_free_ gchar **split = NULL;
		split = g_strsplit (argv[2], "/", 2);
		if (g_strv_length (split) == 1) {
			category = gs_category_new (NULL, split[0], NULL);
		} else {
			_cleanup_object_unref_ GsCategory *parent = NULL;
			parent = gs_category_new (NULL, split[0], NULL);
			category = gs_category_new (parent, split[1], NULL);
		}
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_plugin_list_free (list);
			list = gs_plugin_loader_get_category_apps (plugin_loader,
								   category,
								   refine_flags,
								   NULL,
								   &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "refresh") == 0) {
		ret = gs_plugin_loader_refresh (plugin_loader, 0,
						GS_PLUGIN_REFRESH_FLAGS_UPDATES,
						NULL, &error);
	} else {
		ret = FALSE;
		g_set_error_literal (&error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_FAILED,
				     "Did not recognise option, use 'installed', "
				     "'updates', 'popular', 'get-categories', "
				     "'get-category-apps', 'filename-to-app', "
				     "'sources', 'refresh' or 'search'");
	}
	if (!ret) {
		g_print ("Failed: %s\n", error->message);
		goto out;
	}

	if (show_results) {
		gs_cmd_show_results_apps (list);
		gs_cmd_show_results_categories (categories);
	}
out:
	gs_profile_stop (profile, "GsCmd");
	gs_profile_dump (profile);
	g_option_context_free (context);
	gs_plugin_list_free (list);
	gs_plugin_list_free (categories);
	return status;
}
Example #4
0
gboolean parse_arguments_rstrnt(AppData *app_data, int argc, char *argv[])
{
    gchar **positional_args = NULL;
    GOptionContext *context = NULL;
    GOptionGroup *option_group = NULL;
    GError *error = NULL;
    gboolean rc = FALSE;
    guint positional_arg_count = 0;

    GOptionEntry entry[] = {
        {"server", 's', 0, G_OPTION_ARG_CALLBACK, callback_server,
            "Server to connect to", "URL" },
        { "message", 't', 0, G_OPTION_ARG_STRING, &app_data->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, &app_data->no_plugins,
            "don't run any plugins on server side", NULL },
        { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &positional_args,
            NULL, NULL},
        { NULL }
    };

    option_group = g_option_group_new ("main",
                                                    "Application Options",
                                                    "Various application related options",
                                                    app_data, NULL);

    g_option_group_add_entries(option_group, entry);
    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 RECIPE_URL and TASKID defined.\n"
            "If HARNESS_PREFIX is defined then the value of that must be\n"
            "prefixed to RECIPE_URL and TASKID");
    g_option_context_set_main_group (context, option_group);

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

    if(!parse_succeeded){
        cmd_usage(context);
        rc = FALSE;
        goto cleanup;
    }

    if( positional_args != NULL ) {
        positional_arg_count = g_strv_length(positional_args);
    }

    if( positional_args == NULL ||
        app_data->server == NULL ||
        positional_arg_count > 4 ||
        positional_arg_count < 2 )
    {
        cmd_usage(context);
        rc = FALSE;
        goto cleanup;
    }

    app_data->test_name = g_strdup(positional_args[0]);
    app_data->test_result = g_strdup(positional_args[1]);
    if(positional_arg_count > 2){
        app_data->score = g_strdup(positional_args[2]);
    }

    rc = TRUE;
cleanup:
    g_option_context_free(context);
    g_strfreev(positional_args);
    g_clear_error(&error);

    return rc;
}
Example #5
0
File: main.c Project: GNOME/gvfs
int
main (int argc, char *argv[])
{
    GVfsDaemon *daemon;
    gboolean replace;
    gboolean no_fuse;
    gboolean debugging;
    gboolean show_version;
    GError *error;
    guint name_owner_id;
    GBusNameOwnerFlags flags;
    GOptionContext *context;
    const GOptionEntry options[] = {
        { "replace", 'r', 0, G_OPTION_ARG_NONE, &replace,  N_("Replace old daemon."), NULL },
        { "no-fuse", 0, 0, G_OPTION_ARG_NONE, &no_fuse,  N_("Don’t start fuse."), NULL },
        { "debug", 'd', 0, G_OPTION_ARG_NONE, &debugging,  N_("Enable debug output."), NULL },
        { "version", 0, 0, G_OPTION_ARG_NONE, &show_version, N_("Show program version."), NULL},
        { NULL }
    };

    setlocale (LC_ALL, "");

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

    gvfs_setup_debug_handler ();

#ifdef SIGPIPE
    signal (SIGPIPE, SIG_IGN);
#endif

    g_set_application_name (_("GVFS Daemon"));
    context = g_option_context_new ("");

    g_option_context_set_summary (context, _("Main daemon for GVFS"));

    g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);

    replace = FALSE;
    no_fuse = FALSE;
    debugging = FALSE;
    show_version = FALSE;

    if (g_getenv ("GVFS_DISABLE_FUSE") != NULL)
        no_fuse = TRUE;

    error = NULL;
    if (!g_option_context_parse (context, &argc, &argv, &error))
    {
        /* Translators: the first %s is the application name, */
        /* the second %s is the error message                 */
        g_printerr (_("%s: %s"), g_get_application_name(), error->message);
        g_printerr ("\n");
        g_printerr (_("Try “%s --help” for more information."),
                    g_get_prgname ());
        g_printerr ("\n");
        g_error_free (error);
        g_option_context_free (context);
        return 1;
    }

    g_option_context_free (context);

    if (g_getenv ("GVFS_DEBUG"))
        debugging = TRUE;

    gvfs_set_debug (debugging);

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

    loop = g_main_loop_new (NULL, FALSE);

    daemon = g_vfs_daemon_new (TRUE, replace);
    if (daemon == NULL)
        return 1;

    g_signal_connect (daemon, "shutdown",
                      G_CALLBACK (daemon_shutdown), loop);

    flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
    if (replace)
        flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;

    name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
                                    G_VFS_DBUS_DAEMON_NAME,
                                    flags,
                                    on_bus_acquired,
                                    on_name_acquired,
                                    on_name_lost,
                                    GUINT_TO_POINTER (no_fuse),
                                    NULL);

    g_main_loop_run (loop);

    mount_finalize ();

    g_clear_object (&daemon);
    if (name_owner_id != 0)
        g_bus_unown_name (name_owner_id);
    if (loop != NULL)
        g_main_loop_unref (loop);

    return process_result;
}
int
main (int argc, char *argv[])
{
	GOptionContext *opt_ctx;
	GError *error = NULL;
	NMConnectionList *list;
	DBusGConnection *bus;
	char *type = NULL;
	gboolean create = FALSE;
	gboolean show = FALSE;
	gboolean success;
	char *uuid = NULL;
	NMCEService *service = NULL;
	DBusGProxy *proxy = NULL;
	gboolean show_list;

	GOptionEntry entries[] = {
		{ ARG_TYPE,   't', 0, G_OPTION_ARG_STRING, &type,   "Type of connection to show or create", NM_SETTING_WIRED_SETTING_NAME },
		{ ARG_CREATE, 'c', 0, G_OPTION_ARG_NONE,   &create, "Create a new connection", NULL },
		{ ARG_SHOW,   's', 0, G_OPTION_ARG_NONE,   &show,   "Show a given connection type page", NULL },
		{ "edit",     'e', 0, G_OPTION_ARG_STRING, &uuid,   "Edit an existing connection with a given UUID", "UUID" },
		{ NULL }
	};

	bindtextdomain (GETTEXT_PACKAGE, NMALOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	gtk_init (&argc, &argv);
	textdomain (GETTEXT_PACKAGE);

	opt_ctx = g_option_context_new (NULL);
	g_option_context_set_summary (opt_ctx, "Allows users to view and edit network connection settings");
	g_option_context_add_main_entries (opt_ctx, entries, NULL);
	success = g_option_context_parse (opt_ctx, &argc, &argv, &error);
	g_option_context_free (opt_ctx);

	if (!success) {
		g_warning ("%s\n", error->message);
		g_error_free (error);
		return 1;
	}

	/* Just one page for both CDMA & GSM, handle that here */
	if (type && g_strcmp0 (type, NM_SETTING_CDMA_SETTING_NAME) == 0)
		type = (char *) NM_SETTING_GSM_SETTING_NAME;

	/* Inits the dbus-glib type system too */
	bus = dbus_g_bus_get (DBUS_BUS_SESSION, NULL);
	if (bus) {
		proxy = dbus_g_proxy_new_for_name (bus,
		                                   "org.freedesktop.DBus",
		                                   "/org/freedesktop/DBus",
		                                   "org.freedesktop.DBus");
		g_assert (proxy);

		/* Check for an existing instance on the bus, and if there
		 * is one, send the arguments to it and exit instead of opening
		 * a second instance of the connection editor.
		 */
		if (try_existing_instance (bus, proxy, type, create, show, uuid))
			return 0;
	}

	loop = g_main_loop_new (NULL, FALSE);

	list = nm_connection_list_new ();
	if (!list) {
		g_warning ("Failed to initialize the UI, exiting...");
		return 1;
	}
	g_signal_connect_swapped (list, "done", G_CALLBACK (g_main_loop_quit), loop);

	/* Create our single-instance-app service if we can */
	if (proxy)
		service = nm_ce_service_new (bus, proxy, list);

	/* Show the dialog */
	g_signal_connect_swapped (list, "done", G_CALLBACK (g_main_loop_quit), loop);

	/* Figure out what page or editor window we'll show initially */
	show_list = handle_arguments (list, type, create, show, uuid, (create || show || uuid));
	if (show_list)
		nm_connection_list_present (list);

	setup_signals ();
	g_main_loop_run (loop);

	/* Cleanup */
	g_object_unref (list);
	if (service)
		g_object_unref (service);
	if (proxy)
		g_object_unref (proxy);
	if (bus)
		dbus_g_connection_unref (bus);
	return 0;
}
Example #7
0
int
handle_mount (int argc, char *argv[], gboolean do_help)
{
  GOptionContext *context;
  gchar *param;
  GError *error = NULL;
  GFile *file;
  int i;

  g_set_prgname ("gio mount");

  /* Translators: commandline placeholder */
  param = g_strdup_printf ("[%s...]", _("LOCATION"));
  context = g_option_context_new (param);
  g_free (param);
  g_option_context_set_help_enabled (context, FALSE);
  g_option_context_set_summary (context, _("Mount or unmount the locations."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

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

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

  g_option_context_free (context);

  main_loop = g_main_loop_new (NULL, FALSE);

  if (mount_list)
    list_monitor_items ();
  else if (mount_device_file != NULL)
    mount_with_device_file (mount_device_file);
  else if (unmount_scheme != NULL)
    unmount_all_with_scheme (unmount_scheme);
  else if (mount_monitor)
    monitor ();
  else if (argc > 1)
    {
      for (i = 1; i < argc; i++)
        {
          file = g_file_new_for_commandline_arg (argv[i]);
          if (mount_unmount)
            unmount (file);
          else if (mount_eject)
            eject (file);
          else
            mount (file);
          g_object_unref (file);
        }
    }

  if (outstanding_mounts > 0)
    g_main_loop_run (main_loop);

  return success ? 0 : 2;
}
/**
 * main:
 **/
int
main (int argc, char *argv[])
{
	GOptionContext *context;
	gboolean ret;
	GError *error = NULL;
	DBusGConnection *connection;
	DBusGProxy *proxy = NULL;
	gchar **files = NULL;

	const GOptionEntry options[] = {
		{ G_OPTION_REMAINING, '\0', 0, G_OPTION_ARG_FILENAME_ARRAY, &files,
		/* TRANSLATORS: command line option: a list of files to install */
		  _("Local files to install"), NULL },
		{ NULL}
	};

	setlocale (LC_ALL, "");

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

	if (! g_thread_supported ())
		g_thread_init (NULL);
	g_type_init ();
	gtk_init (&argc, &argv);

	/* TRANSLATORS: program name, an application to install a file that is needed by an application and is provided by packages */
	g_set_application_name (_("Single File Installer"));
	context = g_option_context_new ("gpk-install-provide-file");
	g_option_context_set_summary (context, _("Single File Installer"));
	g_option_context_add_main_entries (context, options, NULL);
	g_option_context_add_group (context, egg_debug_get_option_group ());
	g_option_context_add_group (context, gtk_get_option_group (TRUE));
	g_option_context_parse (context, &argc, &argv, NULL);
	g_option_context_free (context);

	/* TRANSLATORS: application name to pass to to the user if there are not enough privs */
	ret = gpk_check_privileged_user (_("Single File Installer"), TRUE);
	if (!ret)
		goto out;

	if (files == NULL) {
		/* TRANSLATORS: nothing done */
		gpk_error_dialog (_("Failed to install a package to provide a file"),
				  /* TRANSLATORS: nothig was specified */
				  _("You need to specify a filename to install"), NULL);
		goto out;
	}

	/* check dbus connections, exit if not valid */
	connection = dbus_g_bus_get (DBUS_BUS_SESSION, &error);
	if (connection == NULL) {
		egg_warning ("%s", error->message);
		goto out;
	}

	/* get a connection */
	proxy = dbus_g_proxy_new_for_name (connection,
					   "org.freedesktop.PackageKit",
					   "/org/freedesktop/PackageKit",
					   "org.freedesktop.PackageKit.Modify");
	if (proxy == NULL) {
		egg_warning ("Cannot connect to session service");
		goto out;
	}

	/* don't timeout, as dbus-glib sets the timeout ~25 seconds */
	dbus_g_proxy_set_default_timeout (proxy, INT_MAX);

	/* do method */
	ret = dbus_g_proxy_call (proxy, "InstallProvideFiles", &error,
				 G_TYPE_UINT, 0, /* xid */
				 G_TYPE_STRV, files, /* data */
				 G_TYPE_STRING, "hide-finished,hide-warnings", /* interaction */
				 G_TYPE_INVALID,
				 G_TYPE_INVALID);
	if (!ret && !gpk_ignore_session_error (error)) {
		/* TRANSLATORS: This is when the specified DBus method did not execute successfully */
		gpk_error_dialog (_("The action could not be completed"),
				  /* TRANSLATORS: we don't have anything more useful to translate. sorry. */
				  _("The request failed. More details are available in the detailed report."),
				  error->message);
		egg_warning ("%s", error->message);
		goto out;
	}
out:
	if (error != NULL)
		g_error_free (error);
	if (proxy != NULL)
		g_object_unref (proxy);
	g_strfreev (files);
	return !ret;
}
int
main (int argc, char *argv[])
{
        GError *error;
        gint ret;
        GBusNameOwnerFlags flags;
        GOptionContext *context;
        static gboolean replace;
        static gboolean show_version;
        static GOptionEntry entries[] = {
                { "version", 0, 0, G_OPTION_ARG_NONE, &show_version, N_("Output version information and exit"), NULL },
                { "replace", 0, 0, G_OPTION_ARG_NONE, &replace, N_("Replace existing instance"), NULL },
                { "debug", 0, 0, G_OPTION_ARG_NONE, &debug, N_("Enable debugging code"), NULL },

                { NULL }
        };

        ret = 1;
        error = NULL;

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

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

        if (!g_setenv ("GIO_USE_VFS", "local", TRUE)) {
                g_warning ("Couldn't set GIO_USE_GVFS");
                goto out;
        }

        context = g_option_context_new ("");
        g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
        g_option_context_set_summary (context, _("Provides D-Bus interfaces for querying and manipulating\nuser account information."));
        g_option_context_add_main_entries (context, entries, NULL);
        error = NULL;
        if (!g_option_context_parse (context, &argc, &argv, &error)) {
                g_warning ("%s", error->message);
                g_error_free (error);
                goto out;
        }
        g_option_context_free (context);

        if (show_version) {
                g_print ("accounts-daemon " VERSION "\n");
                ret = 0;
                goto out;
        }

        /* If --debug, then print debug messages even when no G_MESSAGES_DEBUG */
        if (debug && !g_getenv ("G_MESSAGES_DEBUG"))
                g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, on_log_debug, NULL);
        g_log_set_default_handler (log_handler, NULL);

        flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
        if (replace)
                flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;
        g_bus_own_name (G_BUS_TYPE_SYSTEM,
                        NAME_TO_CLAIM,
                        flags,
                        on_bus_acquired,
                        NULL,
                        on_name_lost,
                        NULL,
                        NULL);

        loop = g_main_loop_new (NULL, FALSE);

        g_unix_signal_add (SIGINT, on_signal_quit, loop);
        g_unix_signal_add (SIGTERM, on_signal_quit, loop);

        g_debug ("entering main loop");
        g_main_loop_run (loop);

        g_debug ("exiting");
        g_main_loop_unref (loop);

        ret = 0;

 out:
        return ret;
}
Example #10
0
int
handle_tree (int argc, char *argv[], gboolean do_help)
{
  GOptionContext *context;
  GError *error = NULL;
  GFile *file;
  gchar *param;
  int i;

  g_set_prgname ("gio tree");

  /* Translators: commandline placeholder */
  param = g_strdup_printf ("[%s...]", _("LOCATION"));
  context = g_option_context_new (param);
  g_free (param);
  g_option_context_set_help_enabled (context, FALSE);
  g_option_context_set_summary (context,
      _("List contents of directories in a tree-like format."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

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

  g_option_context_parse (context, &argc, &argv, &error);

  if (error != NULL)
    {
      show_help (context, error->message);
      g_error_free (error);
      g_option_context_free (context);
      return 1;
    }

  g_option_context_free (context);

  if (argc > 1)
    {
      for (i = 1; i < argc; i++)
        {
          file = g_file_new_for_commandline_arg (argv[i]);
          tree (file);
          g_object_unref (file);
        }
    }
  else
    {
      char *cwd;

      cwd = g_get_current_dir ();
      file = g_file_new_for_path (cwd);
      g_free (cwd);
      tree (file);
      g_object_unref (file);
    }

  return 0;
}
Example #11
0
// main function
int main(int argc, char *argv[])
{
	gboolean show_version = FALSE;
	gboolean log_info = FALSE;
	gboolean log_debug = FALSE;
	gboolean no_daemon = FALSE;
	gboolean test_mode = FALSE;
	gint poll_interval = -1;
	gboolean success;
	GOptionContext *opt_ctx;

	thd_daemonize = TRUE;
	dbus_enable = FALSE;

	GOptionEntry options[] =
	{
		{
			"version", 0, 0, G_OPTION_ARG_NONE, &show_version, N_(
			"Print thermald version and exit"), NULL
		}
		,
		{
			"no-daemon", 0, 0, G_OPTION_ARG_NONE, &no_daemon, N_(
			"Don't become a daemon: Default is daemon mode"), NULL
		}
		,
		{
			"loglevel=info", 0, 0, G_OPTION_ARG_NONE, &log_info, N_(
			"log severity: info level and up"), NULL
		}
		,
		{
			"loglevel=debug", 0, 0, G_OPTION_ARG_NONE, &log_debug, N_(
			"log severity: debug level and up: Max logging"), NULL
		}
		,
		{
			"test-mode", 0, 0, G_OPTION_ARG_NONE, &test_mode, N_(
			"Test Mode only: Allow non root user"), NULL
		}
		,
		{
			"poll-interval", 0, 0, G_OPTION_ARG_INT, &poll_interval, N_(
			"Poll interval in seconds: Poll for zone temperature changes. "
			"If want to disable polling set to zero."), NULL
		}
		,
		{
			"dbus-enable", 0, 0, G_OPTION_ARG_NONE, &dbus_enable, N_(
			"Enable Dbus."), NULL
		}
		,
		{
			"use-thermal-sysfs", 0, 0, G_OPTION_ARG_NONE, &use_thermal_sys_fs, N_(
			"Use thermal sysfs instead of DTS sensors, default use dts."), NULL
		}
		,

		{
			NULL
		}
	};

	if(!g_module_supported())
	{
		fprintf(stderr, _("GModules are not supported on your platform!\n"));
		exit(1);
	}

	/* Set locale to be able to use environment variables */
	setlocale(LC_ALL, "");

	bindtextdomain(GETTEXT_PACKAGE, TDLOCALEDIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
	textdomain(GETTEXT_PACKAGE);
	/* Parse options */
	opt_ctx = g_option_context_new(NULL);
	g_option_context_set_translation_domain(opt_ctx, GETTEXT_PACKAGE);
	g_option_context_set_ignore_unknown_options(opt_ctx, FALSE);
	g_option_context_set_help_enabled(opt_ctx, TRUE);
	g_option_context_add_main_entries(opt_ctx, options, NULL);

	g_option_context_set_summary(opt_ctx, _(
		"Thermal daemon monitors temperature sensors and decides the best action "
		"based on the temperature readings and user preferences."));

	success = g_option_context_parse(opt_ctx, &argc, &argv, NULL);
	g_option_context_free(opt_ctx);

	if(!success)
	{
		fprintf(stderr, _(
			"Invalid option.  Please use --help to see a list of valid options.\n"));
		exit(1);
	}

	if(show_version)
	{
		fprintf(stdout, TD_DIST_VERSION "\n");
		exit(0);
	}

	if(getuid() != 0 && !test_mode)
	{
		fprintf(stderr, _("You must be root to run thermald!\n"));
		exit(1);
	}
	if(g_mkdir_with_parents(TDRUNDIR, 0755) != 0)
	{
		fprintf(stderr, "Cannot create '%s': %s", TDRUNDIR, strerror(errno));
		exit(1);
	}
	g_mkdir_with_parents(TDCONFDIR, 0755); // Don't care return value as directory
	// may already exist
	if(log_info)
	{
		thd_log_level |= G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO;
	}
	if(log_debug)
	{
		thd_log_level |= G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG;
	}
	if(poll_interval >= 0)
	{
		fprintf(stdout, "Polling enabled: %d\n", poll_interval);
		thd_poll_interval = poll_interval;
	}

	openlog("thermald", LOG_PID, LOG_USER | LOG_DAEMON | LOG_SYSLOG);
	// Don't care return val
	//setlogmask(LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_DEBUG | LOG_INFO);
	thd_daemonize = !no_daemon;
	g_log_set_handler(NULL, G_LOG_LEVEL_MASK, thd_logger, NULL);

	if(no_daemon)
		signal(SIGINT, sig_int_handler);

	// dbus glib processing begin
	thd_dbus_server_proc(no_daemon);

	fprintf(stdout, "Exiting ..\n");
	closelog();
	exit(success ? 0 : 1);
}
Example #12
0
int
handle_rename (int argc, char *argv[], gboolean do_help)
{
  GOptionContext *context;
  GError *error = NULL;
  GFile *file;
  GFile *new_file;
  int retval = 0;
  gchar *param;

  g_set_prgname ("gio rename");

  /* Translators: commandline placeholder */
  param = g_strdup_printf ("%s %s", _("LOCATION"), _("NAME"));
  context = g_option_context_new (param);
  g_free (param);
  g_option_context_set_help_enabled (context, FALSE);

  g_option_context_set_summary (context, _("Rename a file."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

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

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

  if (argc < 3)
    {
      show_help (context, _("Missing argument"));
      return 1;
    }
  if (argc > 3)
    {
      show_help (context, _("Too many arguments"));
      return 1;
    }

  g_option_context_free (context);

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

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

  g_object_unref (file);

  return retval;
}
static GOptionContext *make_option_context(const struct openslide_tools_usage_info *info) {
  GOptionContext *octx = g_option_context_new(info->parameter_string);
  g_option_context_set_summary(octx, info->summary);
  g_option_context_add_main_entries(octx, options, NULL);
  return octx;
}
Example #14
0
int
main (int argc, char *argv[])
{
  GError *error;
  GOptionContext *context;
  GFile *source, *dest, *target;
  gboolean dest_is_dir;
  char *basename;
  int i;
  GFileCopyFlags flags;
  int retval = 0;
  gchar *param;
  gchar *summary;

  setlocale (LC_ALL, "");

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

  error = NULL;
  param = g_strdup_printf ("%s... %s", _("SOURCE"), _("DEST"));
  summary = _("Move one or more files from SOURCE to DEST.");

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

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

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

  dest = g_file_new_for_commandline_arg (argv[argc-1]);

  if (no_target_directory && argc > 3)
    {
      show_help (context, _("Too many arguments\n"));
      g_object_unref (dest);
      return 1;
    }

  dest_is_dir = is_dir (dest);

  if (!dest_is_dir && argc > 3)
    {
      g_printerr (_("Target %s is not a directory\n"), argv[argc-1]);
      show_help (context, NULL);
      g_object_unref (dest);
      return 1;
    }

  g_option_context_free (context);
  g_free (param);

  for (i = 1; i < argc - 1; i++)
    {
      source = g_file_new_for_commandline_arg (argv[i]);

      if (dest_is_dir && !no_target_directory)
	{
	  basename = g_file_get_basename (source);
	  target = g_file_get_child (dest, basename);
	  g_free (basename);
	}
      else
	target = g_object_ref (dest);

      flags = 0;
      if (backup)
	flags |= G_FILE_COPY_BACKUP;
      if (!interactive)
	flags |= G_FILE_COPY_OVERWRITE;

      error = NULL;
      if (!g_file_move (source, target, flags, NULL, progress?show_progress:NULL, NULL, &error))
	{
	  if (interactive && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_EXISTS))
	    {
	      char line[16];

	      g_error_free (error);
	      error = NULL;

	      basename = g_file_get_basename (target);
	      g_print ("overwrite %s?", basename);
	      g_free (basename);

	      if (fgets(line, sizeof (line), stdin) &&
		  line[0] == 'y')
		{
		  flags |= G_FILE_COPY_OVERWRITE;
		  if (!g_file_move (source, target, flags, NULL, NULL, NULL, &error))
		    goto move_failed;
		}
	    }
	  else
	    {
	    move_failed:
	      g_printerr (_("Error moving file %s: %s\n"), argv[i], error->message);
	      g_error_free (error);
	      retval = 1;
	    }
	}

      g_object_unref (source);
      g_object_unref (target);
    }

  g_object_unref (dest);

  return retval;
}
Example #15
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;
}
Example #16
0
int
main (int argc, char *argv[])
{
	GOptionContext *opt_ctx = NULL;
	GError *error = NULL;
	NMConnectionList *list = NULL;
	guint owner_id = 0, registration_id = 0;
	GDBusConnection *bus = NULL;
	gs_free char *type = NULL, *uuid = NULL, *import = NULL;
	gboolean create = FALSE, show = FALSE;
	int ret = 1;

	GOptionEntry entries[] = {
		{ ARG_TYPE,   't', 0, G_OPTION_ARG_STRING, &type,   "Type of connection to show or create", NM_SETTING_WIRED_SETTING_NAME },
		{ ARG_CREATE, 'c', 0, G_OPTION_ARG_NONE,   &create, "Create a new connection", NULL },
		{ ARG_SHOW,   's', 0, G_OPTION_ARG_NONE,   &show,   "Show a given connection type page", NULL },
		{ "edit",     'e', 0, G_OPTION_ARG_STRING, &uuid,   "Edit an existing connection with a given UUID", "UUID" },
		{ ARG_IMPORT, 'i', 0, G_OPTION_ARG_STRING, &import, "Import a VPN connection from given file", NULL },

		/* This is not passed over D-Bus. */
		{ "keep-above", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &nm_ce_keep_above, NULL, NULL },
		{ NULL }
	};

	bindtextdomain (GETTEXT_PACKAGE, NMALOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	gtk_init (&argc, &argv);
	textdomain (GETTEXT_PACKAGE);

	opt_ctx = g_option_context_new (NULL);
	g_option_context_set_summary (opt_ctx, "Allows users to view and edit network connection settings");
	g_option_context_add_main_entries (opt_ctx, entries, NULL);
	if (!g_option_context_parse (opt_ctx, &argc, &argv, &error)) {
		g_printerr ("Failed to parse options: %s\n", error->message);
		goto out;
	}

	/* Just one page for both CDMA & GSM, handle that here */
	if (g_strcmp0 (type, NM_SETTING_CDMA_SETTING_NAME) == 0) {
		g_free (type);
		type = g_strdup (NM_SETTING_GSM_SETTING_NAME);
	}

	bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
	if (bus) {
		/* Check for an existing instance on the bus, and if there
		 * is one, send the arguments to it and exit instead of opening
		 * a second instance of the connection editor.
		 */
		if (try_existing_instance (bus, type, create, show, uuid, import)) {
			/* success */
			ret = 0;
			goto out;
		}
	}

	loop = g_main_loop_new (NULL, FALSE);

	list = nm_connection_list_new ();
	if (!list) {
		g_warning ("Failed to initialize the UI, exiting...");
		goto out;
	}
	g_signal_connect_swapped (list, "done", G_CALLBACK (g_main_loop_quit), loop);

	owner_id = start_service (bus, list, &registration_id);

	/* Figure out what page or editor window we'll show initially */
	if (handle_arguments (list, type, create, show, uuid, import, (create || show || uuid || import)))
		nm_connection_list_present (list);

	g_unix_signal_add (SIGTERM, signal_handler, GINT_TO_POINTER (SIGTERM));
	g_unix_signal_add (SIGINT, signal_handler, GINT_TO_POINTER (SIGINT));

	g_main_loop_run (loop);
	ret = 0;

out:
	if (owner_id)
		g_bus_unown_name (owner_id);
	if (registration_id)
		g_dbus_connection_unregister_object (bus, registration_id);
	if (introspection_data)
		g_dbus_node_info_unref (introspection_data);
	g_clear_error (&error);
	if (opt_ctx)
		g_option_context_free (opt_ctx);
	g_clear_object (&list);
	g_clear_object (&bus);
	return ret;
}
Example #17
0
/**
 * main:
 **/
int
main (int argc, char *argv[])
{
	GMainLoop *loop;
	DBusGConnection *system_connection;
	DBusGConnection *session_connection;
	gboolean verbose = FALSE;
	gboolean version = FALSE;
	gboolean timed_exit = FALSE;
	gboolean immediate_exit = FALSE;
	GpmSession *session = NULL;
	GpmManager *manager = NULL;
	GError *error = NULL;
	GOptionContext *context;
	gint ret;

	const GOptionEntry options[] = {
		{ "verbose", '\0', 0, G_OPTION_ARG_NONE, &verbose,
		  N_("Show extra debugging information"), NULL },
		{ "version", '\0', 0, G_OPTION_ARG_NONE, &version,
		  N_("Show version of installed program and exit"), NULL },
		{ "timed-exit", '\0', 0, G_OPTION_ARG_NONE, &timed_exit,
		  N_("Exit after a small delay (for debugging)"), NULL },
		{ "immediate-exit", '\0', 0, G_OPTION_ARG_NONE, &immediate_exit,
		  N_("Exit after the manager has loaded (for debugging)"), NULL },
		{ NULL}
	};

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

	dbus_g_thread_init ();

	context = g_option_context_new (N_("MATE Power Manager"));
	/* TRANSLATORS: program name, a simple app to view pending updates */
	g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);
	g_option_context_set_translation_domain(context, GETTEXT_PACKAGE);
	g_option_context_set_summary (context, _("MATE Power Manager"));
	g_option_context_parse (context, &argc, &argv, NULL);

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

	dbus_g_thread_init ();

	gtk_init (&argc, &argv);
	egg_debug_init (verbose);

	egg_debug ("MATE %s %s", GPM_NAME, VERSION);

	/* check dbus connections, exit if not valid */
	system_connection = dbus_g_bus_get (DBUS_BUS_SYSTEM, &error);
	if (error) {
		egg_warning ("%s", error->message);
		g_error_free (error);
		egg_error ("This program cannot start until you start "
			   "the dbus system service.\n"
			   "It is <b>strongly recommended</b> you reboot "
			   "your computer after starting this service.");
	}

	session_connection = dbus_g_bus_get (DBUS_BUS_SESSION, &error);
	if (error) {
		egg_warning ("%s", error->message);
		g_error_free (error);
		egg_error ("This program cannot start until you start the "
			   "dbus session service.\n\n"
			   "This is usually started automatically in X "
			   "or mate startup when you start a new session.");
	}

	/* add application specific icons to search path */
	gtk_icon_theme_append_search_path (gtk_icon_theme_get_default (),
                                           GPM_DATA G_DIR_SEPARATOR_S "icons");

	loop = g_main_loop_new (NULL, FALSE);

	/* optionally register with the session */
	session = gpm_session_new ();
	g_signal_connect (session, "stop", G_CALLBACK (gpm_main_stop_cb), loop);
	g_signal_connect (session, "query-end-session", G_CALLBACK (gpm_main_query_end_session_cb), loop);
	g_signal_connect (session, "end-session", G_CALLBACK (gpm_main_end_session_cb), loop);
	gpm_session_register_client (session, "mate-power-manager", getenv ("DESKTOP_AUTOSTART_ID"));

	/* create a new gui object */
	manager = gpm_manager_new ();

	if (!gpm_object_register (session_connection, G_OBJECT (manager))) {
		egg_error ("%s is already running in this session.", GPM_NAME);
		return 0;
	}

	/* register to be a policy agent, just like kpackagekit does */
	ret = dbus_bus_request_name(dbus_g_connection_get_connection(system_connection),
				    "org.freedesktop.Policy.Power",
				    DBUS_NAME_FLAG_REPLACE_EXISTING, NULL);
	switch (ret) {
	case DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER:
		egg_debug ("Successfully acquired interface org.freedesktop.Policy.Power.");
		break;
	case DBUS_REQUEST_NAME_REPLY_IN_QUEUE:
		egg_debug ("Queued for interface org.freedesktop.Policy.Power.");
		break;
	default:
		break;
	};

	/* 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);
	}

	if (immediate_exit == FALSE) {
		g_main_loop_run (loop);
	}

	g_main_loop_unref (loop);

	g_object_unref (session);
	g_object_unref (manager);
unref_program:
	g_option_context_free (context);
	return 0;
}
Example #18
0
int
main (int argc, char **argv)
{
	GList *list = NULL;
	GList *categories = NULL;
	GOptionContext *context;
	gboolean prefer_local = FALSE;
	gboolean ret;
	gboolean show_results = FALSE;
	gboolean verbose = FALSE;
	guint64 refine_flags = GS_PLUGIN_REFINE_FLAGS_DEFAULT;
	gint i;
	gint cache_age = 0;
	gint repeat = 1;
	int status = 0;
	g_auto(GStrv) plugin_names = NULL;
	g_autoptr(GError) error = NULL;
	g_autoptr(GsDebug) debug = gs_debug_new ();
	g_autofree gchar *plugin_names_str = NULL;
	g_autofree gchar *refine_flags_str = NULL;
	g_autoptr(GsApp) app = NULL;
	g_autoptr(GFile) file = NULL;
	g_autoptr(GsPluginLoader) plugin_loader = NULL;
	g_autoptr(AsProfile) profile = NULL;
	g_autoptr(AsProfileTask) ptask = NULL;
	const GOptionEntry options[] = {
		{ "show-results", '\0', 0, G_OPTION_ARG_NONE, &show_results,
		  "Show the results for the action", NULL },
		{ "refine-flags", '\0', 0, G_OPTION_ARG_STRING, &refine_flags_str,
		  "Set any refine flags required for the action", NULL },
		{ "repeat", '\0', 0, G_OPTION_ARG_INT, &repeat,
		  "Repeat the action this number of times", NULL },
		{ "cache-age", '\0', 0, G_OPTION_ARG_INT, &cache_age,
		  "Use this maximum cache age in seconds", NULL },
		{ "prefer-local", '\0', 0, G_OPTION_ARG_NONE, &prefer_local,
		  "Prefer local file sources to AppStream", NULL },
		{ "plugin-names", '\0', 0, G_OPTION_ARG_STRING, &plugin_names_str,
		  "Whitelist only these plugin names", NULL },
		{ "verbose", '\0', 0, G_OPTION_ARG_NONE, &verbose,
		  "Show verbose debugging information", NULL },
		{ NULL}
	};

	setlocale (LC_ALL, "");
	g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);

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

	gtk_init (&argc, &argv);

	context = g_option_context_new (NULL);
	g_option_context_set_summary (context, "GNOME Software Test Program");
	g_option_context_add_main_entries (context, options, NULL);
	g_option_context_add_group (context, gtk_get_option_group (TRUE));
	ret = g_option_context_parse (context, &argc, &argv, &error);
	if (!ret) {
		g_print ("Failed to parse options: %s\n", error->message);
		goto out;
	}
	if (verbose)
		g_setenv ("GS_DEBUG", "1", TRUE);

	/* prefer local sources */
	if (prefer_local)
		g_setenv ("GNOME_SOFTWARE_PREFER_LOCAL", "true", TRUE);

	/* parse any refine flags */
	refine_flags = gs_cmd_parse_refine_flags (refine_flags_str, &error);
	if (refine_flags == G_MAXUINT64) {
		g_print ("Flag unknown: %s\n", error->message);
		goto out;
	}

	profile = as_profile_new ();
	ptask = as_profile_start_literal (profile, "GsCmd");

	/* load plugins */
	plugin_loader = gs_plugin_loader_new ();
	gs_plugin_loader_set_location (plugin_loader, "./plugins/.libs");
	if (plugin_names_str != NULL)
		plugin_names = g_strsplit (plugin_names_str, ",", -1);
	ret = gs_plugin_loader_setup (plugin_loader, plugin_names, &error);
	if (!ret) {
		g_print ("Failed to setup plugins: %s\n", error->message);
		goto out;
	}
	gs_plugin_loader_dump_state (plugin_loader);

	/* do action */
	if (argc == 2 && g_strcmp0 (argv[1], "installed") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_app_list_free (list);
			list = gs_plugin_loader_get_installed (plugin_loader,
							       refine_flags,
							       NULL,
							       &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 3 && g_strcmp0 (argv[1], "search") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_app_list_free (list);
			list = gs_plugin_loader_search (plugin_loader,
							argv[2],
							refine_flags,
							NULL,
							&error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 3 && g_strcmp0 (argv[1], "action-upgrade-download") == 0) {
		app = gs_app_new (argv[2]);
		gs_app_set_kind (app, AS_APP_KIND_OS_UPGRADE);
		ret = gs_plugin_loader_app_action (plugin_loader,
						   app,
						   GS_PLUGIN_LOADER_ACTION_UPGRADE_DOWNLOAD,
						   NULL,
						   &error);
		if (ret)
			gs_app_list_add (&list, app);
	} else if (argc == 3 && g_strcmp0 (argv[1], "refine") == 0) {
		app = gs_app_new (argv[2]);
		for (i = 0; i < repeat; i++) {
			ret = gs_plugin_loader_app_refine (plugin_loader,
							   app,
							   refine_flags,
							   NULL,
							   &error);
			if (!ret)
				break;
		}
		gs_app_list_add (&list, app);
	} else if (argc == 3 && g_strcmp0 (argv[1], "launch") == 0) {
		app = gs_app_new (argv[2]);
		for (i = 0; i < repeat; i++) {
			ret = gs_plugin_loader_app_action (plugin_loader,
							   app,
							   GS_PLUGIN_LOADER_ACTION_LAUNCH,
							   NULL,
							   &error);
			if (!ret)
				break;
		}
	} else if (argc == 3 && g_strcmp0 (argv[1], "filename-to-app") == 0) {
		file = g_file_new_for_path (argv[2]);
		app = gs_plugin_loader_file_to_app (plugin_loader,
						    file,
						    refine_flags,
						    NULL,
						    &error);
		if (app == NULL) {
			ret = FALSE;
		} else {
			gs_app_list_add (&list, app);
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "updates") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_app_list_free (list);
			list = gs_plugin_loader_get_updates (plugin_loader,
							     refine_flags,
							     NULL,
							     &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "upgrades") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_app_list_free (list);
			list = gs_plugin_loader_get_distro_upgrades (plugin_loader,
								     refine_flags,
								     NULL,
								     &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "sources") == 0) {
		list = gs_plugin_loader_get_sources (plugin_loader,
						     refine_flags,
						     NULL,
						     &error);
		if (list == NULL)
			ret = FALSE;
	} else if (argc == 2 && g_strcmp0 (argv[1], "popular") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_app_list_free (list);
			list = gs_plugin_loader_get_popular (plugin_loader,
							     refine_flags,
							     NULL,
							     &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "featured") == 0) {
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_app_list_free (list);
			list = gs_plugin_loader_get_featured (plugin_loader,
							      refine_flags,
							      NULL,
							      &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 2 && g_strcmp0 (argv[1], "get-categories") == 0) {
		for (i = 0; i < repeat; i++) {
			if (categories != NULL)
				gs_app_list_free (categories);
			categories = gs_plugin_loader_get_categories (plugin_loader,
								      refine_flags,
								      NULL,
								      &error);
			if (categories == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc == 3 && g_strcmp0 (argv[1], "get-category-apps") == 0) {
		g_autoptr(GsCategory) category = NULL;
		g_auto(GStrv) split = NULL;
		split = g_strsplit (argv[2], "/", 2);
		if (g_strv_length (split) == 1) {
			category = gs_category_new (NULL, split[0], NULL);
		} else {
			g_autoptr(GsCategory) parent = NULL;
			parent = gs_category_new (NULL, split[0], NULL);
			category = gs_category_new (parent, split[1], NULL);
		}
		for (i = 0; i < repeat; i++) {
			if (list != NULL)
				gs_app_list_free (list);
			list = gs_plugin_loader_get_category_apps (plugin_loader,
								   category,
								   refine_flags,
								   NULL,
								   &error);
			if (list == NULL) {
				ret = FALSE;
				break;
			}
		}
	} else if (argc >= 2 && g_strcmp0 (argv[1], "refresh") == 0) {
		GsPluginRefreshFlags refresh_flags;
		refresh_flags = gs_cmd_refresh_flag_from_string (argv[2]);
		ret = gs_plugin_loader_refresh (plugin_loader, cache_age,
						refresh_flags, NULL, &error);
	} else {
		ret = FALSE;
		g_set_error_literal (&error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_FAILED,
				     "Did not recognise option, use 'installed', "
				     "'updates', 'popular', 'get-categories', "
				     "'get-category-apps', 'filename-to-app', "
				     "'sources', 'refresh', 'launch' or 'search'");
	}
	if (!ret) {
		g_print ("Failed: %s\n", error->message);
		goto out;
	}

	if (show_results) {
		gs_cmd_show_results_apps (list);
		gs_cmd_show_results_categories (categories);
	}
out:
	if (profile != NULL)
		as_profile_dump (profile);
	g_option_context_free (context);
	gs_app_list_free (list);
	gs_app_list_free (categories);
	return status;
}
Example #19
0
int
main (int argc, char **argv)
{
	ArvFakeGvCamera *gv_camera;
	int n_events;
	GInputVector input_vector;
	GOptionContext *context;
	GError *error = NULL;

	arv_g_thread_init (NULL);
	arv_g_type_init ();

	context = g_option_context_new (NULL);
	g_option_context_set_summary (context, "Fake GigEVision camera.");
	g_option_context_set_description (context, "Example: 'arv-fake-gv-camera-" ARAVIS_API_VERSION " -i eth0'");
	g_option_context_add_main_entries (context, arv_option_entries, NULL);

	if (!g_option_context_parse (context, &argc, &argv, &error)) {
		g_option_context_free (context);
		g_print ("Option parsing failed: %s\n", error->message);
		g_error_free (error);
		return EXIT_FAILURE;
	}

	g_option_context_free (context);

	arv_debug_enable (arv_option_debug_domains);

	gv_camera = arv_fake_gv_camera_new (arv_option_interface_name);
	if (gv_camera == NULL) {
		g_print ("Can't instantiate a new fake camera.\n");
		g_print ("An existing instance may already use the '%s' interface.\n", arv_option_interface_name);
		return EXIT_FAILURE;
	}

	input_vector.buffer = g_malloc0 (ARV_FAKE_GV_CAMERA_BUFFER_SIZE);
	input_vector.size = ARV_FAKE_GV_CAMERA_BUFFER_SIZE;

	signal (SIGINT, set_cancel);

	do {
		n_events = g_poll (gv_camera->gvcp_fds, 2, 1000);
		g_print ("n_events = %d\n", n_events);
		if (n_events > 0) {
			GSocketAddress *remote_address;
			int count;

			count = g_socket_receive_message (gv_camera->gvcp_socket,
							  &remote_address, &input_vector, 1, NULL, NULL,
							  G_SOCKET_MSG_NONE, NULL, NULL);
			if (count > 0)
				handle_control_packet (gv_camera, gv_camera->gvcp_socket,
						       remote_address, input_vector.buffer, count);

			if (gv_camera->discovery_socket != NULL) {
				count = g_socket_receive_message (gv_camera->discovery_socket,
								  &remote_address, &input_vector, 1, NULL, NULL,
								  G_SOCKET_MSG_NONE, NULL, NULL);
				if (count > 0)
					handle_control_packet (gv_camera, gv_camera->discovery_socket,
							       remote_address, input_vector.buffer, count);
			}
		}
	} while (!cancel);

	g_free (input_vector.buffer);

	arv_fake_gv_camera_free (gv_camera);

	return EXIT_SUCCESS;
}
Example #20
0
int main( int argc, char *argv[])
{
    GtkWidget *window;
    GtkWidget *button;
    GtkWidget *vbox;

    playback_t play = { 0 };

    /* Option parsing */
    GError *error = NULL;
    GOptionContext *context;
    GOptionEntry entries[] =
    {
      { "input-filename", 'i', 0, G_OPTION_ARG_FILENAME, &(play.filename), "Input filename", "FILE" },
      { NULL }
    };

    context = g_option_context_new("- Firefly MV Camera Playback");
    g_option_context_set_summary(context, 
            "Replays successive frames previously recorded\n"
            "using dc1394-record");
    g_option_context_add_main_entries (context, entries, NULL);

    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        printf( "Error: %s\n%s", 
                error->message, 
                g_option_context_get_help(context, TRUE, NULL));
        exit(1);
    }
    if (play.filename == NULL) {
        printf( "Error: You must supply a filename\n%s", 
                g_option_context_get_help(context, TRUE, NULL));
        exit(2);
    }

    if (play.filename[0] == '-') {
        play.fp = stdin;
    } else {
        play.fp = fopen(play.filename, "rb");
    }

    if( play.fp == NULL ) { 
        perror("opening file");
        exit(1);
    }

    // read the first frame
    play.total_frame_size = read_frame(&play.frame, play.fp);
    if (play.frame.color_coding == DC1394_COLOR_CODING_MONO8)
        play.show = GRAY;
    else if (play.frame.color_coding == DC1394_COLOR_CODING_RGB8)
        play.show = COLOR;
    else if (play.frame.color_coding == DC1394_COLOR_CODING_RAW8)
        play.show = FORMAT7;
    else {
        perror("invalid color coding");
        exit(1);
    }

    gtk_init( &argc, &argv );
    gdk_rgb_init();

    gtk_widget_set_default_colormap (gdk_rgb_get_cmap());
    gtk_widget_set_default_visual (gdk_rgb_get_visual());

    // create window
    window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
    g_signal_connect( G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL );
    g_signal_connect( G_OBJECT(window), "destroy", G_CALLBACK(delete_event), NULL );
    gtk_container_set_border_width( GTK_CONTAINER(window), 10 );

    // add widgets
    // vbox (VBox)
    vbox = gtk_vbox_new(FALSE, 10);
    gtk_container_add( GTK_CONTAINER(window), vbox );

    // canvas (DrawingArea)
    play.canvas = gtk_drawing_area_new();
    gtk_widget_set_size_request(play.canvas, play.frame.size[0], play.frame.size[1]);
    g_signal_connect (G_OBJECT (play.canvas), "expose_event",  
            G_CALLBACK (expose_event_callback), &play);

    gtk_widget_set_events(play.canvas, GDK_LEAVE_NOTIFY_MASK
            | GDK_BUTTON_PRESS_MASK
            | GDK_BUTTON_RELEASE_MASK
            | GDK_POINTER_MOTION_MASK );

    g_signal_connect( G_OBJECT(play.canvas), "button_press_event", 
           G_CALLBACK(canvas_button_press), &play);

    gtk_box_pack_start(GTK_BOX(vbox), play.canvas, TRUE, TRUE, 0);

    // quit button 
    button = gtk_button_new_with_label( "Quit" );
    g_signal_connect_swapped( G_OBJECT(button), "clicked",
            G_CALLBACK(gtk_widget_destroy),
            G_OBJECT(window) );
    gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, TRUE, 0);

    // play button 
    button = gtk_button_new_with_label( "Play" );
    g_signal_connect (G_OBJECT (button), "clicked",
                      G_CALLBACK (on_play_clicked_event), (gpointer) &play);
    gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, TRUE, 0);

    // display everything
    gtk_widget_show_all( window );

    // render the first frame
    renderframe(0, &play);
    
    // go
    gtk_main();

    fclose(play.fp);

    return 0;
}
int main(int argc, char **argv)
{
  unsigned i;
  GError *error = NULL;
  GOptionContext *op_context;
  unsigned line_no = 0;
  GHashTable *contexts_by_str;
  GPtrArray *all_contexts;
  GHashTable *code_points_by_line;
  GPtrArray *all_code_points;
  char *tmp_fname;
  char **files;
  guint n_files;
  AllocInfo *total_by_time;
  op_context = g_option_context_new (NULL);
  g_option_context_set_summary (op_context, "gsk-analyze-successive-memdumps");
  g_option_context_add_main_entries (op_context, op_entries, NULL);
  if (!g_option_context_parse (op_context, &argc, &argv, &error))
    gsk_fatal_user_error ("error parsing command-line options: %s", error->message);
  g_option_context_free (op_context);

  contexts_by_str = g_hash_table_new (g_str_hash, g_str_equal);
  code_points_by_line = g_hash_table_new (g_str_hash, g_str_equal);
  all_contexts = g_ptr_array_new ();
  all_code_points = g_ptr_array_new ();

  if (dir_name == NULL)
    g_error ("missing argument directory");

  n_files = argc - 1;
  files = argv + 1;
  g_printerr ("Scanning %u input files... ", n_files);
  total_by_time = g_new0 (AllocInfo, n_files);
  for (i = 0; i < n_files; i++)
    {
      FILE *fp = fopen (files[i], "r");
      char buf[4096];
      GString *context_str = g_string_new ("");
      AllocInfo ai;
      Context *context;
      update_percent_bar (i, n_files);
      if (fp == NULL)
        gsk_fatal_user_error ("opening %s failed: %s",
	                      files[i], g_strerror (errno));
      do
        {
          if (!fgets (buf, sizeof (buf), fp))
            gsk_fatal_user_error ("file %s: unexpected eof", files[i]);
          line_no++;
        }
      while (is_preamble_line (buf));
next_block_start:
      if (g_str_has_prefix (buf, "Summary: "))
        goto done_file;
      if (sscanf (buf, "%u bytes allocated in %u blocks from:",
                      &ai.n_bytes, &ai.n_blocks) != 2)
        gsk_fatal_user_error ("error parsing line %u from %s",
                              line_no, files[i]);
      g_string_set_size (context_str, 0);
      for (;;)
        {
          if (fgets (buf, sizeof (buf), fp) == NULL)
            gsk_fatal_user_error ("file %s: unexpected eof", files[i]);
          line_no++;
          if (buf[0] != ' ')
            break;
          g_string_append (context_str, buf + 2);
        }

      /* find or create context */
      context = g_hash_table_lookup (contexts_by_str, context_str->str);
      if (context == NULL)
        {
          context = g_new (Context, 1);
          context->str = g_strdup (context_str->str);
          context->alloc_infos = g_new0 (AllocInfo, n_files);
          g_hash_table_insert (contexts_by_str, context->str, context);
          context->total_bytes = 0;
          g_ptr_array_add (all_contexts, context);
        }
      context->alloc_infos[i] = ai;
      context->total_bytes += ai.n_bytes;
      total_by_time[i].n_bytes += ai.n_bytes;
      total_by_time[i].n_blocks += ai.n_blocks;
      goto next_block_start;

done_file:
      fclose (fp);
    }
  update_percent_bar (i, n_files);

  g_ptr_array_sort (all_contexts, compare_p_context_by_total_bytes_descending);
  if (!gsk_mkdir_p (dir_name, 0755, &error))
    gsk_fatal_user_error ("error making directory %s: %s", dir_name, error->message);
  static const char *subdirs[] = { "data", "images", "code-points" };
  for (i = 0; i < G_N_ELEMENTS (subdirs); i++)
    {
      tmp_fname = g_strdup_printf ("%s/%s", dir_name, subdirs[i]);
      if (!gsk_mkdir_p (tmp_fname, 0755, &error))
        g_error ("error mkdir(%s): %s", tmp_fname, error->message);
      g_free (tmp_fname);
    }
  FILE *gnuplot_script_fp, *index_html_fp, *main_html_fp;
  tmp_fname = g_strdup_printf ("%s/gnuplot.input", dir_name);
  gnuplot_script_fp = fopen (tmp_fname, "w");
  if (gnuplot_script_fp == NULL)
    g_error ("error creating %s: %s", tmp_fname, g_strerror (errno));
  g_free (tmp_fname);
  fprintf (gnuplot_script_fp,
           "set terminal png\n\n");
  index_html_fp = NULL;

  {
    FILE *fp;
    tmp_fname = g_strdup_printf ("%s/data/total.data", dir_name);
    fp = fopen (tmp_fname, "w");
    if (fp == NULL)
      g_error ("creating %s failed", tmp_fname);
    g_free (tmp_fname);
    for (i = 0; i < n_files; i++)
      fprintf (fp, "%u %u %u\n", i,
               total_by_time[i].n_bytes,
               total_by_time[i].n_blocks);
    fclose (fp);

    fprintf (gnuplot_script_fp,
             "set output \"%s/images/total.png\"\n", dir_name);
    fprintf (gnuplot_script_fp,
             "plot \"%s/data/total.data\" using 1:2 title \"bytes\", \"%s/data/total.data\" using 1:3 title \"blocks\"\n",
             dir_name, dir_name);
  }

  tmp_fname = g_strdup_printf ("%s/index.html", dir_name);
  main_html_fp = fopen (tmp_fname, "w");
  if (main_html_fp == NULL)
    g_error ("error creating %s: %s", tmp_fname, g_strerror (errno));
  fprintf (main_html_fp, "<html><body>\n"
                         "Total:\n<br/><img src=\"images/total.png\" /><br/>\n"
                         "<ul>\n");

  g_printerr ("Writing data files for %u contexts... ", all_contexts->len);
  for (i = 0; i < all_contexts->len; i++)
    {
      FILE *fp;
      Context *context = all_contexts->pdata[i];
      guint j;
      update_percent_bar (i, all_contexts->len);
      if (i % 100 == 0)
        {
          if (index_html_fp != NULL)
            {
              fprintf (index_html_fp, "</body></html>\n");
              fclose (index_html_fp);
            }
          tmp_fname = g_strdup_printf ("%s/index-%03u.html", dir_name, i / 100);
          index_html_fp = fopen (tmp_fname, "w");
          if (index_html_fp == NULL)
            g_error ("error creating %s: %s", tmp_fname, g_strerror (errno));
          g_free (tmp_fname);
          fprintf (index_html_fp, "<html><body>\n");
          fprintf (index_html_fp, "<h1>Contexts %u .. %u</h1>\n", i, MIN (i + 99, all_contexts->len - 1));

          fprintf (main_html_fp, "<li><a href=\"index-%03u.html\">Contexts %u .. %u</a></li>\n",
                   i / 100,  i, MIN (i + 99, all_contexts->len - 1));
        }

      tmp_fname = g_strdup_printf ("%s/data/context-%05u.data", dir_name, i);
      fp = fopen (tmp_fname, "w");
      if (fp == NULL)
        g_error ("error creating %s: %s", tmp_fname, g_strerror (errno));
      for (j = 0; j < n_files; j++)
        fprintf (fp, "%u %u %u\n", j,
                 context->alloc_infos[j].n_bytes,
                 context->alloc_infos[j].n_blocks);
      fclose (fp);
      fprintf (gnuplot_script_fp,
               "set output \"%s/images/context-%05u.png\"\n", dir_name, i);
      fprintf (gnuplot_script_fp,
               "plot \"%s/data/context-%05u.data\" using 1:2 title \"bytes\", \"%s/data/context-%05u.data\" using 1:3 title \"blocks\"\n",
               dir_name, i,
               dir_name, i);

      pr_context (index_html_fp, i, context, "images");
    }
  update_percent_bar (i, all_contexts->len);
  fprintf (main_html_fp, "</ul>\n"
                         "<h1>Code Point Index</h1>\n"
                          "<a href=\"index-by-code-point.html\">here</a>\n");
  if (index_html_fp != NULL)
    {
      fprintf (index_html_fp, "</body></html>\n");
      fclose (index_html_fp);
    }
  fprintf (main_html_fp, "</body></html>\n");
  fclose (main_html_fp);

  g_printerr ("Calculating code-points... ");
  for (i = 0; i < all_contexts->len; i++)
    {
      Context *context = all_contexts->pdata[i];
      CodePoint *cp;
      char **strs = g_strsplit (context->str, "\n", 0);
      unsigned j;
      for (j = 0; strs[j] != NULL; j++)
        {
          g_strstrip (strs[j]);
          if (strs[j][0] != 0)
            {
              cp = g_hash_table_lookup (code_points_by_line, strs[j]);
              if (cp == NULL)
                {
                  cp = g_new (CodePoint, 1);
                  cp->line = g_strdup (strs[j]);
                  cp->context_indices = g_array_new (FALSE, FALSE, sizeof (guint));
                  g_hash_table_insert (code_points_by_line, cp->line, cp);
                  g_ptr_array_add (all_code_points, cp);
                }
              if (cp->context_indices->len == 0
               || g_array_index (cp->context_indices, guint, cp->context_indices->len - 1) != i)
                g_array_append_val (cp->context_indices, i);
            }
        }
      g_strfreev (strs);
    }
  g_printerr (" done [%u code points].\n", all_code_points->len);
  g_ptr_array_sort (all_code_points, compare_p_code_point_by_line);
  tmp_fname = g_strdup_printf ("%s/index-by-code-point.html", dir_name);
  main_html_fp = fopen (tmp_fname, "w");
  if (main_html_fp == NULL)
    g_error ("error creating %s: %s", tmp_fname, g_strerror (errno));
  g_free (tmp_fname);
  fprintf (main_html_fp,
           "<html><body><h1>Code Points</h1>\n");
  fprintf (main_html_fp,
           "<ul>\n");
  AllocInfo *totals;
  totals = g_new (AllocInfo, n_files);
  g_printerr ("Creating code-point data... ");
  for (i = 0; i < all_code_points->len; i++)
    {
      CodePoint *cp = all_code_points->pdata[i];
      FILE *fp;
      unsigned j;
      update_percent_bar (i, all_code_points->len);
      memset (totals, 0, sizeof (AllocInfo) * n_files);
      for (j = 0; j < cp->context_indices->len; j++)
        {
          guint context_index = g_array_index (cp->context_indices, guint, j);
          Context *context = all_contexts->pdata[context_index];
          guint k;
          for (k = 0; k < n_files; k++)
            {
              totals[k].n_bytes += context->alloc_infos[k].n_bytes;
              totals[k].n_blocks += context->alloc_infos[k].n_blocks;
            }
        }
      tmp_fname = g_strdup_printf ("%s/data/codepoint-%05u.data", dir_name, i);
      fp = fopen (tmp_fname, "w");
      for (j = 0; j < n_files; j++)
        fprintf (fp, "%u %u %u\n", j,
                 totals[j].n_bytes,
                 totals[j].n_blocks);
      fclose (fp);

      fprintf (gnuplot_script_fp,
               "set output \"%s/images/codepoint-%05u.png\"\n", dir_name, i);
      fprintf (gnuplot_script_fp,
               "plot \"%s/data/codepoint-%05u.data\" using 1:2 title \"bytes\", \"%s/data/codepoint-%05u.data\" using 1:3 title \"blocks\"\n",
               dir_name, i,
               dir_name, i);

      fprintf (main_html_fp, "<li>Code point %05u: <a href=\"code-points/%05u.html\">%s</a> (%u contexts)</li>\n",
               i, i, cp->line, cp->context_indices->len);
      tmp_fname = g_strdup_printf ("%s/code-points/%05u.html", dir_name, i);
      fp = fopen (tmp_fname, "w");
      if (fp == NULL)
        g_error ("error creating %s: %s", tmp_fname, g_strerror (errno));
      g_free (tmp_fname);



      fprintf (fp, "<html><body><h1>Code Point %u</h1>\n"
               "<b><pre>\n"
               "%s\n"
               "</pre>\n"
               "</b>\n", i, cp->line);
      fprintf (fp, "<p>Summary<br /><img src=\"../images/codepoint-%05u.png\" /></p>\n", i);
      for (j = 0; j < MIN (cp->context_indices->len, 100); j++)
        pr_context (fp, g_array_index (cp->context_indices, guint, j),
                    all_contexts->pdata[g_array_index (cp->context_indices, guint, j)],
                    "../images");
      if (j < cp->context_indices->len)
        fprintf (fp, "<p><b>%u Contexts omitted</b></p>\n",
                 (guint)(cp->context_indices->len - j));
      fprintf (fp,
               "</body></html>\n");
      fclose (fp);
    }
  update_percent_bar (i, all_code_points->len);
  fprintf (main_html_fp,
           "</ul>\n"
           "</body></html>\n");
  fclose (main_html_fp);

  fclose (gnuplot_script_fp);

  g_printerr ("Running gnuplot... ");
  tmp_fname = g_strdup_printf ("gnuplot < %s/gnuplot.input", dir_name);
  if (system (tmp_fname) != 0)
    gsk_fatal_user_error ("error running gnuplot");
  g_free (tmp_fname);
  g_printerr (" done.\n");

  return 0;
}
Example #22
0
int
main(int argc, char *argv[])
{
	IAnjutaProject *project = NULL;
	AnjutaProjectNode *node;
	AnjutaProjectNode *child;
	AnjutaProjectNode *sibling;
	AnjutaProjectNode *root = NULL;
	char **command;
	GOptionContext *context;
	GError *error = NULL;

	/* Initialize program */
	g_type_init ();


	/* Parse options */
 	context = g_option_context_new ("list [args]");
  	g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
	g_option_context_set_summary (context, "test new autotools project manger");
	if (!g_option_context_parse (context, &argc, &argv, &error))
    {
		exit (1);
    }
	if (argc < 2)
	{
		printf ("PROJECT: %s", g_option_context_get_help (context, TRUE, NULL));
		exit (1);
	}

	open_output ();

	/* Execute commands */
	for (command = &argv[1]; *command != NULL; command++)
	{
		if (g_ascii_strcasecmp (*command, "load") == 0)
		{
			GFile *file = g_file_new_for_commandline_arg (*(++command));

			if (project == NULL)
			{
				gint best = 0;
				gint probe;
				GType type;
				GTypeModule *module;

				/* Register project types */
				module = g_object_new (dummy_type_module_get_type (), NULL);
				amp_project_register (module);

				/* Check for project type */
				probe = amp_project_probe (file, NULL);
				if (probe > best)
				{
					best = probe;
					type = AMP_TYPE_PROJECT;
				}

				if (best == 0)
				{
					print_error ("Error: No backend for loading project in %s", *command);
					break;
				}
				else
				{
					project = IANJUTA_PROJECT (amp_project_new (file, NULL, NULL));
				}
			}

			root = ianjuta_project_get_root (project, &error);
			ianjuta_project_load_node (project, root, &error);
			g_object_unref (file);
		}
		else if (g_ascii_strcasecmp (*command, "list") == 0)
		{
			list_root (project, root);
		}
		else if (g_ascii_strcasecmp (*command, "move") == 0)
		{
			if (AMP_IS_PROJECT (project))
			{
				amp_project_move (AMP_PROJECT (project), *(++command));
			}
		}
		else if (g_ascii_strcasecmp (*command, "save") == 0)
		{
			ianjuta_project_save_node (project, root, NULL);
		}
		else if (g_ascii_strcasecmp (*command, "remove") == 0)
		{
			node = get_node (project, root, *(++command));
			ianjuta_project_remove_node (project, node, NULL);
		}
		else if (g_ascii_strcasecmp (*command, "dump") == 0)
		{
			if (g_ascii_strcasecmp (command[1], "makefile") == 0)
			{
				node = get_node (project, root, command[2]);
				amp_project_dump (AMP_PROJECT (project), node, DUMP_MAKEFILE);
				command +=2;
			}
			else if (g_ascii_strcasecmp (command[1], "configure") == 0)
			{
				amp_project_dump (AMP_PROJECT (project), root, DUMP_CONFIGURE);
				command +=1;
			}
			else
			{
				print_error ("Error: unknown command %s %s", *command, command[1]);
				break;
			}
		}
		else if (g_ascii_strcasecmp (command[0], "add") == 0)
		{
			node = get_node (project, root, command[2]);
			if (g_ascii_strcasecmp (command[1], "group") == 0)
			{
				if ((command[4] != NULL) && (g_ascii_strcasecmp (command[4], "before") == 0))
				{
					sibling = get_node (project, root, command[5]);
					child = ianjuta_project_add_node_before (project, node, sibling, ANJUTA_PROJECT_GROUP, NULL, command[3], &error);
					command += 2;
				}
				else if ((command[4] != NULL) && (g_ascii_strcasecmp (command[4], "after") == 0))
				{
					sibling = get_node (project, root, command[5]);
					child = ianjuta_project_add_node_after (project, node, sibling, ANJUTA_PROJECT_GROUP, NULL, command[3], &error);
					command += 2;
				}
				else
				{
					child = ianjuta_project_add_node_before (project, node, NULL, ANJUTA_PROJECT_GROUP, NULL, command[3], &error);
				}
			}
			else if (g_ascii_strcasecmp (command[1], "target") == 0)
			{
				if ((command[5] != NULL) && (g_ascii_strcasecmp (command[5], "before") == 0))
				{
					sibling = get_node (project, root, command[6]);
					child = ianjuta_project_add_node_before (project, node, sibling, ANJUTA_PROJECT_TARGET | get_target_type (project, command[4]), NULL, command[3], &error);
					command += 2;
				}
				else if ((command[5] != NULL) && (g_ascii_strcasecmp (command[5], "after") == 0))
				{
					sibling = get_node (project, root, command[6]);
					child = ianjuta_project_add_node_after (project, node, sibling, ANJUTA_PROJECT_TARGET | get_target_type (project, command[4]), NULL, command[3], &error);
					command += 2;
				}
				else
				{
					child = ianjuta_project_add_node_before (project, node, NULL, ANJUTA_PROJECT_TARGET | get_target_type (project, command[4]), NULL, command[3], &error);
				}
				command++;
			}
			else if (g_ascii_strcasecmp (command[1], "source") == 0)
			{
				GFile *file = get_file (node, command[3]);

				if ((command[4] != NULL) && (g_ascii_strcasecmp (command[4], "before") == 0))
				{
					sibling = get_node (project, root, command[5]);
					child = ianjuta_project_add_node_before (project, node, sibling, ANJUTA_PROJECT_SOURCE, file, NULL, &error);
					command += 2;
				}
				else if ((command[4] != NULL) && (g_ascii_strcasecmp (command[4], "after") == 0))
				{
					sibling = get_node (project, root, command[5]);
					child = ianjuta_project_add_node_after (project, node, sibling, ANJUTA_PROJECT_SOURCE, file, NULL, &error);
					command += 2;
				}
				else
				{
					child = ianjuta_project_add_node_before (project, node, NULL, ANJUTA_PROJECT_SOURCE, file, NULL, &error);
				}
				g_object_unref (file);
			}
			else if (g_ascii_strcasecmp (command[1], "module") == 0)
			{
				if ((command[4] != NULL) && (g_ascii_strcasecmp (command[4], "before") == 0))
				{
					sibling = get_node (project, root, command[5]);
					child = ianjuta_project_add_node_before (project, node, sibling, ANJUTA_PROJECT_MODULE, NULL, command[3], &error);
					command += 2;
				}
				else if ((command[4] != NULL) && (g_ascii_strcasecmp (command[4], "after") == 0))
				{
					sibling = get_node (project, root, command[5]);
					child = ianjuta_project_add_node_after (project, node, sibling, ANJUTA_PROJECT_MODULE, NULL, command[3], &error);
					command += 2;
				}
				else
				{
					child = ianjuta_project_add_node_before (project, node, NULL, ANJUTA_PROJECT_MODULE, NULL, command[3], &error);
				}
			}
			else if (g_ascii_strcasecmp (command[1], "package") == 0)
			{
				if ((command[4] != NULL) && (g_ascii_strcasecmp (command[4], "before") == 0))
				{
					sibling = get_node (project, root, command[5]);
					child = ianjuta_project_add_node_before (project, node, sibling, ANJUTA_PROJECT_PACKAGE, NULL, command[3], &error);
					command += 2;
				}
				else if ((command[4] != NULL) && (g_ascii_strcasecmp (command[4], "after") == 0))
				{
					sibling = get_node (project, root, command[5]);
					child = ianjuta_project_add_node_after (project, node, sibling, ANJUTA_PROJECT_PACKAGE, NULL, command[3], &error);
					command += 2;
				}
				else
				{
					child = ianjuta_project_add_node_before (project, node, NULL, ANJUTA_PROJECT_PACKAGE, NULL, command[3], &error);
				}
			}
			else
			{
				print_error ("Error: unknown command %s", *command);

				break;
			}
			command += 3;
		}
		else if (g_ascii_strcasecmp (command[0], "set") == 0)
		{
			if (AMP_IS_PROJECT (project))
			{
				AnjutaProjectPropertyInfo *info;

				node = get_node (project, root, command[1]);
				info = get_project_property (project, node, command[2]);
				if (info != NULL)
				{
					gchar *value = g_shell_unquote (command[3], NULL);
					ianjuta_project_set_property (project, node, info->id, NULL, value, NULL);
					g_free (value);
				}
			}
			command += 3;
		}
		else if (g_ascii_strcasecmp (command[0], "clear") == 0)
		{
			if (AMP_IS_PROJECT (project))
			{
				AnjutaProjectPropertyInfo *info;

				node = get_node (project, root, command[1]);
				info = get_project_property (project, node, command[2]);
				if (info != NULL)
				{
					ianjuta_project_remove_property (project, node, info->id, NULL, NULL);
				}
			}
			command += 2;
		}
		else
		{
			print_error ("Error: unknown command %s", *command);

			break;
		}
		amp_project_wait_ready (project);
		if (error != NULL)
		{
			print_error ("Error: %s", error->message == NULL ? "unknown error" : error->message);

			g_error_free (error);
			error = NULL;
		}
	}

	/* Free objects */
	if (project) g_object_unref (project);
	close_output ();

	return (0);
}