/** * main: **/ int main (int argc, char *argv[]) { CdUtilPrivate *priv; gboolean ret = TRUE; gboolean verbose = FALSE; guint retval = 1; g_autoptr(GError) error = NULL; g_autofree gchar *cmd_descriptions = NULL; g_autofree gchar *locale = NULL; g_autoptr(GFile) file = NULL; const GOptionEntry options[] = { { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, /* TRANSLATORS: command line option */ _("Show extra debugging information"), NULL }, { "locale", '\0', 0, G_OPTION_ARG_STRING, &locale, /* TRANSLATORS: command line option */ _("The locale to use when setting localized text"), NULL }, { NULL} }; setlocale (LC_ALL, ""); bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); cmsSetLogErrorHandler (cd_util_lcms_error_cb); /* create helper object */ priv = g_new0 (CdUtilPrivate, 1); priv->rewrite_file = TRUE; priv->client = cd_client_new (); /* add commands */ priv->cmd_array = g_ptr_array_new_with_free_func ((GDestroyNotify) cd_util_item_free); cd_util_add (priv->cmd_array, "extract-vcgt", /* TRANSLATORS: command description */ _("Generate the VCGT calibration of a given size"), cd_util_extract_vcgt); cd_util_add (priv->cmd_array, "md-clear", /* TRANSLATORS: command description */ _("Clear any metadata in the profile"), cd_util_clear_metadata); cd_util_add (priv->cmd_array, "md-init", /* TRANSLATORS: command description */ _("Initialize any metadata for the profile"), cd_util_init_metadata); cd_util_add (priv->cmd_array, "md-add", /* TRANSLATORS: command description */ _("Add a metadata item to the profile"), cd_util_add_metadata); cd_util_add (priv->cmd_array, "md-remove", /* TRANSLATORS: command description */ _("Remove a metadata item from the profile"), cd_util_remove_metadata); cd_util_add (priv->cmd_array, "set-copyright", /* TRANSLATORS: command description */ _("Sets the copyright string"), cd_util_set_copyright); cd_util_add (priv->cmd_array, "set-description", /* TRANSLATORS: command description */ _("Sets the description string"), cd_util_set_description); cd_util_add (priv->cmd_array, "set-manufacturer", /* TRANSLATORS: command description */ _("Sets the manufacturer string"), cd_util_set_manufacturer); cd_util_add (priv->cmd_array, "set-model", /* TRANSLATORS: command description */ _("Sets the model string"), cd_util_set_model); cd_util_add (priv->cmd_array, "md-fix", /* TRANSLATORS: command description */ _("Automatically fix metadata in the profile"), cd_util_set_fix_metadata); cd_util_add (priv->cmd_array, "set-version", /* TRANSLATORS: command description */ _("Set the ICC profile version"), cd_util_set_version); cd_util_add (priv->cmd_array, "export-tag-data", /* TRANSLATORS: command description */ _("Export the tag data"), cd_util_export_tag_data); /* sort by command name */ g_ptr_array_sort (priv->cmd_array, (GCompareFunc) cd_sort_command_name_cb); /* get a list of the commands */ priv->context = g_option_context_new (NULL); cmd_descriptions = cd_util_get_descriptions (priv->cmd_array); g_option_context_set_summary (priv->context, cmd_descriptions); /* TRANSLATORS: program name */ g_set_application_name (_("Color Management")); g_option_context_add_main_entries (priv->context, options, NULL); ret = g_option_context_parse (priv->context, &argc, &argv, &error); if (!ret) { /* TRANSLATORS: the user didn't read the man page */ g_print ("%s: %s\n", _("Failed to parse arguments"), error->message); goto out; } /* use explicit locale */ priv->locale = g_strdup (locale); /* set verbose? */ if (verbose) { g_setenv ("COLORD_VERBOSE", "1", FALSE); } else { g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, cd_util_ignore_cb, NULL); } /* the first option is always the filename */ if (argc < 2) { g_print ("%s\n", "Filename must be the first argument"); goto out; } /* open file */ file = g_file_new_for_path (argv[1]); priv->icc = cd_icc_new (); ret = cd_icc_load_file (priv->icc, file, CD_ICC_LOAD_FLAGS_ALL, NULL, &error); if (!ret) { g_print ("%s\n", error->message); goto out; } /* run the specified command */ ret = cd_util_run (priv, argv[2], (gchar**) &argv[2], &error); if (!ret) { g_print ("%s\n", error->message); goto out; } /* save file */ if (priv->rewrite_file) { ret = cd_icc_save_file (priv->icc, file, CD_ICC_SAVE_FLAGS_NONE, NULL, &error); if (!ret) { g_print ("%s\n", error->message); goto out; } } /* success */ retval = 0; out: if (priv != NULL) { if (priv->cmd_array != NULL) g_ptr_array_unref (priv->cmd_array); g_option_context_free (priv->context); if (priv->icc != NULL) g_object_unref (priv->icc); g_object_unref (priv->client); g_free (priv->locale); g_free (priv); } return retval; }
int main (int argc, char **argv) { State *state = NULL; GOptionContext *context = NULL; static char **args = NULL; static gboolean run_script = FALSE; static gboolean allow_remote_connections = FALSE; gboolean debug = FALSE; gboolean ret; int exit_status = EX_OK; static GOptionEntry entries [] = { { "run-script", 'r', 0, G_OPTION_ARG_NONE, &run_script, N_("Run program through /etc/gdm/Xsession wrapper script"), NULL }, { "allow-remote-connections", 'a', 0, G_OPTION_ARG_NONE, &allow_remote_connections, N_("Listen on TCP socket"), NULL }, { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &args, "", "" }, { NULL } }; bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR); textdomain (GETTEXT_PACKAGE); setlocale (LC_ALL, ""); gdm_log_init (); context = g_option_context_new (_("GNOME Display Manager X Session Launcher")); g_option_context_add_main_entries (context, entries, NULL); g_option_context_parse (context, &argc, &argv, NULL); g_option_context_free (context); if (args == NULL || args[0] == NULL || args[1] != NULL) { g_warning ("gdm-x-session takes one argument (the session)"); exit_status = EX_USAGE; goto out; } init_state (&state); state->session_command = args[0]; state->settings = gdm_settings_new (); ret = gdm_settings_direct_init (state->settings, DATADIR "/gdm/gdm.schemas", "/"); if (!ret) { g_printerr ("Unable to initialize settings\n"); exit_status = EX_DATAERR; goto out; } gdm_settings_direct_get_boolean (GDM_KEY_DEBUG, &debug); state->debug_enabled = debug; gdm_log_set_debug (debug); state->main_loop = g_main_loop_new (NULL, FALSE); state->cancellable = g_cancellable_new (); g_unix_signal_add (SIGTERM, (GSourceFunc) on_sigterm, state); ret = spawn_x_server (state, allow_remote_connections, state->cancellable); if (!ret) { g_printerr ("Unable to run X server\n"); exit_status = EX_SOFTWARE; goto out; } ret = spawn_bus (state, state->cancellable); if (!ret) { g_printerr ("Unable to run session message bus\n"); exit_status = EX_SOFTWARE; goto out; } import_environment (state, state->cancellable); ret = update_bus_environment (state, state->cancellable); if (!ret) { g_printerr ("Unable to update bus environment\n"); exit_status = EX_SOFTWARE; goto out; } ret = register_display (state, state->cancellable); if (!ret) { g_printerr ("Unable to register display with display manager\n"); exit_status = EX_SOFTWARE; goto out; } ret = spawn_session (state, run_script, state->cancellable); if (!ret) { g_printerr ("Unable to run session\n"); exit_status = EX_SOFTWARE; goto out; } g_main_loop_run (state->main_loop); /* Only use exit status of session if we're here because it exit */ if (state->session_subprocess == NULL) { exit_status = state->session_exit_status; } out: signal_subprocesses (state); wait_on_subprocesses (state); clear_state (&state); return exit_status; }
"stay active", NULL }, { "sn", 's', 0, G_OPTION_ARG_NONE, &sn, "Enable startup notification", NULL }, { "output", 'o', 0, G_OPTION_ARG_STRING, &output, "file to write data to", NULL }, { "template", 'T', 0, G_OPTION_ARG_STRING, &template, "Use filename as template for openbox-menu output", NULL }, { "noicons", 'i', 0, G_OPTION_ARG_NONE, &no_icons, "Don't display icons in menu", NULL }, { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &app_menu, NULL, "[file.menu]" }, {NULL} }; GOptionContext *help_context = NULL; help_context = g_option_context_new (" - Openbox menu generator " VERSION); g_option_context_set_help_enabled (help_context, TRUE); g_option_context_add_main_entries (help_context, entries, NULL); g_option_context_parse (help_context, &argc, &argv, &error); if (error) { g_warning ("%s\n", error->message); g_error_free (error); return NULL; } OB_Menu *context = context_new(); if (output) context->output = g_build_filename (g_get_user_cache_dir (), output, NULL);
int main (int argc, char *argv[]) { GError *error = NULL; GOptionContext *context = NULL; GFile *file; gchar *summary; gchar *description; int i; gchar *param; gboolean res; setlocale (LC_ALL, ""); bindtextdomain (GETTEXT_PACKAGE, GVFS_LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); param = g_strdup_printf (("%s..."), _("FILE")); /* Translators: this message will appear after the usage string */ /* and before the list of options. */ summary = _("Concatenate files and print to the standard output."); description = g_strconcat (_("gvfs-cat works just like the traditional cat utility, but using gvfs\n" "locations instead of local files: for example you can use something\n" "like smb://server/resource/file.txt as location."), "\n\n", _("Note: just pipe through cat if you need its formatting options\n" "like -n, -T or other."), NULL); context = g_option_context_new (param); g_option_context_set_summary (context, summary); g_option_context_set_description (context, description); g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE); g_option_context_parse (context, &argc, &argv, &error); g_option_context_free (context); g_free (param); g_free (description); 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 (show_version) { g_print (PACKAGE_STRING "\n"); return 0; } if (!locations) { /* Translators: the %s is the program name. This error message */ /* means the user is calling gvfs-cat without any argument. */ g_printerr (_("%s: missing locations"), g_get_prgname ()); g_printerr ("\n"); g_printerr (_("Try \"%s --help\" for more information."), g_get_prgname ()); g_printerr ("\n"); return 1; } res = TRUE; i = 0; do { file = g_file_new_for_commandline_arg (locations[i]); res = cat (file) && res; g_object_unref (file); } while (locations[++i] != NULL); return res ? 0 : 2; }
int main (int argc, char **argv) { GstBus *bus; GOptionContext *ctx; GIOChannel *io_stdin; GError *err = NULL; gboolean res; GOptionEntry options[] = { {NULL} }; GThread *rthread; /* Clear application state */ memset (state, 0, sizeof (*state)); state->animate = TRUE; state->current_buffer = NULL; state->caps = NULL; #if !GLIB_CHECK_VERSION (2, 31, 0) /* must initialise the threading system before using any other GLib funtion */ if (!g_thread_supported ()) g_thread_init (NULL); #endif ctx = g_option_context_new ("[ADDITIONAL ARGUMENTS]"); g_option_context_add_main_entries (ctx, options, NULL); g_option_context_add_group (ctx, gst_init_get_option_group ()); if (!g_option_context_parse (ctx, &argc, &argv, &err)) { g_print ("Error initializing: %s\n", GST_STR_NULL (err->message)); g_option_context_free (ctx); g_clear_error (&err); exit (1); } g_option_context_free (ctx); if (argc != 2) { g_print ("Usage: %s <URI> or <PIPELINE-DESCRIPTION>\n", argv[0]); exit (1); } /* Initialize GStreamer */ gst_init (&argc, &argv); /* initialize inter thread comunnication */ init_intercom (state); TRACE_VC_MEMORY ("state 0"); if (!(rthread = g_thread_new ("render", (GThreadFunc) render_func, NULL))) { g_print ("Render thread create failed\n"); exit (1); } /* Initialize player */ if (gst_uri_is_valid (argv[1])) { res = init_playbin_player (state, argv[1]); } else { res = init_parse_launch_player (state, argv[1]); } if (!res) goto done; /* Create a GLib Main Loop and set it to run */ state->main_loop = g_main_loop_new (NULL, FALSE); /* Add a keyboard watch so we get notified of keystrokes */ io_stdin = g_io_channel_unix_new (fileno (stdin)); g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc) handle_keyboard, state); g_io_channel_unref (io_stdin); /* *INDENT-OFF* */ g_print ("Available commands: \n" " a - Toggle animation \n" " p - Pause playback \n" " r - Resume playback \n" " l - Query position/duration\n" " f - Seek 30 seconds forward \n" " b - Seek 30 seconds backward \n" " q - Quit \n"); /* *INDENT-ON* */ /* Connect the bus handlers */ bus = gst_element_get_bus (state->pipeline); gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bus_sync_handler, state, NULL); gst_bus_add_signal_watch_full (bus, G_PRIORITY_HIGH); gst_bus_enable_sync_message_emission (bus); g_signal_connect (G_OBJECT (bus), "message::error", (GCallback) error_cb, state); g_signal_connect (G_OBJECT (bus), "message::buffering", (GCallback) buffering_cb, state); g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback) eos_cb, state); g_signal_connect (G_OBJECT (bus), "message::qos", (GCallback) qos_cb, state); g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback) state_changed_cb, state); gst_object_unref (bus); /* Make player start playing */ gst_element_set_state (state->pipeline, GST_STATE_PLAYING); /* Start the mainloop */ state->main_loop = g_main_loop_new (NULL, FALSE); g_main_loop_run (state->main_loop); done: /* Release pipeline */ if (state->pipeline) { gst_element_set_state (state->pipeline, GST_STATE_NULL); if (state->vsink) { gst_object_unref (state->vsink); state->vsink = NULL; } gst_object_unref (state->pipeline); } /* Unref the mainloop */ if (state->main_loop) { g_main_loop_unref (state->main_loop); } /* Stop rendering thread */ state->running = FALSE; g_thread_join (rthread); if (state->caps) { gst_caps_unref (state->caps); state->caps = NULL; } terminate_intercom (state); TRACE_VC_MEMORY ("at exit"); return 0; }
static gboolean git_evtag_builtin_sign (struct EvTag *self, int argc, char **argv, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; int r; const char *tagname; git_object *obj = NULL; git_oid specified_oid; GOptionContext *optcontext; guint64 elapsed_ns; char commit_oid_hexstr[GIT_OID_HEXSZ+1]; optcontext = g_option_context_new ("TAGNAME - Create a new GPG signed tag"); if (!option_context_parse (optcontext, sign_options, &argc, &argv, cancellable, error)) goto out; if (argc < 2) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "A TAGNAME argument is required"); goto out; } else if (argc > 2) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Too many arguments"); goto out; } tagname = argv[1]; r = git_revparse_single (&obj, self->top_repo, "HEAD"); if (!handle_libgit_ret (r, error)) goto out; specified_oid = *git_object_id (obj); git_oid_fmt (commit_oid_hexstr, &specified_oid); commit_oid_hexstr[sizeof(commit_oid_hexstr)-1] = '\0'; if (!validate_at_head (self, &specified_oid, error)) goto out; if (!checksum_commit_recurse (self, &specified_oid, &elapsed_ns, cancellable, error)) goto out; if (opt_print_only) { char *stats = get_stats (self); g_print ("%s\n", stats); g_free (stats); g_print ("%s %s\n", EVTAG_SHA512, g_checksum_get_string (self->checksum)); } else { const char *editor; int tmpfd; char *temppath; char *editor_child_argv[] = { NULL, NULL, NULL }; GPtrArray *gittag_child_argv = g_ptr_array_new (); GString *buf = g_string_new ("\n\n"); gboolean have_evtag; tmpfd = g_file_open_tmp ("git-evtag-XXXXXX.md", &temppath, error); if (tmpfd < 0) goto out; (void) close (tmpfd); g_string_append_printf (buf, "# git-evtag comment: Computed checksum in %0.1fs\n", (double)(elapsed_ns) / (double) G_USEC_PER_SEC); { char *stats = get_stats (self); g_string_append (buf, stats); g_string_append_c (buf, '\n'); g_free (stats); } g_string_append (buf, EVTAG_SHA512); g_string_append_c (buf, ' '); g_string_append (buf, g_checksum_get_string (self->checksum)); g_string_append_c (buf, '\n'); if (opt_with_legacy_archive_tag) { if (!compute_and_append_legacy_archive_checksum (commit_oid_hexstr, buf, cancellable, error)) goto out; } if (!g_file_set_contents (temppath, buf->str, -1, error)) goto out; g_string_free (buf, TRUE); editor = getenv ("EDITOR"); if (!editor) editor = "vi"; editor_child_argv[0] = (char*)editor; editor_child_argv[1] = (char*)temppath; if (!spawn_sync_require_success (editor_child_argv, G_SPAWN_SEARCH_PATH | G_SPAWN_CHILD_INHERITS_STDIN, error)) goto out; if (!check_file_has_evtag (temppath, &have_evtag, error)) goto out; if (!have_evtag) { g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Aborting tag due to deleted Git-EVTag line"); goto out; } g_ptr_array_add (gittag_child_argv, "git"); g_ptr_array_add (gittag_child_argv, "tag"); if (!opt_no_signature) g_ptr_array_add (gittag_child_argv, "-s"); if (opt_keyid) { g_ptr_array_add (gittag_child_argv, "--local-user"); g_ptr_array_add (gittag_child_argv, opt_keyid); } g_ptr_array_add (gittag_child_argv, "-F"); g_ptr_array_add (gittag_child_argv, temppath); g_ptr_array_add (gittag_child_argv, (char*)tagname); g_ptr_array_add (gittag_child_argv, (char*)commit_oid_hexstr); g_ptr_array_add (gittag_child_argv, NULL); if (!spawn_sync_require_success ((char**)gittag_child_argv->pdata, G_SPAWN_SEARCH_PATH, error)) { g_printerr ("Saved tag message in: %s\n", temppath); goto out; } (void) unlink (temppath); g_ptr_array_free (gittag_child_argv, TRUE); } ret = TRUE; out: return ret; }
/* mkfs.lhfs -l http://<path> -s name */ int main(int argc, char *argv[]) { if (log4c_init()) { g_message("log4c_init failed!"); } GError *error = NULL; GOptionContext *context; context = g_option_context_new("- mkfs hlfs"); g_option_context_add_main_entries(context, entries, NULL); g_option_context_set_help_enabled(context, TRUE); g_option_group_set_error_hook(g_option_context_get_main_group(context), (GOptionErrorFunc)error_func); if (!g_option_context_parse(context, &argc, &argv, &error)) { g_message("option parsing failed: %s", error->message); exit(EXIT_FAILURE); } //g_print("location is :%s\n",location); //g_print("fsname is :%s\n",fsname); //g_print("block size is :%d\n",block_size); //g_print("segment size is :%d\n",seg_size); // seg_size = SEGMENT_SIZE; if(seg_size <= 0 || seg_size%(1024*1024)!=0){ g_message("segsize <=0 or segment size must 1M margin"); return -1; } if(block_size <=0 || block_size%(512) != 0){ g_message("blocksize <=0 or block size must 512 margin"); return -1; } if(max_fs_size <=0){ g_message("max fs size <=0"); return -1; } struct back_storage *storage = init_storage_handler(uri); if(NULL ==storage){ g_message("can not get storage handler for uri:%s",uri); g_option_context_free(context); return -1; } if((0==storage->bs_file_is_exist(storage,NULL)) && (0==storage->bs_file_is_exist(storage,"superblock"))){ g_message("hlfs with uri:%s has exist",uri); g_option_context_free(context); return 1; } if( 0!=storage->bs_file_mkdir(storage,NULL)){ g_message("can not mkdir for our fs %s",uri); g_option_context_free(context); return -1; } GKeyFile *sb_keyfile= g_key_file_new(); g_key_file_set_string(sb_keyfile,"METADATA","uri",uri); g_key_file_set_integer(sb_keyfile,"METADATA","block_size",block_size); g_key_file_set_integer(sb_keyfile,"METADATA","segment_size",seg_size); g_key_file_set_uint64(sb_keyfile,"METADATA","max_fs_size",max_fs_size); gchar *data = g_key_file_to_data(sb_keyfile,NULL,NULL); g_message("key file data :%s",data); char *head,*hostname,*dir,*fs_name; int port; parse_from_uri(uri,&head,&hostname,&dir,&fs_name,&port); char *sb_file_path = g_build_filename(dir,fs_name,"superblock",NULL); g_message("sb file path %s",sb_file_path); bs_file_t file = storage->bs_file_create(storage,"superblock"); g_message("sb file path 1%s",sb_file_path); //bs_file_t file = storage->bs_file_open(storage,"superblock",BS_WRITEABLE); if (NULL == file) { g_message("open file :superblock failed"); g_free(sb_file_path); g_option_context_free(context); return -1; } g_message("sb file path 2%s",sb_file_path); int size = storage->bs_file_append(storage, file,(char*)data,strlen(data)+1); if(size != strlen(data)+1){ g_message("can not write superblock file"); g_free(sb_file_path); g_option_context_free(context); return -1; } g_message("append size:%d",size); storage->bs_file_flush(storage,file); storage->bs_file_close(storage,file); deinit_storage_handler(storage); if (log4c_fini()) { g_message("log4c_fini failed!"); } return 0; }
int main(int argc, char *argv[]) { int ret = -1; int lockfd = -1; gboolean foreground = FALSE; gboolean force_local_mode = FALSE; gboolean wrote_pidfile = FALSE; memdb_t *memdb = NULL; dfsm_t *dcdb = NULL; dfsm_t *status_fsm = NULL; qb_log_init("pmxcfs", LOG_DAEMON, LOG_DEBUG); /* remove default filter */ qb_log_filter_ctl(QB_LOG_SYSLOG, QB_LOG_FILTER_REMOVE, QB_LOG_FILTER_FILE, "*", LOG_DEBUG); qb_log_tags_stringify_fn_set(log_tags_stringify); qb_log_ctl(QB_LOG_STDERR, QB_LOG_CONF_ENABLED, QB_TRUE); update_qb_log_settings(); g_set_print_handler(glib_print_handler); g_set_printerr_handler(glib_print_handler); g_log_set_default_handler(glib_log_handler, NULL); GOptionContext *context; GOptionEntry entries[] = { { "debug", 'd', 0, G_OPTION_ARG_NONE, &cfs.debug, "Turn on debug messages", NULL }, { "foreground", 'f', 0, G_OPTION_ARG_NONE, &foreground, "Do not daemonize server", NULL }, { "local", 'l', 0, G_OPTION_ARG_NONE, &force_local_mode, "Force local mode (ignore cluster.conf, force quorum)", NULL }, { NULL }, }; context = g_option_context_new (""); g_option_context_add_main_entries (context, entries, NULL); GError *err = NULL; if (!g_option_context_parse (context, &argc, &argv, &err)) { cfs_critical("option parsing failed: %s", err->message); g_error_free (err); qb_log_fini(); exit (1); } g_option_context_free(context); if (optind < argc) { cfs_critical("too many arguments"); qb_log_fini(); exit(-1); } if (cfs.debug) { update_qb_log_settings(); } struct utsname utsname; if (uname(&utsname) != 0) { cfs_critical("Unable to read local node name"); qb_log_fini(); exit (-1); } for (int i=0; i < sizeof(utsname.nodename); i++) { if (utsname.nodename[i] =='.') utsname.nodename[i] = 0; } cfs.nodename = g_strdup(utsname.nodename); if (!(cfs.ip = lookup_node_ip(cfs.nodename))) { cfs_critical("Unable to get local IP address"); qb_log_fini(); exit(-1); } struct group *www_data = getgrnam("www-data"); if (!www_data) { cfs_critical("Unable to get www-data group ID"); qb_log_fini(); exit (-1); } cfs.gid = www_data->gr_gid; g_thread_init(NULL); umask(027); mkdir(VARLIBDIR, 0755); if ((lockfd = open(LOCKFILE, O_RDWR|O_CREAT|O_APPEND)) == -1) { cfs_critical("unable to create lock '%s': %s", LOCKFILE, strerror (errno)); goto err; } for (int i = 10; i >= 0; i--) { if (flock(lockfd, LOCK_EX|LOCK_NB) != 0) { if (!i) { cfs_critical("unable to aquire pmxcfs lock: %s", strerror (errno)); goto err; } if (i == 10) cfs_message("unable to aquire pmxcfs lock - trying again"); sleep(1); } } cfs_status_init(); gboolean create = !g_file_test(DBFILENAME, G_FILE_TEST_EXISTS); if (!(memdb = memdb_open (DBFILENAME))) { cfs_critical("memdb_open failed - unable to open database '%s'", DBFILENAME); goto err; } // automatically import cluster.conf from host if (create && !force_local_mode) { char *cdata = NULL; gsize clen = 0; if (g_file_get_contents(HOST_CLUSTER_CONF_FN, &cdata, &clen, NULL)) { guint32 mtime = time(NULL); memdb_create(memdb, "/cluster.conf", 0, mtime); if (memdb_write(memdb, "/cluster.conf", 0, mtime, cdata, clen, 0, 1) < 0) { cfs_critical("memdb_write failed - unable to import cluster.conf"); goto err; } } } // does cluster.conf exist? gpointer conf_data = NULL; int len = memdb_read(memdb, "cluster.conf", &conf_data); if (len >= 0) { if (force_local_mode) { cfs_message("forcing local mode (althought cluster.conf exists)"); cfs_set_quorate(1, TRUE); } else { if (!(dcdb = dcdb_new(memdb))) goto err; dcdb_sync_cluster_conf(memdb, 1); } } else { cfs_debug("using local mode (cluster.conf does not exist)"); cfs_set_quorate(1, TRUE); } if (conf_data) g_free(conf_data); cfs_plug_memdb_t *config = cfs_plug_memdb_new("memdb", memdb, dcdb); cfs_plug_base_t *bplug = cfs_plug_base_new("", (cfs_plug_t *)config); create_symlinks(bplug, cfs.nodename); root_plug = (cfs_plug_t *)bplug; system("umount -f " CFSDIR " >/dev/null 2>&1"); char *fa[] = { "-f", "-odefault_permissions", "-oallow_other", NULL}; struct fuse_args fuse_args = FUSE_ARGS_INIT(sizeof (fa)/sizeof(gpointer) - 1, fa); struct fuse_chan *fuse_chan = fuse_mount(CFSDIR, &fuse_args); if (!fuse_chan) { cfs_critical("fuse_mount error: %s", strerror(errno)); goto err; } if (!(fuse = fuse_new(fuse_chan, &fuse_args, &fuse_ops, sizeof(fuse_ops), NULL))) { cfs_critical("fuse_new error: %s", strerror(errno)); goto err; } fuse_set_signal_handlers(fuse_get_session(fuse)); if (!foreground) { pid_t cpid = fork(); if (cpid == -1) { cfs_critical("failed to daemonize program - %s", strerror (errno)); goto err; } else if (cpid) { write_pidfile(cpid); qb_log_fini(); _exit (0); } else { int nullfd; chroot("/"); if ((nullfd = open("/dev/null", O_RDWR, 0)) != -1) { dup2(nullfd, 0); dup2(nullfd, 1); dup2(nullfd, 2); if (nullfd > 2) close (nullfd); } // do not print to the console after this point qb_log_ctl(QB_LOG_STDERR, QB_LOG_CONF_ENABLED, QB_FALSE); setsid(); } } else { write_pidfile(getpid()); } wrote_pidfile = TRUE; cfs_loop_t *corosync_loop = cfs_loop_new(fuse); cfs_service_t *service_quorum = NULL; cfs_service_t *service_confdb = NULL; cfs_service_t *service_dcdb = NULL; cfs_service_t *service_status = NULL; if (dcdb) { service_quorum = service_quorum_new(); cfs_loop_add_service(corosync_loop, service_quorum, QB_LOOP_HIGH); service_confdb = service_confdb_new(); cfs_loop_add_service(corosync_loop, service_confdb, QB_LOOP_MED); service_dcdb = service_dfsm_new(dcdb); cfs_service_set_timer(service_dcdb, DCDB_VERIFY_TIME); cfs_loop_add_service(corosync_loop, service_dcdb, QB_LOOP_MED); status_fsm = cfs_status_dfsm_new(); service_status = service_dfsm_new(status_fsm); cfs_loop_add_service(corosync_loop, service_status, QB_LOOP_LOW); } cfs_loop_start_worker(corosync_loop); server_start(memdb); ret = fuse_loop_mt(fuse); cfs_message("teardown filesystem"); server_stop(); fuse_unmount(CFSDIR, fuse_chan); fuse_destroy(fuse); cfs_debug("set stop event loop flag"); cfs_loop_stop_worker(corosync_loop); cfs_loop_destroy(corosync_loop); cfs_debug("worker finished"); if (service_dcdb) service_dfsm_destroy(service_dcdb); if (service_confdb) service_confdb_destroy(service_confdb); if (service_quorum) service_quorum_destroy(service_quorum); if (service_status) service_dfsm_destroy(service_status); sleep(1); /* do not restart too fast */ ret: if (status_fsm) dfsm_destroy(status_fsm); if (dcdb) dfsm_destroy(dcdb); if (memdb) memdb_close(memdb); if (wrote_pidfile) unlink(CFS_PID_FN); cfs_message("exit proxmox configuration filesystem (%d)", ret); cfs_status_cleanup(); qb_log_fini(); exit(ret); err: goto ret; }
int main(int argc, char **argv) { XmrApp *app; GOptionContext *context; GError *error = NULL; PlayerAction player_action = ActionNone; gchar *tmp_dir = NULL; #if !GLIB_CHECK_VERSION(2, 32, 0) g_thread_init(NULL); #endif gdk_threads_init(); g_type_init(); setlocale(LC_ALL, NULL); #ifdef ENABLE_NLS /* initialize i18n */ bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); textdomain(GETTEXT_PACKAGE); #endif context = g_option_context_new(NULL); g_option_context_add_main_entries(context, options, GETTEXT_PACKAGE); g_option_context_add_group(context, gtk_get_option_group(TRUE)); g_option_context_add_group(context, gst_init_get_option_group()); if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) { g_print(_("%s\nRun '%s --help' to see a full list of available command line options.\n"), error->message, argv[0]); g_error_free(error); g_option_context_free(context); exit(1); } g_option_context_free(context); if (action_play){ player_action = ActionPlay; }else if (action_pause){ player_action = ActionPause; }else if(action_next){ player_action = ActionNext; }else if(action_love){ player_action = ActionLove; }else if(action_hate){ player_action = ActionHate; } if (player_action != ActionNone) { DBusConnection *bus; DBusError dbus_error; dbus_error_init(&dbus_error); bus = dbus_bus_get(DBUS_BUS_SESSION, &dbus_error); if (!bus) { g_warning ("Failed to connect to the D-BUS daemon: %s", dbus_error.message); dbus_error_free(&dbus_error); exit(1); } dbus_connection_setup_with_g_main(bus, NULL); send_action(bus, player_action); // exit directly return 0; } xmr_debug_enable(debug); gst_init(&argc, &argv); gdk_threads_init(); curl_global_init(CURL_GLOBAL_ALL); // this make our XmrRadio always works g_object_set(gtk_settings_get_default(), "gtk-button-images", TRUE, NULL); // ensure folder exists tmp_dir = g_strdup_printf("%s/%s", g_get_tmp_dir(), PACKAGE); g_mkdir_with_parents(tmp_dir, 0755); app = xmr_app_new(); g_application_run(G_APPLICATION(app), argc, argv); // remove ... list_file(tmp_dir, FALSE, remove_file, NULL); g_free(tmp_dir); g_object_unref(app); curl_global_cleanup(); return 0; }
int main(int argc, char **argv) { GOptionContext *context; GError *error = NULL; gint res; context = g_option_context_new("<application> [app arguments]"); g_option_context_add_main_entries(context, entries, NULL); g_option_context_set_summary(context, PACKAGE_DESC); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_printerr("Option parsing failed: %s\n", error->message); return -1; } if (opts.show_version) { g_printerr(PACKAGE_DESC); g_printerr("\nBuild-Date: " __DATE__ " " __TIME__ "\n"); return 0; } if (!opts.app || !opts.app[0]) { g_printerr("Missing application\n"); return -2; } if (opts.forks < 1) { g_printerr("Invalid forks argument: %i\n", opts.forks); return -3; } if (opts.retry < 1) { g_printerr("Invalid retry argument: %i\n", opts.retry); return -4; } if (opts.retry_timeout_ms < 0) { g_printerr("Invalid timeout argument: %i\n", opts.retry_timeout_ms); return -5; } data *d = g_slice_new0(data); d->children = (child*) g_slice_alloc0(sizeof(child) * opts.forks); d->running = 0; d->shutdown = FALSE; d->return_status = 0; d->loop = ev_default_loop(0); #define WATCH_SIG(x) do { ev_signal_init(&d->sig##x, forward_sig_cb, SIG##x); d->sig##x.data = d; ev_signal_start(d->loop, &d->sig##x); ev_unref(d->loop); } while (0) #define WATCH_TERM_SIG(x) do { ev_signal_init(&d->sig##x, terminate_forward_sig_cb, SIG##x); d->sig##x.data = d; ev_signal_start(d->loop, &d->sig##x); ev_unref(d->loop); } while (0) #define UNWATCH_SIG(x) do { ev_ref(d->loop); ev_signal_stop(d->loop, &d->sig##x); } while (0) WATCH_TERM_SIG(HUP); WATCH_TERM_SIG(INT); WATCH_TERM_SIG(QUIT); WATCH_TERM_SIG(TERM); WATCH_TERM_SIG(USR1); WATCH_SIG(USR2); for (gint i = 0; i < opts.forks; i++) { d->children[i].d = d; d->children[i].id = i; d->children[i].pid = -1; d->children[i].tries = 0; d->children[i].watcher.data = &d->children[i]; ev_child_init(&d->children[i].watcher, child_died, -1, 0); spawn(&d->children[i]); } ev_loop(d->loop, 0); res = d->return_status; g_slice_free1(sizeof(child) * opts.forks, d->children); g_slice_free(data, d); UNWATCH_SIG(HUP); UNWATCH_SIG(INT); UNWATCH_SIG(QUIT); UNWATCH_SIG(TERM); UNWATCH_SIG(USR1); UNWATCH_SIG(USR2); return res; }
static gboolean local_cmdline (GApplication *app, gchar ***arguments, gint *exit_status) { gint i; gchar **argv; gint argc = 0; gboolean retval = TRUE; GError *error = NULL; GOptionContext *optcontext; GOptionEntry options[] = { { "hidden", 'h', 0, G_OPTION_ARG_NONE, &hidden, N_("Don’t display any dialogs; do any work (e.g. importing) and exit"), NULL }, { "if-needed", 'n', 0, G_OPTION_ARG_NONE, &only_if_needed, N_("Don’t display any dialogs unless there are only “People Nearby” accounts"), NULL }, { "select-account", 's', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_STRING, &selected_account_name, N_("Initially select given account (eg, " "gabble/jabber/foo_40example_2eorg0)"), N_("<account-id>") }, { NULL } }; optcontext = g_option_context_new (N_("— Empathy Accounts")); g_option_context_add_group (optcontext, gtk_get_option_group (FALSE)); g_option_context_add_main_entries (optcontext, options, GETTEXT_PACKAGE); g_option_context_set_translation_domain (optcontext, GETTEXT_PACKAGE); argv = *arguments; for (i = 0; argv[i] != NULL; i++) argc++; if (!g_option_context_parse (optcontext, &argc, &argv, &error)) { g_print ("%s\nRun '%s --help' to see a full list of available command line options.\n", error->message, argv[0]); g_warning ("Error in empathy init: %s", error->message); g_clear_error (&error); *exit_status = EXIT_FAILURE; } else { if (g_application_register (app, NULL, &error)) { g_application_activate (app); } else { g_warning ("Impossible to register empathy-application: %s", error->message); g_clear_error (&error); *exit_status = EXIT_FAILURE; } } g_option_context_free (optcontext); return retval; }
gint main(int argc,char *argv[]) { GError* error = NULL; gchar* program_name; gboolean mode_1d; g_thread_init( NULL ); eh_init_glib(); { GOptionContext* context = g_option_context_new( "Run hyperpycnal flow model." ); g_option_context_add_main_entries( context , entries , NULL ); if ( !g_option_context_parse( context , &argc , &argv , &error ) ) eh_error( "Error parsing command line arguments: %s" , error->message ); } _day *= S_SECONDS_PER_DAY; if ( _version ) { eh_fprint_version_info( stdout , "sakura" , 0 , 9 , 0 ); eh_exit(0); } if ( _debug ) g_setenv( "SAKURA_DEBUG" , "TRUE" , TRUE ); program_name = g_path_get_basename( argv[0] ); if ( strcasecmp( program_name , "sakura")==0 ) { _angle = 0.; mode_1d = TRUE; } if ( _verbose ) { if ( mode_1d ) eh_info( "Operating in 1D mode (ignoring width information)." ); else eh_info( "Operating in 1.5D mode." ); eh_info( "Duration of flow (days) : %f" , _day*S_DAYS_PER_SECOND ); eh_info( "Spreading angle (degrees) : %f" , _angle ); } if ( !error ) { gint i; Sakura_param_st* param = NULL; Sakura_bathy_st* bathy_data = NULL; Sakura_bathy_st* bathy_data_0 = NULL; Sakura_flood_st** flood_data = NULL; Sakura_const_st* const_data = NULL; Sakura_sediment_st* sediment_data = NULL; Eh_dbl_grid deposit; Eh_dbl_grid total_deposit; const double spreading_angle = tan(_angle*G_PI/180.); if ( ( param = sakura_scan_parameter_file( _in_file , &error ) )==NULL || ( flood_data = sakura_scan_flood_file ( _flood_file , param , &error ) )==NULL || ( bathy_data_0 = sakura_scan_bathy_file ( _bathy_file , param , &error ) )==NULL ) eh_error( "%s" , error->message ); bathy_data = sakura_copy_bathy_data ( NULL , bathy_data_0 ); const_data = sakura_set_constant_data ( param , bathy_data ); const_data = sakura_set_constant_output_data( const_data , _data_file , _data_id , _data_int ); sediment_data = sakura_set_sediment_data ( param ); deposit = eh_grid_new( double , sediment_data->n_grains , bathy_data->len ); total_deposit = eh_grid_new( double , sediment_data->n_grains , bathy_data->len ); for ( i=0 ; flood_data[i] ; i++ ) { /* Run each day of the flood */ /* The width starts at the river width for each day */ sakura_set_width( bathy_data , flood_data[i]->width , spreading_angle ); sakura_run_flood( bathy_data , flood_data[i] , sediment_data , const_data , eh_dbl_grid_data(deposit) ); eh_dbl_grid_add( total_deposit , deposit ); if ( _data_file ) sakura_write_data ( _data_file , deposit ); if ( _reset_bathy ) sakura_copy_bathy_data( bathy_data , bathy_data_0 ); } sakura_write_output( _out_file , bathy_data , eh_dbl_grid_data(total_deposit) , sediment_data->n_grains ); eh_grid_destroy( total_deposit , TRUE ); eh_grid_destroy( deposit , TRUE ); }
int main(int argc, char **argv) { int month, day, year; int day_array[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; struct tm new_tm_time; SaErrorT rv; SaHpiSessionIdT sessionid; SaHpiDomainInfoT domainInfo; SaHpiRptEntryT rptentry; SaHpiEntryIdT rptentryid; SaHpiEntryIdT nextrptentryid; SaHpiResourceIdT resourceid; SaHpiTimeT oldtime; SaHpiTimeT newtime; SaHpiTimeT readbacktime; SaHpiTextBufferT buffer; GOptionContext *context; /* Print version strings */ oh_prog_version(argv[0]); /* Parsing options */ static char usetext[]="- Exercises Event Log clock APIs.\n " OH_SVN_REV; OHC_PREPARE_REVISION(usetext); context = g_option_context_new (usetext); g_option_context_add_main_entries (context, my_options, NULL); if (!ohc_option_parse(&argc, argv, context, &copt, OHC_ALL_OPTIONS - OHC_ENTITY_PATH_OPTION // not applicable - OHC_VERBOSE_OPTION )) { // no verbose mode g_option_context_free (context); EXIT1; } g_option_context_free (context); if ( !findate || !fintime) { CRIT("Please enter date and time to be set, or try --help."); EXIT1; } if (findate) { if (copt.debug) printf("New date to be set: %s\n",findate); if (sscanf(findate,"%2d/%2d/%4d", &month, &day, &year) != 3) { CRIT("%s: Invalid date", argv[0]); EXIT1; } /* check month, day and year for correctness */ if ((month < 1) || (month > 12)) { CRIT("%s: Month out of range: (%d)", argv[0], month); EXIT1; }; if (year < 1900) { CRIT("%s: Year out of range: (%d)", argv[0], year); EXIT1; }; month--; if (month == 1) { /* if the given year is a leap year */ if ((((year % 4) == 0) && ((year % 100) != 0)) || ((year % 400) == 0)) day_array[1] = 29; }; if ((day < 1) || (day > day_array[month])) { CRIT("%s: Day out of range: (%d)", argv[0], day); EXIT1; }; new_tm_time.tm_mon = month; new_tm_time.tm_mday = day; new_tm_time.tm_year = year - 1900; } if (fintime) { if (copt.debug) DBG("New time to be set: %s",fintime); if (sscanf(fintime,"%2d:%2d:%2d", &new_tm_time.tm_hour, &new_tm_time.tm_min, &new_tm_time.tm_sec) != 3) { CRIT("%s: Invalid time", argv[0]); EXIT1; } /* check hours, minutes and seconds for correctness */ if ((new_tm_time.tm_hour < 0) || (new_tm_time.tm_hour > 24)) { CRIT("%s: Hours out of range: (%d)", argv[0], new_tm_time.tm_hour); EXIT1; }; if ((new_tm_time.tm_min < 0) || (new_tm_time.tm_min > 60)) { CRIT("%s: Minutes out of range: (%d)", argv[0], new_tm_time.tm_min); EXIT1; }; if ((new_tm_time.tm_sec < 0) || (new_tm_time.tm_sec > 60)) { CRIT("%s: Seconds out of range: (%d)", argv[0], new_tm_time.tm_sec); EXIT1; } } if (copt.debug) DBG("Values passed to mktime():\n\tmon %d\n\tday %d\n\tyear %d\n\tHH %d\n\tMM %d\n\tSS %d", new_tm_time.tm_mon, new_tm_time.tm_mday, new_tm_time.tm_year, new_tm_time.tm_hour, new_tm_time.tm_min, new_tm_time.tm_sec); newtime = (SaHpiTimeT) mktime(&new_tm_time) * 1000000000; if (copt.debug) DBG("New date and time in SaHpiTimeT %" PRId64 "\n", (int64_t)newtime); rv = ohc_session_open_by_option ( &copt, &sessionid); if (rv != SA_OK) EXIT1; if (copt.debug) DBG("saHpiDiscover"); rv = saHpiDiscover(sessionid); if (copt.debug) DBG("saHpiDiscover %s", oh_lookup_error(rv)); rv = saHpiDomainInfoGet(sessionid, &domainInfo); if (copt.debug) DBG("saHpiDomainInfoGet %s", oh_lookup_error(rv)); printf("DomainInfo: RptUpdateCount = %u, RptUpdateTimestamp = %lx\n", domainInfo.RptUpdateCount, (unsigned long)domainInfo.RptUpdateTimestamp); /* walk the RPT list */ rptentryid = SAHPI_FIRST_ENTRY; while ((rv == SA_OK) && (rptentryid != SAHPI_LAST_ENTRY)) { rv = saHpiRptEntryGet(sessionid,rptentryid,&nextrptentryid,&rptentry); if (copt.debug) DBG("saHpiRptEntryGet %s", oh_lookup_error(rv)); if ((rv == SA_OK) && (rptentry.ResourceCapabilities & SAHPI_CAPABILITY_EVENT_LOG)) { resourceid = rptentry.ResourceId; if (copt.debug) DBG("RPT %x capabilities = %x", resourceid, rptentry.ResourceCapabilities); rv = saHpiEventLogTimeGet(sessionid, resourceid, &oldtime); oh_decode_time(oldtime, &buffer); printf ("\nCurrent event log time on HPI target: %s\n", buffer.Data); printf ("Setting new event log time on HPI target ...\n"); rv = saHpiEventLogTimeSet(sessionid, resourceid, newtime); if (rv != SA_OK) { CRIT("saHpiEventLogTimeSet returned %s", oh_lookup_error(rv)); } rv = saHpiEventLogTimeGet(sessionid, resourceid, &readbacktime); oh_decode_time(readbacktime, &buffer); printf ("Read-Back-Check event log time: %s\n", buffer.Data); } // entryid = SAHPI_OLDEST_ENTRY; rptentryid = nextrptentryid; } rv = saHpiSessionClose(sessionid); g_free(findate); g_free(fintime); return(0); }
int main (int argc, char **argv) { int was_result_written = 0; int pass; /* This was to move gslice area out of the tree of Marpa calls during memory debugging */ /* void* dummy = g_slice_alloc(42); */ /* g_slice_free1(42, dummy); */ GError *error = NULL; GOptionContext *context; char *test_string; context = g_option_context_new ("- test balanced parens"); g_option_context_add_main_entries (context, entries, NULL); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_print ("option parsing failed: %s\n", error->message); exit (1); } if (string) { /* Never freed */ test_string = string; string_length = strlen (test_string); printf ("Target is \"%s\", length=%d\n", test_string, string_length); } else if (string_length < 10) { fprintf (stderr, "String length is %d, must be at least 10\n", string_length); exit (1); } else { /* Never freed */ test_string = gen_example_string (string_length); printf ("Target at end, length=%d\n", string_length); } for (pass = 0; pass < repeats; pass++) { int location; int start_of_match = -1; int end_of_match = -1; Marpa_Symbol_ID s_top, s_prefix, s_first_balanced; Marpa_Symbol_ID s_prefix_char, s_balanced; Marpa_Symbol_ID s_balanced_sequence; struct marpa_g *g; struct marpa_r *r; void *result; /* Longest rule is 4 symbols */ Marpa_Symbol_ID rhs[4]; g = marpa_g_new (); s_top = marpa_symbol_new (g); s_prefix = marpa_symbol_new (g); s_first_balanced = marpa_symbol_new (g); s_prefix_char = marpa_symbol_new (g); s_balanced = marpa_symbol_new (g); s_lparen = marpa_symbol_new (g); s_rparen = marpa_symbol_new (g); s_balanced_sequence = marpa_symbol_new (g); rhs[0] = s_prefix; rhs[1] = s_first_balanced; marpa_rule_new (g, s_top, rhs, 2); marpa_sequence_new (g, s_prefix, s_prefix_char, -1, 0, 0); rhs[0] = s_balanced; marpa_rule_new (g, s_first_balanced, rhs, 1); rhs[0] = s_lparen; rhs[1] = s_rparen; marpa_rule_new (g, s_balanced, rhs, 2); rhs[0] = s_lparen; rhs[1] = s_balanced_sequence; rhs[2] = s_rparen; marpa_rule_new (g, s_balanced, rhs, 3); marpa_sequence_new (g, s_balanced_sequence, s_balanced, -1, 1, 0); marpa_symbol_is_terminal_set (g, s_prefix_char, 1); marpa_symbol_is_terminal_set (g, s_lparen, 1); marpa_symbol_is_terminal_set (g, s_rparen, 1); marpa_start_symbol_set (g, s_top); result = marpa_precompute (g); if (!result) { puts (marpa_g_error (g)); exit (1); } { int AHFA_state_count = marpa_AHFA_state_count (g); int ahfa_id; first_balanced_completion = -1; for (ahfa_id = 0; ahfa_id < AHFA_state_count; ahfa_id++) { unsigned int aim_ix; unsigned int aim_count = marpa_AHFA_state_item_count (g, ahfa_id); for (aim_ix = 0; aim_ix < aim_count; aim_ix++) { int aim_id = marpa_AHFA_state_item (g, ahfa_id, aim_ix); int position = marpa_AHFA_item_position (g, aim_id); if (position == -1) { Marpa_Rule_ID rule = marpa_AHFA_item_rule (g, aim_id); Marpa_Symbol_ID lhs = marpa_rule_lhs (g, rule); if (lhs == s_first_balanced) { if (first_balanced_completion != -1) { fprintf (stderr, "First balanced completion is not unique"); exit (1); } first_balanced_completion = ahfa_id; break; } } } } } r = create_recce (g); for (location = 0; location <= string_length; location++) { int origin, status; Marpa_Symbol_ID paren_token = test_string[location] == '(' ? s_lparen : s_rparen; status = marpa_alternative (r, paren_token, 0, 1); if (status < -1) fatal_r_error ("marpa alternative", r, status); status = marpa_alternative (r, s_prefix_char, 0, 1); if (status < -1) fatal_r_error ("marpa alternative", r, status); status = marpa_earleme_complete (r); if (status < -1) fatal_r_error ("marpa_earleme_complete", r, status); /* If none of the alternatives were accepted, we are done */ origin = at_first_balanced_completion (r, location + 1); if (origin >= 0) { start_of_match = origin; end_of_match = location + 1; break; } } if (start_of_match < 0) { printf ("No balanced parens\n"); } while (++location < string_length) { int origin, status, earleme_complete_status; Marpa_Symbol_ID paren_token = test_string[location] == '(' ? s_lparen : s_rparen; status = marpa_alternative (r, paren_token, 0, 1); if (status == -1) break; if (status < -1) fatal_r_error ("marpa alternative", r, status); earleme_complete_status = marpa_earleme_complete (r); if (earleme_complete_status < -1) fatal_r_error ("marpa_earleme_complete", r, earleme_complete_status); origin = at_first_balanced_completion (r, location + 1); if (origin >= 0 && origin < start_of_match) { start_of_match = origin; end_of_match = location + 1; break; } if (earleme_complete_status == 0) break; } if (!was_result_written) { printf ("Match at %d-%d\n", start_of_match, end_of_match); was_result_written++; } marpa_r_free (r); marpa_g_free (g); g = NULL; } exit (0); }
gint main (gint argc, gchar **argv) { setlocale (LC_ALL, ""); GOptionContext *context = g_option_context_new ("- ibus daemon"); g_option_context_add_main_entries (context, entries, "ibus-daemon"); g_argv = g_strdupv (argv); GError *error = NULL; if (!g_option_context_parse (context, &argc, &argv, &error)) { g_printerr ("Option parsing failed: %s\n", error->message); g_error_free (error); exit (-1); } if (g_gdbus_timeout < -1) { g_printerr ("Bad timeout (must be >= -1): %d\n", g_gdbus_timeout); exit (-1); } if (g_mempro) { g_mem_set_vtable (glib_mem_profiler_table); signal (SIGUSR2, _sig_usr2_handler); } /* check uid */ { const gchar *username = ibus_get_user_name (); uid_t uid = getuid (); struct passwd *pwd = getpwuid (uid); if (pwd == NULL || g_strcmp0 (pwd->pw_name, username) != 0) { g_printerr ("Please run ibus-daemon with login user! Do not run ibus-daemon with sudo or su.\n"); exit (-1); } } /* daemonize process */ if (daemonize) { if (daemon (1, 0) != 0) { g_printerr ("Can not daemonize ibus.\n"); exit (-1); } } /* create a new process group. this is important to kill all of its children by SIGTERM at a time in bus_ibus_impl_destroy. */ setpgid (0, 0); ibus_init (); ibus_set_log_handler (g_verbose); /* check if ibus-daemon is running in this session */ if (ibus_get_address () != NULL) { IBusBus *bus = ibus_bus_new (); if (ibus_bus_is_connected (bus)) { if (!replace) { g_printerr ("current session already has an ibus-daemon.\n"); exit (-1); } ibus_bus_exit (bus, FALSE); while (ibus_bus_is_connected (bus)) { g_main_context_iteration (NULL, TRUE); } } g_object_unref (bus); } bus_server_init (); if (!single) { /* execute config component */ if (g_strcmp0 (config, "default") == 0) { BusComponent *component; component = bus_registry_lookup_component_by_name (BUS_DEFAULT_REGISTRY, IBUS_SERVICE_CONFIG); if (component) { bus_component_set_restart (component, restart); } if (component == NULL || !bus_component_start (component, g_verbose)) { g_printerr ("Can not execute default config program\n"); exit (-1); } } else if (g_strcmp0 (config, "disable") != 0 && g_strcmp0 (config, "") != 0) { if (!execute_cmdline (config)) exit (-1); } /* execute panel component */ if (g_strcmp0 (panel, "default") == 0) { BusComponent *component; component = bus_registry_lookup_component_by_name (BUS_DEFAULT_REGISTRY, IBUS_SERVICE_PANEL); if (component) { bus_component_set_restart (component, restart); } if (component == NULL || !bus_component_start (component, g_verbose)) { g_printerr ("Can not execute default panel program\n"); exit (-1); } } else if (g_strcmp0 (panel, "disable") != 0 && g_strcmp0 (panel, "") != 0) { if (!execute_cmdline (panel)) exit (-1); } } /* execute ibus xim server */ if (xim) { if (!execute_cmdline (LIBEXECDIR "/ibus-x11 --kill-daemon")) exit (-1); } bus_server_run (); return 0; }
int main (int argc, char *argv[]) { g_type_init(); #ifdef GOIS GOptionContext *ctx; GError *error = NULL; ctx = g_option_context_new (NULL); g_option_context_add_group (ctx, g_irepository_get_option_group ()); if (!g_option_context_parse (ctx, &argc, &argv, &error)) { g_print ("swimmer: %s\n", error->message); // exit(1); } #endif /* * Prior to any use of the type system, g_type_init() has to be called * to initialize the type system and assorted other code portions * (such as the various fundamental type implementations or the signal * system). */ /* Create our object */ NatureAnimal *an = nature_animal_new("Animal", 12); //SwimmerSw *sw = g_object_new(SWIMMER_TYPE, NULL); an->age += 1; g_print("incremented animal->age: %d\n", an->age); /* Call object method */ nature_animal_eat(an, "helowrld"); nature_animal_cry(an, "test"); my_int num = 110183; nature_animal_myint(an, num); nature_animal_uint(an, num*2); nature_animal_get_data(an); g_object_unref(an); // nature_animal_do_action(sw); printf("\n\n"); NatureAnimal *m = nature_monkey_new("Monkey", 10); nature_animal_eat(m, "eat_monkey"); nature_animal_cry(m, "cry monkey"); nature_animal_get_data(m); m->age += 3; nature_animal_get_data(m); // nature_animal_do_action(m); nature_monkey_print_private(m); nature_monkey_set_private(m, "gorilla", "afrika"); nature_monkey_print_private(m); g_object_unref(m); printf("\n"); NatureAnimal *h = mankind_human_new("Jack", 30); nature_animal_eat(h, "eat_human"); nature_animal_cry(h, "cry human"); nature_animal_get_data(h); int r =9; int *arr; nature_animal_pint(h, &r, &arr); printf("r = %d\n", r); printf("arr[0] = %d\n", arr[0]); printf("arr[1] = %d\n", arr[1]); mankind_human_print_private(h); /* printf("\n"); DigitalComp *dc = digital_comp_new("Jack", 30); digital_comp_compute(dc, "comp compute"); digital_comp_reboot(dc, "comp reboot"); digital_comp_halt(dc); */ (void) argc; (void) argv; return 0; }
static void test_g_option_context (void) { g_autoptr(GOptionContext) val = g_option_context_new ("hello"); g_assert (val != NULL); }
int main (int argc, char **argv) { gchar exe_path[PATH_MAX+1]; ssize_t exe_path_len; gboolean replace; gboolean verbose; gboolean show_version; GBusNameOwnerFlags flags; GOptionContext *context; g_autoptr(GError) error = NULL; const GOptionEntry options[] = { { "replace", 'r', 0, G_OPTION_ARG_NONE, &replace, "Replace old daemon.", NULL }, { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Enable debug output.", NULL }, { "session", 0, 0, G_OPTION_ARG_NONE, &on_session_bus, "Run in session, not system scope (for tests).", NULL }, { "no-idle-exit", 0, 0, G_OPTION_ARG_NONE, &no_idle_exit, "Don't exit when idle.", NULL }, { "version", 0, 0, G_OPTION_ARG_NONE, &show_version, "Show program version.", NULL}, { NULL } }; setlocale (LC_ALL, ""); g_setenv ("GIO_USE_VFS", "local", TRUE); g_set_prgname (argv[0]); g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, message_handler, NULL); context = g_option_context_new (""); g_option_context_set_summary (context, "Flatpak system helper"); g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE); replace = FALSE; verbose = FALSE; show_version = FALSE; if (!g_option_context_parse (context, &argc, &argv, &error)) { 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_option_context_free (context); return 1; } if (show_version) { g_print (PACKAGE_STRING "\n"); return 0; } if (verbose) g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, message_handler, NULL); authority = polkit_authority_get_sync (NULL, &error); if (authority == NULL) { g_printerr ("Can't get polkit authority: %s\n", error->message); return 1; } exe_path_len = readlink ("/proc/self/exe", exe_path, sizeof (exe_path) - 1); if (exe_path_len > 0) { exe_path[exe_path_len] = 0; GFileMonitor *monitor; g_autoptr(GFile) exe = NULL; g_autoptr(GError) local_error = NULL; exe = g_file_new_for_path (exe_path); monitor = g_file_monitor_file (exe, G_FILE_MONITOR_NONE, NULL, &local_error); if (monitor == NULL) g_warning ("Failed to set watch on %s: %s", exe_path, error->message); else g_signal_connect (monitor, "changed", G_CALLBACK (binary_file_changed_cb), NULL); } flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT; if (replace) flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE; name_owner_id = g_bus_own_name (on_session_bus ? G_BUS_TYPE_SESSION : G_BUS_TYPE_SYSTEM, "org.freedesktop.Flatpak.SystemHelper", flags, on_bus_acquired, on_name_acquired, on_name_lost, NULL, NULL); /* Ensure we don't idle exit */ schedule_idle_callback (); main_loop = g_main_loop_new (NULL, FALSE); g_main_loop_run (main_loop); return 0; }
static gboolean git_evtag_builtin_verify (struct EvTag *self, int argc, char **argv, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; int r; gboolean verified = FALSE; GOptionContext *optcontext; git_oid tag_oid; git_object *obj = NULL; char *long_tagname = NULL; git_tag *tag; const char *tagname; const char *message; git_oid specified_oid; const char *nl; guint64 elapsed_ns; const char *expected_checksum; char commit_oid_hexstr[GIT_OID_HEXSZ+1]; char tag_oid_hexstr[GIT_OID_HEXSZ+1]; char *git_verify_tag_argv[] = {"git", "verify-tag", NULL, NULL }; optcontext = g_option_context_new ("TAGNAME - Verify a signed tag"); if (!option_context_parse (optcontext, verify_options, &argc, &argv, cancellable, error)) goto out; if (argc < 2) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "A TAGNAME argument is required"); goto out; } else if (argc > 2) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Too many arguments"); goto out; } tagname = argv[1]; long_tagname = g_strconcat ("refs/tags/", tagname, NULL); r = git_reference_name_to_id (&tag_oid, self->top_repo, long_tagname); if (!handle_libgit_ret (r, error)) goto out; r = git_tag_lookup (&tag, self->top_repo, &tag_oid); if (!handle_libgit_ret (r, error)) goto out; r = git_tag_target (&obj, tag); if (!handle_libgit_ret (r, error)) goto out; specified_oid = *git_object_id (obj); git_oid_fmt (commit_oid_hexstr, &specified_oid); commit_oid_hexstr[sizeof(commit_oid_hexstr)-1] = '\0'; if (!validate_at_head (self, &specified_oid, error)) goto out; message = git_tag_message (tag); if (!git_oid_tostr (tag_oid_hexstr, sizeof (tag_oid_hexstr), git_tag_id (tag))) g_assert_not_reached (); if (!opt_no_signature) { git_verify_tag_argv[2] = tag_oid_hexstr; if (!spawn_sync_require_success (git_verify_tag_argv, G_SPAWN_SEARCH_PATH, error)) goto out; } if (!checksum_commit_recurse (self, &specified_oid, &elapsed_ns, cancellable, error)) goto out; expected_checksum = g_checksum_get_string (self->checksum); while (TRUE) { nl = strchr (message, '\n'); if (g_str_has_prefix (message, EVTAG_SHA512)) { char *line; if (nl) line = g_strndup (message, nl - message); else line = g_strdup (message); g_strchomp (line); if (!verify_line (expected_checksum, line, commit_oid_hexstr, error)) goto out; { char *stats = get_stats (self); g_print ("%s\n", stats); g_free (stats); } g_print ("Successfully verified: %s\n", line); verified = TRUE; break; } if (!nl) break; message = nl + 1; } if (!verified) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Failed to find %s in tag message", EVTAG_SHA512); goto out; } ret = TRUE; out: return ret; }
/** * The xmms2 daemon main initialisation function */ int main (int argc, char **argv) { xmms_output_plugin_t *o_plugin; xmms_config_property_t *cv; xmms_main_t *mainobj; int loglevel = 1; gchar default_path[XMMS_PATH_MAX + 16], *tmp; gboolean verbose = FALSE; gboolean quiet = FALSE; gboolean version = FALSE; gboolean runasroot = FALSE; gboolean showhelp = FALSE; const gchar *outname = NULL; const gchar *ipcpath = NULL; gchar *uuid, *ppath = NULL; int status_fd = -1; GOptionContext *context = NULL; GError *error = NULL; setlocale (LC_ALL, ""); /** * The options that the server accepts. */ GOptionEntry opts[] = { {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Increase verbosity", NULL}, {"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet, "Decrease verbosity", NULL}, {"version", 'V', 0, G_OPTION_ARG_NONE, &version, "Print version", NULL}, {"output", 'o', 0, G_OPTION_ARG_STRING, &outname, "Use 'x' as output plugin", "<x>"}, {"ipc-socket", 'i', 0, G_OPTION_ARG_FILENAME, &ipcpath, "Listen to socket 'url'", "<url>"}, {"plugindir", 'p', 0, G_OPTION_ARG_FILENAME, &ppath, "Search for plugins in directory 'foo'", "<foo>"}, {"conf", 'c', 0, G_OPTION_ARG_FILENAME, &conffile, "Specify alternate configuration file", "<file>"}, {"status-fd", 's', 0, G_OPTION_ARG_INT, &status_fd, "Specify a filedescriptor to write to when started", "fd"}, {"yes-run-as-root", 0, 0, G_OPTION_ARG_NONE, &runasroot, "Give me enough rope to shoot myself in the foot", NULL}, {"show-help", 'h', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &showhelp, "Use --help or -? instead", NULL}, {NULL} }; /** Check that we are running against the correct glib version */ if (glib_major_version != GLIB_MAJOR_VERSION || glib_minor_version < GLIB_MINOR_VERSION) { g_print ("xmms2d is build against version %d.%d,\n" "but is (runtime) linked against %d.%d.\n" "Refusing to start.\n", GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, glib_major_version, glib_minor_version); exit (EXIT_FAILURE); } xmms_signal_block (); context = g_option_context_new ("- XMMS2 Daemon"); g_option_context_add_main_entries (context, opts, NULL); if (!g_option_context_parse (context, &argc, &argv, &error) || error) { g_print ("Error parsing options: %s\n", error->message); g_clear_error (&error); exit (EXIT_FAILURE); } if (showhelp) { #if GLIB_CHECK_VERSION(2,14,0) g_print ("%s", g_option_context_get_help (context, TRUE, NULL)); exit (EXIT_SUCCESS); #else g_print ("Please use --help or -? for help\n"); exit (EXIT_FAILURE); #endif } g_option_context_free (context); if (argc != 1) { g_print ("There were unknown options, aborting!\n"); exit (EXIT_FAILURE); } if (xmms_checkroot ()) { if (runasroot) { g_print ("***************************************\n"); g_print ("Warning! You are running XMMS2D as root, this is a bad idea!\nBut I'll allow it since you asked nicely.\n"); g_print ("***************************************\n\n"); } else { g_print ("PLEASE DON'T RUN XMMS2D AS ROOT!\n\n(if you really must, read the help)\n"); exit (EXIT_FAILURE); } } if (verbose) { loglevel++; } else if (quiet) { loglevel--; } if (version) { print_version (); } g_thread_init (NULL); g_random_set_seed (time (NULL)); xmms_log_init (loglevel); xmms_ipc_init (); load_config (); cv = xmms_config_property_register ("core.logtsfmt", "%H:%M:%S ", NULL, NULL); xmms_log_set_format (xmms_config_property_get_string (cv)); xmms_fallback_ipcpath_get (default_path, sizeof (default_path)); cv = xmms_config_property_register ("core.ipcsocket", default_path, on_config_ipcsocket_change, NULL); if (!ipcpath) { /* * if not ipcpath is specifed on the cmd line we * grab it from the config */ ipcpath = xmms_config_property_get_string (cv); } if (!xmms_ipc_setup_server (ipcpath)) { xmms_ipc_shutdown (); xmms_log_fatal ("IPC failed to init!"); } if (!xmms_plugin_init (ppath)) { exit (EXIT_FAILURE); } mainobj = xmms_object_new (xmms_main_t, xmms_main_destroy); mainobj->medialib_object = xmms_medialib_init (); mainobj->colldag_object = xmms_collection_init (mainobj->medialib_object); mainobj->mediainfo_object = xmms_mediainfo_reader_start (mainobj->medialib_object); mainobj->playlist_object = xmms_playlist_init (mainobj->medialib_object, mainobj->colldag_object); uuid = xmms_medialib_uuid (mainobj->medialib_object); mainobj->collsync_object = xmms_coll_sync_init (uuid, mainobj->colldag_object, mainobj->playlist_object); g_free (uuid); mainobj->plsupdater_object = xmms_playlist_updater_init (mainobj->playlist_object); mainobj->xform_object = xmms_xform_object_init (); mainobj->bindata_object = xmms_bindata_init (); /* find output plugin. */ cv = xmms_config_property_register ("output.plugin", XMMS_OUTPUT_DEFAULT, change_output, mainobj); if (outname) { xmms_config_property_set_data (cv, outname); } outname = xmms_config_property_get_string (cv); xmms_log_info ("Using output plugin: %s", outname); o_plugin = (xmms_output_plugin_t *) xmms_plugin_find (XMMS_PLUGIN_TYPE_OUTPUT, outname); if (!o_plugin) { xmms_log_error ("Baaaaad output plugin, try to change the" "output.plugin config variable to something useful"); } mainobj->output_object = xmms_output_new (o_plugin, mainobj->playlist_object, mainobj->medialib_object); if (!mainobj->output_object) { xmms_log_fatal ("Failed to create output object!"); } mainobj->visualization_object = xmms_visualization_new (mainobj->output_object); if (status_fd != -1) { write (status_fd, "+", 1); } xmms_signal_init (XMMS_OBJECT (mainobj)); xmms_main_register_ipc_commands (XMMS_OBJECT (mainobj)); /* Save the time we started in order to count uptime */ mainobj->starttime = time (NULL); /* Dirty hack to tell XMMS_PATH a valid path */ g_strlcpy (default_path, ipcpath, sizeof (default_path)); tmp = strchr (default_path, ';'); if (tmp) { *tmp = '\0'; } g_setenv ("XMMS_PATH", default_path, TRUE); /* Also put the full path for clients that understands */ g_setenv("XMMS_PATH_FULL", ipcpath, TRUE); tmp = XMMS_BUILD_PATH ("shutdown.d"); cv = xmms_config_property_register ("core.shutdownpath", tmp, NULL, NULL); g_free (tmp); tmp = XMMS_BUILD_PATH ("startup.d"); cv = xmms_config_property_register ("core.startuppath", tmp, NULL, NULL); g_free (tmp); /* Startup dir */ do_scriptdir (xmms_config_property_get_string (cv), "start"); mainloop = g_main_loop_new (NULL, FALSE); g_main_loop_run (mainloop); return EXIT_SUCCESS; }
int main (int argc, char **argv) { g_autoptr(GOptionContext) option_context = NULL; gboolean ret; gboolean verbose = FALSE; g_autoptr(GError) error = NULL; g_autofree gchar *basename = NULL; g_autofree gchar *icons_dir = NULL; g_autofree gchar *origin = NULL; g_autofree gchar *xml_basename = NULL; g_autofree gchar *output_dir = NULL; g_autofree gchar *prefix = NULL; g_autoptr(AsStore) store = NULL; g_autoptr(GFile) xml_dir = NULL; g_autoptr(GFile) xml_file = NULL; guint min_icon_size = 32; guint i; const GOptionEntry options[] = { { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, /* TRANSLATORS: command line option */ _("Show extra debugging information"), NULL }, { "prefix", '\0', 0, G_OPTION_ARG_FILENAME, &prefix, /* TRANSLATORS: command line option */ _("Set the prefix"), "DIR" }, { "output-dir", '\0', 0, G_OPTION_ARG_FILENAME, &output_dir, /* TRANSLATORS: command line option */ _("Set the output directory"), "DIR" }, { "icons-dir", '\0', 0, G_OPTION_ARG_FILENAME, &icons_dir, /* TRANSLATORS: command line option */ _("Set the icons directory"), "DIR" }, { "origin", '\0', 0, G_OPTION_ARG_STRING, &origin, /* TRANSLATORS: command line option */ _("Set the origin name"), "NAME" }, { "min-icon-size", '\0', 0, G_OPTION_ARG_INT, &min_icon_size, /* TRANSLATORS: command line option */ _("Set the minimum icon size in pixels"), "ICON_SIZE" }, { "basename", '\0', 0, G_OPTION_ARG_STRING, &basename, /* TRANSLATORS: command line option */ _("Set the basenames of the output files"), "NAME" }, { NULL} }; setlocale (LC_ALL, ""); bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); option_context = g_option_context_new (" - APP-IDS"); g_option_context_add_main_entries (option_context, options, NULL); ret = g_option_context_parse (option_context, &argc, &argv, &error); if (!ret) { /* TRANSLATORS: error message */ g_print ("%s: %s\n", _("Failed to parse arguments"), error->message); return EXIT_FAILURE; } if (verbose) g_setenv ("G_MESSAGES_DEBUG", "all", TRUE); /* set defaults */ if (prefix == NULL) prefix = g_strdup ("/usr"); if (output_dir == NULL) output_dir = g_build_filename (prefix, "share/app-info/xmls", NULL); if (icons_dir == NULL) icons_dir = g_build_filename (prefix, "share/app-info/icons", origin, NULL); if (origin == NULL) { g_print ("WARNING: Metadata origin not set, using 'example'\n"); origin = g_strdup ("example"); } if (basename == NULL) basename = g_strdup (origin); if (argc == 1) { g_autofree gchar *tmp = NULL; tmp = g_option_context_get_help (option_context, TRUE, NULL); g_print ("%s", tmp); return EXIT_FAILURE; } store = as_store_new (); as_store_set_api_version (store, 0.8); as_store_set_origin (store, origin); /* load each application specified */ for (i = 1; i < (guint) argc; i++) { const gchar *app_name = argv[i]; g_auto(GStrv) intl_domains = NULL; g_autoptr(AsApp) app_appdata = NULL; g_autoptr(AsApp) app_desktop = NULL; /* TRANSLATORS: we're generating the AppStream data */ g_print ("%s %s\n", _("Processing application"), app_name); app_appdata = load_appdata (prefix, app_name, &error); if (app_appdata == NULL) { /* TRANSLATORS: the .appdata.xml file could not * be loaded */ g_print ("%s: %s\n", _("Error loading AppData file"), error->message); return EXIT_FAILURE; } /* set translations */ if (!as_app_builder_search_translations (app_appdata, prefix, 25, AS_APP_BUILDER_FLAG_NONE, NULL, &error)) { /* TRANSLATORS: the .mo files could not be parsed */ g_print ("%s: %s\n", _("Error parsing translations"), error->message); return EXIT_FAILURE; } /* auto-add kudos */ if (!as_app_builder_search_kudos (app_appdata, prefix, AS_APP_BUILDER_FLAG_NONE, &error)) { /* TRANSLATORS: we could not auto-add the kudo */ g_print ("%s: %s\n", _("Error parsing kudos"), error->message); return EXIT_FAILURE; } /* auto-add provides */ if (!as_app_builder_search_provides (app_appdata, prefix, AS_APP_BUILDER_FLAG_NONE, &error)) { /* TRANSLATORS: we could not auto-add the provides */ g_print ("%s: %s\n", _("Error parsing provides"), error->message); return EXIT_FAILURE; } as_store_add_app (store, app_appdata); app_desktop = load_desktop (prefix, icons_dir, min_icon_size, app_name, as_app_get_id (app_appdata), &error); if (app_desktop == NULL) { /* TRANSLATORS: the .desktop file could not * be loaded */ g_print ("%s: %s\n", _("Error loading desktop file"), error->message); return EXIT_FAILURE; } as_store_add_app (store, app_desktop); } /* create output directory */ if (g_mkdir_with_parents (output_dir, 0755)) { int errsv = errno; g_print ("%s: %s\n", /* TRANSLATORS: this is when the folder could * not be created */ _("Error creating output directory"), strerror (errsv)); return EXIT_FAILURE; } xml_dir = g_file_new_for_path (output_dir); xml_basename = g_strconcat (basename, ".xml.gz", NULL); xml_file = g_file_get_child (xml_dir, xml_basename); /* TRANSLATORS: we've saving the XML file to disk */ g_print ("%s %s\n", _("Saving AppStream"), g_file_get_path (xml_file)); if (!as_store_to_file (store, xml_file, AS_NODE_TO_XML_FLAG_FORMAT_MULTILINE | AS_NODE_TO_XML_FLAG_FORMAT_INDENT | AS_NODE_TO_XML_FLAG_ADD_HEADER, NULL, &error)) { /* TRANSLATORS: this is when the destination file * cannot be saved for some reason */ g_print ("%s: %s\n", _("Error saving AppStream file"), error->message); return EXIT_FAILURE; } /* TRANSLATORS: information message */ g_print ("%s\n", _("Done!")); return EXIT_SUCCESS; }
int main(int argc, char **argv) { int pid, ret; struct sigaction new_action, old_action; GOptionContext *ctx; GError *parse_err = NULL; daemon_pid_file_ident = daemon_log_ident = daemon_ident_from_argv0(argv[0]); daemon_pid_file_proc = conf_pid_file_proc; if (conf_init() < 0) return EXIT_FAILURE; ctx = g_option_context_new(""); g_option_context_add_main_entries(ctx, options, PACKAGE); g_option_context_set_summary(ctx, PACKAGE"-"VERSION GITHEAD" - mpd cron daemon"); if (!g_option_context_parse(ctx, &argc, &argv, &parse_err)) { g_printerr("option parsing failed: %s\n", parse_err->message); g_option_context_free(ctx); g_error_free(parse_err); return EXIT_FAILURE; } g_option_context_free(ctx); if (optv) { about(); cleanup(); return EXIT_SUCCESS; } #ifdef DAEMON_SET_VERBOSITY_AVAILABLE if (conf.no_daemon) daemon_set_verbosity(LOG_DEBUG); #endif /* DAEMON_SET_VERBOSITY_AVAILABLE */ /* Version to environment variable */ g_setenv("MPDCRON_PACKAGE", PACKAGE, 1); g_setenv("MPDCRON_VERSION", VERSION, 1); g_setenv("MPDCRON_GITHEAD", GITHEAD, 1); /* Command line options to environment variables */ if (conf.no_daemon) g_unsetenv("MCOPT_DAEMONIZE"); else g_setenv("MCOPT_DAEMONIZE", "1", 1); /* Important! Parse configuration file before killing the daemon * because the configuration file has a pidfile and killwait option. */ cfd = g_key_file_new(); if (keyfile_load(&cfd) < 0) { cleanup(); return EXIT_FAILURE; } if (optk) { if (daemon_pid_file_kill_wait(SIGINT, conf.killwait) < 0) { g_warning("Failed to kill daemon: %s", strerror(errno)); cleanup(); return EXIT_FAILURE; } daemon_pid_file_remove(); cleanup(); return EXIT_SUCCESS; } /* Logging */ g_log_set_default_handler(log_handler, GINT_TO_POINTER(conf.no_daemon ? 5 : conf.loglevel)); /* Signal handling */ new_action.sa_handler = sig_cleanup; sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; #define HANDLE_SIGNAL(sig) \ do { \ sigaction((sig), NULL, &old_action); \ if (old_action.sa_handler != SIG_IGN) \ sigaction((sig), &new_action, NULL); \ } while (0) HANDLE_SIGNAL(SIGABRT); HANDLE_SIGNAL(SIGSEGV); HANDLE_SIGNAL(SIGINT); HANDLE_SIGNAL(SIGTERM); #undef HANDLE_SIGNAL if (conf.no_daemon) { /* Create the main loop */ loop = g_main_loop_new(NULL, FALSE); #ifdef HAVE_GMODULE /* Load modules which may add initial events */ keyfile_load_modules(&cfd); #endif /* HAVE_GMODULE */ g_key_file_free(cfd); cfd = NULL; /* Add default initial events */ loop_connect(); /* Run the main loop */ g_main_loop_run(loop); cleanup(); return EXIT_SUCCESS; } /* Daemonize */ if ((pid = daemon_pid_file_is_running()) > 0) { g_critical("Daemon already running on PID %u", pid); return EXIT_FAILURE; } daemon_retval_init(); pid = daemon_fork(); if (pid < 0) { g_critical("Failed to fork: %s", strerror(errno)); daemon_retval_done(); return EXIT_FAILURE; } else if (pid != 0) { /* Parent */ cleanup(); if ((ret = daemon_retval_wait(2)) < 0) { g_critical("Could not receive return value from daemon process: %s", strerror(errno)); return 255; } if (ret != 0) g_critical("Daemon returned %i as return value", ret); else g_critical("Daemon returned %i as return value", ret); return ret; } else { /* Daemon */ if (daemon_close_all(-1) < 0) { g_critical("Failed to close all file descriptors: %s", strerror(errno)); daemon_retval_send(1); return EXIT_FAILURE; } if (daemon_pid_file_create() < 0) { g_critical("Failed to create PID file: %s", strerror(errno)); daemon_retval_send(2); return EXIT_FAILURE; } /* Send OK to parent process */ daemon_retval_send(0); /* Create the main loop */ loop = g_main_loop_new(NULL, FALSE); #ifdef HAVE_GMODULE /* Load modules which may add initial events */ keyfile_load_modules(&cfd); #endif /* HAVE_GMODULE */ g_key_file_free(cfd); cfd = NULL; /* Add default initial events */ loop_connect(); /* Run the main loop */ g_main_loop_run(loop); cleanup(); return EXIT_SUCCESS; } return EXIT_SUCCESS; }
static void parse_args(gint argc, gchar **argv, FileInfo *fi) { EncArray *encarray; gint i; GError *error = NULL; GOptionContext *context; gchar *opt_codeset = NULL; gint opt_tab_width = 0; gboolean opt_jump = 0; gboolean opt_version = FALSE; GOptionEntry entries[] = { { "codeset", 0, 0, G_OPTION_ARG_STRING, &opt_codeset, "Set codeset to open file", "CODESET" }, { "tab-width", 0, 0, G_OPTION_ARG_INT, &opt_tab_width, "Set tab width", "WIDTH" }, { "jump", 0, 0, G_OPTION_ARG_INT, &opt_jump, "Jump to specified line", "LINENUM" }, { "version", 0, 0, G_OPTION_ARG_NONE, &opt_version, "Show version number", NULL }, { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL } }; context = g_option_context_new("[filename]"); g_option_context_add_main_entries(context, entries, PACKAGE); g_option_context_add_group(context, gtk_get_option_group(TRUE)); g_option_context_set_ignore_unknown_options(context, FALSE); g_option_context_parse(context, &argc, &argv, &error); g_option_context_free(context); if (error) { g_print("%s: %s\n", PACKAGE, error->message); g_error_free(error); exit(-1); } if (opt_version) { g_print("%s\n", PACKAGE_STRING); exit(0); } if (opt_codeset) { g_convert("TEST", -1, "UTF-8", opt_codeset, NULL, NULL, &error); if (error) { g_error_free(error); error = NULL; } else { g_free(fi->charset); fi->charset = g_strdup(opt_codeset); } } if (opt_tab_width) indent_set_default_tab_width(opt_tab_width); if (opt_jump) jump_linenum = opt_jump; if (fi->charset && (g_ascii_strcasecmp(fi->charset, get_default_charset()) != 0) && (g_ascii_strcasecmp(fi->charset, "UTF-8") != 0)) { encarray = get_encoding_items(get_encoding_code()); for (i = 0; i < ENCODING_MAX_ITEM_NUM; i++) if (encarray->item[i]) if (g_ascii_strcasecmp(fi->charset, encarray->item[i]) == 0) break; if (i == ENCODING_MAX_ITEM_NUM) fi->charset_flag = TRUE; } if (argc >= 2) fi->filename = parse_file_uri(argv[1]); }
int main (int argc, char **argv) { PinPointRenderer *renderer; GOptionContext *context; GError *error = NULL; char *text = NULL; memcpy (&default_point, &pin_default_point, sizeof (default_point)); renderer = pp_clutter_renderer (); context = g_option_context_new ("- Presentations made easy"); g_option_context_add_main_entries (context, entries, NULL); g_option_context_add_group (context, clutter_get_option_group_without_init ()); g_option_context_add_group (context, cogl_get_option_group ()); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_print ("option parsing failed: %s\n", error->message); return EXIT_FAILURE; } pinfile = argv[1]; if (!pinfile) { g_print ("usage: %s [options] <presentation>\n", argv[0]); text = g_strdup ("[no-markup][transition=sheet][red]\n" "--\n" "usage: pinpoint [options] <presentation.txt>\n"); } else { if (!g_file_get_contents (pinfile, &text, NULL, NULL)) { g_print ("failed to load presentation from %s\n", pinfile); return -1; } } #ifdef USE_CLUTTER_GST clutter_gst_init (&argc, &argv); #else clutter_init (&argc, &argv); #endif #ifdef USE_DAX dax_init (&argc, &argv); #endif /* select the cairo renderer if we have requested pdf output */ if (pp_output_filename && g_str_has_suffix (pp_output_filename, ".pdf")) { #ifdef HAVE_PDF renderer = pp_cairo_renderer (); /* makes more sense to default to a white "stage" colour in PDFs*/ default_point.stage_color = "white"; #else g_warning ("Pinpoint was built without PDF support"); return EXIT_FAILURE; #endif } if (!pinfile) pp_rehearse = FALSE; if (pinfile) { GFile *file; file = g_file_new_for_commandline_arg (pinfile); pp_basedir = g_file_get_parent (file); g_object_unref (file); } renderer->init (renderer, pinfile); pp_parse_slides (renderer, text); g_free (text); if (pp_rehearse) { pp_rehearse_init (); printf ("Running in rehearsal mode, press ctrl+C to abort without saving timings back to %s\n", pinfile); } renderer->run (renderer); renderer->finalize (renderer); if (renderer->source) g_free (renderer->source); #if 0 if (pp_rehearse) pp_rehearse_save (); #endif g_list_free (pp_slides); return 0; }
int main (int argc, char **argv) { GOptionContext *context; GOptionGroup *group; GError* err = NULL; int i; int args_len; mode_t dir_permissions; char *basename; setlocale (LC_ALL, ""); basename = g_path_get_basename (argv[0]); if (g_strcmp0 (basename, "desktop-file-edit") == 0) edit_mode = TRUE; g_free (basename); context = g_option_context_new (""); g_option_context_set_summary (context, edit_mode ? _("Edit a desktop file.") : _("Install desktop files.")); g_option_context_add_main_entries (context, main_options, NULL); if (!edit_mode) { group = g_option_group_new ("install", _("Installation options for desktop file"), _("Show desktop file installation options"), NULL, NULL); g_option_group_add_entries (group, install_options); g_option_context_add_group (context, group); } group = g_option_group_new ("edit", _("Edition options for desktop file"), _("Show desktop file edition options"), NULL, NULL); g_option_group_add_entries (group, edit_options); g_option_group_set_parse_hooks (group, NULL, post_parse_edit_options_callback); g_option_context_add_group (context, group); err = NULL; g_option_context_parse (context, &argc, &argv, &err); if (err != NULL) { g_printerr ("%s\n", err->message); g_printerr (_("Run '%s --help' to see a full list of available command line options.\n"), argv[0]); g_error_free (err); return 1; } if (!edit_mode) { if (vendor_name == NULL && g_getenv ("DESKTOP_FILE_VENDOR")) vendor_name = g_strdup (g_getenv ("DESKTOP_FILE_VENDOR")); if (target_dir == NULL && g_getenv ("DESKTOP_FILE_INSTALL_DIR")) target_dir = g_strdup (g_getenv ("DESKTOP_FILE_INSTALL_DIR")); if (target_dir == NULL) { if (g_getenv ("RPM_BUILD_ROOT")) target_dir = g_build_filename (g_getenv ("RPM_BUILD_ROOT"), DATADIR, "applications", NULL); else target_dir = g_build_filename (DATADIR, "applications", NULL); } /* Create the target directory */ dir_permissions = permissions; /* Add search bit when the target file is readable */ if (permissions & 0400) dir_permissions |= 0100; if (permissions & 0040) dir_permissions |= 0010; if (permissions & 0004) dir_permissions |= 0001; g_mkdir_with_parents (target_dir, dir_permissions); } args_len = 0; for (i = 0; args && args[i]; i++) args_len++; if (edit_mode) { if (args_len == 0) { g_printerr (_("Must specify a desktop file to process.\n")); return 1; } if (args_len > 1) { g_printerr (_("Only one desktop file can be processed at once.\n")); return 1; } } else { if (args_len == 0) { g_printerr (_("Must specify one or more desktop files to process.\n")); return 1; } } for (i = 0; args && args[i]; i++) { err = NULL; process_one_file (args[i], &err); if (err != NULL) { g_printerr (_("Error on file \"%s\": %s\n"), args[i], err->message); g_error_free (err); return 1; } } #if GLIB_CHECK_VERSION(2,28,0) g_slist_free_full (edit_actions, (GDestroyNotify) dfu_edit_action_free); #else g_slist_foreach (edit_actions, (GFunc) dfu_edit_action_free, NULL); g_slist_free (edit_actions); #endif g_option_context_free (context); return 0; }
int main( int argc, char* argv[] ) { GError *error = NULL; GOptionContext *context; context = g_option_context_new("config_file_name or profile name"); g_option_context_add_main_entries(context, options_entries, ""); if (!g_option_context_parse (context, &argc, &argv, &error)) { std::cout << "option parsing failed: " << error->message << "\n"; return -1; } if (ver) { std::cout << VERSION << "\n"; g_option_context_free(context); return 0; } if (argc != 2) { #ifdef WIN32 std::cout << "Usage: spectrum.exe <configuration_file.cfg>\n"; #else #if GLIB_CHECK_VERSION(2,14,0) std::cout << g_option_context_get_help(context, FALSE, NULL); #else std::cout << "Usage: spectrum <configuration_file.cfg>\n"; std::cout << "See \"man spectrum\" for more info.\n"; #endif #endif } else { #ifndef WIN32 signal(SIGPIPE, SIG_IGN); if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) { std::cout << "SIGCHLD handler can't be set\n"; g_option_context_free(context); return -1; } if (signal(SIGINT, spectrum_sigint_handler) == SIG_ERR) { std::cout << "SIGINT handler can't be set\n"; g_option_context_free(context); return -1; } if (signal(SIGTERM, spectrum_sigterm_handler) == SIG_ERR) { std::cout << "SIGTERM handler can't be set\n"; g_option_context_free(context); return -1; } struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = spectrum_sighup_handler; if (sigaction(SIGHUP, &sa, NULL)) { std::cout << "SIGHUP handler can't be set\n"; g_option_context_free(context); return -1; } #endif std::string config(argv[1]); new BalancerComponent(config); } g_option_context_free(context); }
int main (int argc, char *argv[]) { gboolean print_all = FALSE; gboolean do_print_blacklist = FALSE; gboolean plugin_name = FALSE; gboolean print_aii = FALSE; gboolean uri_handlers = FALSE; #ifndef GST_DISABLE_OPTION_PARSING GOptionEntry options[] = { {"print-all", 'a', 0, G_OPTION_ARG_NONE, &print_all, N_("Print all elements"), NULL}, {"print-blacklist", 'b', 0, G_OPTION_ARG_NONE, &do_print_blacklist, N_("Print list of blacklisted files"), NULL}, {"print-plugin-auto-install-info", '\0', 0, G_OPTION_ARG_NONE, &print_aii, N_("Print a machine-parsable list of features the specified plugin " "or all plugins provide.\n " "Useful in connection with external automatic plugin " "installation mechanisms"), NULL}, {"plugin", '\0', 0, G_OPTION_ARG_NONE, &plugin_name, N_("List the plugin contents"), NULL}, {"uri-handlers", 'u', 0, G_OPTION_ARG_NONE, &uri_handlers, N_ ("Print supported URI schemes, with the elements that implement them"), NULL}, GST_TOOLS_GOPTION_VERSION, {NULL} }; GOptionContext *ctx; GError *err = NULL; #endif #ifdef ENABLE_NLS bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); #endif #if !GLIB_CHECK_VERSION (2, 31, 0) g_thread_init (NULL); #endif gst_tools_set_prgname ("gst-inspect"); #ifndef GST_DISABLE_OPTION_PARSING ctx = g_option_context_new ("[ELEMENT-NAME | PLUGIN-NAME]"); g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE); g_option_context_add_group (ctx, gst_init_get_option_group ()); if (!g_option_context_parse (ctx, &argc, &argv, &err)) { g_print ("Error initializing: %s\n", err->message); exit (1); } g_option_context_free (ctx); #else gst_init (&argc, &argv); #endif gst_tools_print_version ("gst-inspect"); if (print_all && argc > 1) { g_print ("-a requires no extra arguments\n"); return 1; } if (uri_handlers && argc > 1) { g_print ("-u requires no extra arguments\n"); exit (1); } /* if no arguments, print out list of elements */ if (uri_handlers) { print_all_uri_handlers (); } else if (argc == 1 || print_all) { if (do_print_blacklist) print_blacklist (); else { if (print_aii) print_all_plugin_automatic_install_info (); else print_element_list (print_all); } } else { /* else we try to get a factory */ GstElementFactory *factory; GstPlugin *plugin; const char *arg = argv[argc - 1]; int retval; if (!plugin_name) { factory = gst_element_factory_find (arg); /* if there's a factory, print out the info */ if (factory) { retval = print_element_info (factory, print_all); gst_object_unref (factory); } else { retval = print_element_features (arg); } } else { retval = -1; } /* otherwise check if it's a plugin */ if (retval) { plugin = gst_default_registry_find_plugin (arg); /* if there is such a plugin, print out info */ if (plugin) { if (print_aii) { print_plugin_automatic_install_info (plugin); } else { print_plugin_info (plugin); print_plugin_features (plugin); } } else { GError *error = NULL; if (g_file_test (arg, G_FILE_TEST_EXISTS)) { plugin = gst_plugin_load_file (arg, &error); if (plugin) { if (print_aii) { print_plugin_automatic_install_info (plugin); } else { print_plugin_info (plugin); print_plugin_features (plugin); } } else { g_print (_("Could not load plugin file: %s\n"), error->message); g_error_free (error); return -1; } } else { g_print (_("No such element or plugin '%s'\n"), arg); return -1; } } } } return 0; }
int main(int argc, char * argv[]){ FILE * input = stdin; FILE * output = stdout; setlocale(LC_ALL, ""); GError * error = NULL; GOptionContext * context; context = g_option_context_new("- n-gram segment"); g_option_context_add_main_entries(context, entries, NULL); if (!g_option_context_parse(context, &argc, &argv, &error)) { g_print("option parsing failed:%s\n", error->message); exit(EINVAL); } if (outputfile) { output = fopen(outputfile, "w"); if (NULL == output) { perror("open file failed"); exit(EINVAL); } } if (argc > 2) { fprintf(stderr, "too many arguments.\n"); exit(EINVAL); } if (2 == argc) { input = fopen(argv[1], "r"); if (NULL == input) { perror("open file failed"); exit(EINVAL); } } SystemTableInfo system_table_info; bool retval = system_table_info.load(SYSTEM_TABLE_INFO); if (!retval) { fprintf(stderr, "load table.conf failed.\n"); exit(ENOENT); } /* init phrase table */ FacadePhraseTable2 phrase_table; MemoryChunk * chunk = new MemoryChunk; chunk->load(SYSTEM_PHRASE_INDEX); phrase_table.load(chunk, NULL); /* init phrase index */ FacadePhraseIndex phrase_index; const pinyin_table_info_t * phrase_files = system_table_info.get_table_info(); if (!load_phrase_index(phrase_files, &phrase_index)) exit(ENOENT); /* init bi-gram */ Bigram system_bigram; system_bigram.attach(SYSTEM_BIGRAM, ATTACH_READONLY); Bigram user_bigram; gfloat lambda = system_table_info.get_lambda(); /* init phrase lookup */ PhraseLookup phrase_lookup(lambda, &phrase_table, &phrase_index, &system_bigram, &user_bigram); CONTEXT_STATE state, next_state; GArray * current_ucs4 = g_array_new(TRUE, TRUE, sizeof(ucs4_t)); PhraseTokens tokens; memset(tokens, 0, sizeof(PhraseTokens)); phrase_index.prepare_tokens(tokens); /* split the sentence */ char * linebuf = NULL; size_t size = 0; ssize_t read; while( (read = getline(&linebuf, &size, input)) != -1 ){ if ( '\n' == linebuf[strlen(linebuf) - 1] ) { linebuf[strlen(linebuf) - 1] = '\0'; } /* check non-ucs4 characters */ const glong num_of_chars = g_utf8_strlen(linebuf, -1); glong len = 0; ucs4_t * sentence = g_utf8_to_ucs4(linebuf, -1, NULL, &len, NULL); if ( len != num_of_chars ) { fprintf(stderr, "non-ucs4 characters encountered:%s.\n", linebuf); fprintf(output, "%d \n", null_token); continue; } /* only new-line persists. */ if ( 0 == num_of_chars ) { fprintf(output, "%d \n", null_token); continue; } state = CONTEXT_INIT; int result = phrase_table.search( 1, sentence, tokens); g_array_append_val( current_ucs4, sentence[0]); if ( result & SEARCH_OK ) state = CONTEXT_SEGMENTABLE; else state = CONTEXT_UNKNOWN; for ( int i = 1; i < num_of_chars; ++i) { int result = phrase_table.search( 1, sentence + i, tokens); if ( result & SEARCH_OK ) next_state = CONTEXT_SEGMENTABLE; else next_state = CONTEXT_UNKNOWN; if ( state == next_state ){ g_array_append_val(current_ucs4, sentence[i]); continue; } assert ( state != next_state ); if ( state == CONTEXT_SEGMENTABLE ) deal_with_segmentable(&phrase_lookup, current_ucs4, output); if ( state == CONTEXT_UNKNOWN ) deal_with_unknown(current_ucs4, output); /* save the current character */ g_array_set_size(current_ucs4, 0); g_array_append_val(current_ucs4, sentence[i]); state = next_state; } if ( current_ucs4->len ) { /* this seems always true. */ if ( state == CONTEXT_SEGMENTABLE ) deal_with_segmentable(&phrase_lookup, current_ucs4, output); if ( state == CONTEXT_UNKNOWN ) deal_with_unknown(current_ucs4, output); g_array_set_size(current_ucs4, 0); } /* print extra enter */ if ( gen_extra_enter ) fprintf(output, "%d \n", null_token); g_free(sentence); } phrase_index.destroy_tokens(tokens); /* print enter at file tail */ fprintf(output, "%d \n", null_token); g_array_free(current_ucs4, TRUE); free(linebuf); fclose(input); fclose(output); return 0; }
int main(int argc, char *argv[]) { signal_user_data_t *ud; GError *error = NULL; GOptionContext *context; hb_global_init(); #ifdef ENABLE_NLS bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR); bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); textdomain(GETTEXT_PACKAGE); #endif context = g_option_context_new(_("- Transcode media formats")); g_option_context_add_main_entries(context, entries, GETTEXT_PACKAGE); g_option_context_add_group(context, gtk_get_option_group(TRUE)); #if defined(_ENABLE_GST) g_option_context_add_group(context, gst_init_get_option_group()); #endif g_option_context_parse(context, &argc, &argv, &error); if (error != NULL) { g_warning("%s: %s", G_STRFUNC, error->message); g_clear_error(&error); } g_option_context_free(context); #if defined(_WIN32) if (win32_console) { // Enable console logging if(AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){ close(STDOUT_FILENO); freopen("CONOUT$", "w", stdout); close(STDERR_FILENO); freopen("CONOUT$", "w", stderr); } } else { // Non-console windows apps do not have a stderr->_file // assigned properly stderr->_file = STDERR_FILENO; stdout->_file = STDOUT_FILENO; } #endif if (argc > 1 && dvd_device == NULL && argv[1][0] != '-') { dvd_device = argv[1]; } gtk_init(&argc, &argv); GtkCssProvider *css = gtk_css_provider_new(); error = NULL; gtk_css_provider_load_from_data(css, MyCSS, -1, &error); if (error == NULL) { GdkScreen *ss = gdk_screen_get_default(); gtk_style_context_add_provider_for_screen(ss, GTK_STYLE_PROVIDER(css), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); } else { g_warning("%s: %s", G_STRFUNC, error->message); g_clear_error(&error); } #if !defined(_WIN32) notify_init("HandBrake"); #endif ghb_resource_init(); ghb_load_icons(); #if !defined(_WIN32) dbus_g_thread_init(); #endif ghb_udev_init(); ghb_write_pid_file(); ud = g_malloc0(sizeof(signal_user_data_t)); ud->debug = ghb_debug; g_log_set_handler(NULL, G_LOG_LEVEL_DEBUG, debug_log_handler, ud); g_log_set_handler("Gtk", G_LOG_LEVEL_WARNING, warn_log_handler, ud); //g_log_set_handler("Gtk", G_LOG_LEVEL_CRITICAL, warn_log_handler, ud); ud->globals = ghb_dict_new(); ud->prefs = ghb_dict_new(); ud->settings_array = ghb_array_new(); ud->settings = ghb_dict_new(); ghb_array_append(ud->settings_array, ud->settings); ud->builder = create_builder_or_die(BUILDER_NAME); // Enable events that alert us to media change events watch_volumes(ud); //GtkWidget *widget = GHB_WIDGET(ud->builder, "PictureDetelecineCustom"); //gtk_entry_set_inner_border(widget, 2); // Since GtkBuilder no longer assigns object ids to widget names // Assign a few that are necessary for style overrides to work GtkWidget *widget; #if defined(_NO_UPDATE_CHECK) widget = GHB_WIDGET(ud->builder, "check_updates_box"); gtk_widget_hide(widget); #endif // Must set the names of the widgets that I want to modify // style for. gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_hud"), "preview_hud"); gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_frame"), "preview_frame"); gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_preview_play"), "live_preview_play"); gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_preview_progress"), "live_preview_progress"); gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_encode_progress"), "live_encode_progress"); gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_duration"), "live_duration"); gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_show_crop"), "preview_show_crop"); gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_fullscreen"), "preview_fullscreen"); widget = GHB_WIDGET(ud->builder, "preview_hud"); gtk_widget_set_name(widget, "preview_hud"); widget = GHB_WIDGET(ud->builder, "preview_window"); gtk_widget_set_name(widget, "preview_window"); // Set up the "hud" control overlay for the preview window GtkWidget *preview_box, *draw, *hud, *blender; preview_box = GHB_WIDGET(ud->builder, "preview_window_box"); draw = GHB_WIDGET(ud->builder, "preview_image"); hud = GHB_WIDGET(ud->builder, "preview_hud"); #if 0 // GTK_CHECK_VERSION(3, 0, 0) // This uses the new GtkOverlay widget. // // Unfortunately, GtkOverlay is broken in a couple of ways. // // First, it doesn't respect gtk_widget_shape_combine_region() // on it's child overlays. It appears to just ignore the clip // mask of the child. // // Second, it doesn't respect window opacity. // // So for now, I'll just continue using my home-grown overlay // widget (GhbCompositor). blender = gtk_overlay_new(); gtk_container_add(GTK_CONTAINER(preview_box), blender); gtk_container_add(GTK_CONTAINER(blender), draw); gtk_widget_set_valign (hud, GTK_ALIGN_END); gtk_widget_set_halign (hud, GTK_ALIGN_CENTER); gtk_overlay_add_overlay(GTK_OVERLAY(blender), hud); g_signal_connect(G_OBJECT(blender), "get-child-position", G_CALLBACK(position_overlay_cb), ud); gtk_widget_show(blender); #else // Set up compositing for hud blender = ghb_compositor_new(); gtk_container_add(GTK_CONTAINER(preview_box), blender); ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), draw, 1, 1); ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), hud, 2, .85); gtk_widget_show(blender); #endif // Redirect stderr to the activity window ghb_preview_init(ud); IoRedirect(ud); ghb_log( "%s - %s - %s", HB_PROJECT_TITLE, HB_PROJECT_BUILD_TITLE, HB_PROJECT_URL_WEBSITE ); ghb_init_dep_map(); // Need to connect x264_options textview buffer to the changed signal // since it can't be done automatically GtkTextView *textview; GtkTextBuffer *buffer; textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "x264Option")); buffer = gtk_text_view_get_buffer(textview); g_signal_connect(buffer, "changed", (GCallback)x264_entry_changed_cb, ud); textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "VideoOptionExtra")); buffer = gtk_text_view_get_buffer(textview); g_signal_connect(buffer, "changed", (GCallback)video_option_changed_cb, ud); textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "MetaLongDescription")); buffer = gtk_text_view_get_buffer(textview); g_signal_connect(buffer, "changed", (GCallback)plot_changed_cb, ud); ghb_combo_init(ud); g_debug("ud %p\n", ud); g_debug("ud->builder %p\n", ud->builder); bind_audio_tree_model(ud); bind_subtitle_tree_model(ud); bind_presets_tree_model(ud); bind_queue_tree_model(ud); bind_chapter_tree_model(ud); // Connect up the signals to their callbacks // I wrote my own connector so that I could pass user data // to the callbacks. Builder's standard autoconnect doesn't all this. gtk_builder_connect_signals_full(ud->builder, MyConnect, ud); ghb_init_audio_defaults_ui(ud); ghb_init_subtitle_defaults_ui(ud); // Parsing x264 options "" initializes x264 widgets to proper defaults ghb_x264_init(ud); // Load prefs before presets. Some preset defaults may depend // on preference settings. // First load default values ghb_settings_init(ud->prefs, "Preferences"); ghb_settings_init(ud->globals, "Globals"); ghb_settings_init(ud->settings, "Initialization"); ghb_settings_init(ud->settings, "OneTimeInitialization"); // Load user preferences file ghb_prefs_load(ud); // Store user preferences into ud->prefs ghb_prefs_to_settings(ud->prefs); int logLevel = ghb_dict_get_int(ud->prefs, "LoggingLevel"); ghb_backend_init(logLevel); // Load the presets files ghb_presets_load(ud); // Note that ghb_preset_to_settings(ud->settings) is called when // the default preset is selected. ghb_settings_to_ui(ud, ud->globals); ghb_settings_to_ui(ud, ud->prefs); // Note that ghb_settings_to_ui(ud->settings) happens when initial // empty title is initialized. if (ghb_dict_get_bool(ud->prefs, "hbfd")) { ghb_hbfd(ud, TRUE); } const gchar *source = ghb_dict_get_string(ud->prefs, "default_source"); ghb_dvd_set_current(source, ud); // Populate the presets tree view ghb_presets_list_init(ud, NULL); // Get the first preset name if (arg_preset != NULL) { ghb_select_preset(ud->builder, arg_preset); } else { ghb_select_default_preset(ud->builder); } // Grey out widgets that are dependent on a disabled feature ghb_check_all_depencencies(ud); if (dvd_device != NULL) { // Source overridden from command line option ghb_dict_set_string(ud->globals, "scan_source", dvd_device); g_idle_add((GSourceFunc)ghb_idle_scan, ud); } else { GhbValue *gval = ghb_dict_get_value(ud->prefs, "default_source"); ghb_dict_set(ud->globals, "scan_source", ghb_value_dup(gval)); } // Reload and check status of the last saved queue g_idle_add((GSourceFunc)ghb_reload_queue, ud); // Start timer for monitoring libhb status, 500ms g_timeout_add(200, ghb_timer_cb, (gpointer)ud); // Add dvd devices to File menu ghb_volname_cache_init(); GHB_THREAD_NEW("Cache Volume Names", (GThreadFunc)ghb_cache_volnames, ud); GtkWidget *ghb_window = GHB_WIDGET(ud->builder, "hb_window"); gint window_width, window_height; GdkGeometry geo = { -1, -1, 1920, 768, -1, -1, 10, 10, 0, 0, GDK_GRAVITY_NORTH_WEST }; GdkWindowHints geo_mask; geo_mask = GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE | GDK_HINT_BASE_SIZE; gtk_window_set_geometry_hints(GTK_WINDOW(ghb_window), ghb_window, &geo, geo_mask); window_width = ghb_dict_get_int(ud->prefs, "window_width"); window_height = ghb_dict_get_int(ud->prefs, "window_height"); /* * Filter objects in GtkBuilder xml * Unfortunately, GtkFilter is poorly supported by GtkBuilder, * so a lot of the setup must happen in code. SourceFilterAll SourceFilterVideo SourceFilterTS SourceFilterMPG SourceFilterEVO SourceFilterVOB SourceFilterMKV SourceFilterMP4 SourceFilterAVI SourceFilterMOV SourceFilterOGG SourceFilterFLV SourceFilterWMV */ // Add filters to source chooser GtkFileFilter *filter; GtkFileChooser *chooser; chooser = GTK_FILE_CHOOSER(GHB_WIDGET(ud->builder, "source_dialog")); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAll")); gtk_file_filter_set_name(filter, _("All")); gtk_file_filter_add_pattern(filter, "*"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterVideo")); gtk_file_filter_set_name(filter, _("Video")); gtk_file_filter_add_mime_type(filter, "video/*"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterTS")); gtk_file_filter_set_name(filter, "TS"); gtk_file_filter_add_pattern(filter, "*.ts"); gtk_file_filter_add_pattern(filter, "*.TS"); gtk_file_filter_add_pattern(filter, "*.m2ts"); gtk_file_filter_add_pattern(filter, "*.M2TS"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMPG")); gtk_file_filter_set_name(filter, "MPG"); gtk_file_filter_add_pattern(filter, "*.mpg"); gtk_file_filter_add_pattern(filter, "*.MPG"); gtk_file_filter_add_pattern(filter, "*.mepg"); gtk_file_filter_add_pattern(filter, "*.MEPG"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterEVO")); gtk_file_filter_set_name(filter, "EVO"); gtk_file_filter_add_pattern(filter, "*.evo"); gtk_file_filter_add_pattern(filter, "*.EVO"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterVOB")); gtk_file_filter_set_name(filter, "VOB"); gtk_file_filter_add_pattern(filter, "*.vob"); gtk_file_filter_add_pattern(filter, "*.VOB"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMKV")); gtk_file_filter_set_name(filter, "MKV"); gtk_file_filter_add_pattern(filter, "*.mkv"); gtk_file_filter_add_pattern(filter, "*.MKV"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMP4")); gtk_file_filter_set_name(filter, "MP4"); gtk_file_filter_add_pattern(filter, "*.mp4"); gtk_file_filter_add_pattern(filter, "*.MP4"); gtk_file_filter_add_pattern(filter, "*.m4v"); gtk_file_filter_add_pattern(filter, "*.M4V"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMOV")); gtk_file_filter_set_name(filter, "MOV"); gtk_file_filter_add_pattern(filter, "*.mov"); gtk_file_filter_add_pattern(filter, "*.MOV"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAVI")); gtk_file_filter_set_name(filter, "AVI"); gtk_file_filter_add_pattern(filter, "*.avi"); gtk_file_filter_add_pattern(filter, "*.AVI"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterOGG")); gtk_file_filter_set_name(filter, "OGG"); gtk_file_filter_add_pattern(filter, "*.ogg"); gtk_file_filter_add_pattern(filter, "*.OGG"); gtk_file_filter_add_pattern(filter, "*.ogv"); gtk_file_filter_add_pattern(filter, "*.OGV"); gtk_file_filter_add_pattern(filter, "*.ogm"); gtk_file_filter_add_pattern(filter, "*.OGM"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterFLV")); gtk_file_filter_set_name(filter, "FLV"); gtk_file_filter_add_pattern(filter, "*.flv"); gtk_file_filter_add_pattern(filter, "*.FLV"); gtk_file_chooser_add_filter(chooser, filter); filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterWMV")); gtk_file_filter_set_name(filter, "WMV"); gtk_file_filter_add_pattern(filter, "*.wmv"); gtk_file_filter_add_pattern(filter, "*.WMV"); gtk_file_chooser_add_filter(chooser, filter); // Gtk has a really stupid bug. If the file chooser is showing // hidden files AND there is no filter set, it will not select // the filename when gtk_file_chooser_set_filename is called. // So add a completely unnessary filter to prevent this behavior. filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAll")); gtk_file_chooser_set_filter(chooser, filter); PangoFontDescription *font_desc; font_desc = pango_font_description_from_string("monospace 10"); textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "activity_view")); gtk_widget_override_font(GTK_WIDGET(textview), font_desc); pango_font_description_free(font_desc); // Grrrr! Gtk developers !!!hard coded!!! the width of the // radio buttons in GtkStackSwitcher to 100!!! // // Thankfully, GtkStackSwitcher is a regular container object // and we can access the buttons to change their width. GList *stack_switcher_children, *link; GtkContainer * stack_switcher = GTK_CONTAINER( GHB_WIDGET(ud->builder, "SettingsStackSwitcher")); link = stack_switcher_children = gtk_container_get_children(stack_switcher); while (link != NULL) { GtkWidget *widget = link->data; gtk_widget_set_size_request(widget, -1, -1); gtk_widget_set_hexpand(widget, TRUE); gtk_widget_set_halign(widget, GTK_ALIGN_FILL); link = link->next; } g_list_free(stack_switcher_children); gtk_window_resize(GTK_WINDOW(ghb_window), window_width, window_height); gtk_widget_show(ghb_window); // Everything should be go-to-go. Lets rock! gtk_main(); ghb_backend_close(); ghb_value_free(&ud->queue); ghb_value_free(&ud->settings_array); ghb_value_free(&ud->prefs); ghb_value_free(&ud->globals); ghb_value_free(&ud->x264_priv); g_io_channel_unref(ud->activity_log); ghb_settings_close(); ghb_resource_free(); #if !defined(_WIN32) notify_uninit(); #endif g_object_unref(ud->builder); g_free(ud->current_dvd_device); g_free(ud); return 0; }
int main (int argc, char *argv[]) { TrackerConfig *config; TrackerController *controller; GOptionContext *context; GMainLoop *loop; GError *error = NULL; gchar *log_filename; guint shutdown_timeout; /* Set up locale */ setlocale (LC_ALL, ""); bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); /* Translators: this message will appear immediately after the * usage string - Usage: COMMAND <THIS_MESSAGE> */ context = g_option_context_new (_("- start the tracker writeback service")); g_option_context_add_main_entries (context, entries, NULL); g_option_context_parse (context, &argc, &argv, &error); g_option_context_free (context); if (version) { g_print ("\n" ABOUT "\n" LICENSE "\n"); return EXIT_SUCCESS; } /* Initialize logging */ config = tracker_config_new (); if (verbosity > -1) { tracker_config_set_verbosity (config, verbosity); } tracker_log_init (tracker_config_get_verbosity (config), &log_filename); if (log_filename != NULL) { g_message ("Using log file:'%s'", log_filename); g_free (log_filename); } sanity_check_option_values (config); if (disable_shutdown) { shutdown_timeout = 0; } else { shutdown_timeout = QUIT_TIMEOUT; } controller = tracker_controller_new (shutdown_timeout, &error); if (error) { g_critical ("Error creating controller: %s", error->message); g_error_free (error); return EXIT_FAILURE; } g_message ("Main thread is: %p", g_thread_self ()); loop = g_main_loop_new (NULL, FALSE); g_main_loop_run (loop); tracker_log_shutdown (); g_object_unref (controller); g_main_loop_unref (loop); g_object_unref (config); return EXIT_SUCCESS; }