Exemplo n.º 1
0
void
gmameui_init (void)
{
	gchar *filename;
#ifdef ENABLE_JOYSTICK
	gboolean usejoyingui;
#endif
	
#ifdef ENABLE_DEBUG
	GTimer *mytimer;

	mytimer = g_timer_new ();
	g_timer_start (mytimer);
#endif

	/* FIXME TODO Move to mame_options_init () */
	filename = g_build_filename (g_get_user_config_dir (), "gmameui", "options", NULL);
	if (!g_file_test (filename, G_FILE_TEST_IS_DIR)) {
		GMAMEUI_DEBUG ("no options directory creating one");
		g_mkdir (filename, S_IRWXU);
	}
	g_free (filename);

	GMAMEUI_DEBUG (_("Initialising list of possible MAME executable options"));
	xmame_options_init ();
	
	GMAMEUI_DEBUG (_("Initialising MAME executables"));
	main_gui.exec_list = mame_exec_list_new ();
	
	/* Load GUI preferences */
	main_gui.gui_prefs = mame_gui_prefs_new ();

	/* Set the MAME executable list */
	GValueArray *va_exec_paths;
	gchar *mame_executable = NULL;
	guint i;
	g_object_get (main_gui.gui_prefs,
		      "executable-paths", &va_exec_paths,
		      "current-executable", &mame_executable,
		      NULL);
	for (i = 0; i < va_exec_paths->n_values; i++) {
		GMAMEUI_DEBUG (_("Adding executable from preferences file: %s"),
			       g_value_get_string (g_value_array_get_nth (va_exec_paths, i)));
		
		MameExec *exec = mame_exec_new_from_path (g_value_get_string (g_value_array_get_nth (va_exec_paths, i)));
		mame_exec_list_add (main_gui.exec_list, exec);
		
		// FIXME TODO Unref the exec
	}
	g_value_array_free (va_exec_paths);
	
	if (mame_executable) {
		GMAMEUI_DEBUG ("Adding executable that was specified previously as %s", mame_executable);
		mame_exec_list_set_current_executable (main_gui.exec_list,
						       mame_exec_list_get_exec_by_path (main_gui.exec_list, mame_executable));
		g_free (mame_executable);
	} else if (mame_exec_list_size (main_gui.exec_list) > 0) {
		/* Only set a default executable if there are available ones to choose from */
		GMAMEUI_DEBUG ("Adding default executable in position 0");
		mame_exec_list_set_current_executable (main_gui.exec_list,
						       mame_exec_list_nth (main_gui.exec_list, 0));
	}

#ifdef ENABLE_DEBUG
g_message (_("Time to initialise: %.02f seconds"), g_timer_elapsed (mytimer, NULL));
#endif

	/* Create a new audit object */
	gui_prefs.audit = gmameui_audit_new ();

	/* Create a new IO Handler object */
	gui_prefs.io_handler = gmameui_io_handler_new ();

	/* Create a new romset fix list */
	gui_prefs.fixes = gmameui_romfix_list_new ();
	
	/* Initialise the gamelist */
	gui_prefs.gl = mame_gamelist_new ();
#ifdef ENABLE_DEBUG
	g_timer_stop (mytimer);
	g_message (_("Time to initialise GMAMEUI: %.02f seconds"), g_timer_elapsed (mytimer, NULL));
	g_timer_destroy (mytimer);
#endif

#ifdef ENABLE_JOYSTICK
	gchar *joystick_device;
	
	g_object_get (main_gui.gui_prefs,
		      "usejoyingui", &usejoyingui,
		      "joystick-name", &joystick_device,
		      NULL);
	if (usejoyingui) {
		joydata = joystick_new (joystick_device);

		if (joydata)
			g_message (_("Joystick %s found"), joydata->device_name);
		else
			g_message (_("No Joystick found"));
	}
	
	g_free (joystick_device);
#endif
	/* doesn't matter if joystick is enabled or not but easier to handle after */
	joy_focus_on ();

}
Exemplo n.º 2
0
int
phoneui_utils_sound_init_finish(GKeyFile *keyfile,char* suffix)
{
	int err, f;
	char *device_name;
	char *alsa;
	static GSourceFuncs funcs = {
		_sourcefunc_prepare,
		_sourcefunc_check,
		_sourcefunc_dispatch,
		0,
		0,
		0
	};

	alsa = malloc(strlen(suffix) + strlen("alsa") + 1);
	if (alsa) {
		strcpy(alsa, "alsa");
		strcat(alsa, suffix);
	}else{
		alsa = strdup("alsa");
		g_warning("Malloc failure in %s at line %d",__func__,__LINE__);
	}

	sound_state = SOUND_STATE_IDLE;
	sound_state_type = SOUND_STATE_TYPE_DEFAULT;

	device_name = g_key_file_get_string(keyfile, alsa, "hardware_control_name", NULL);
	if (!device_name) {
		g_message("No hw control found, using default");
		device_name = strdup("hw:0");
	}

	if (hctl) {
		snd_hctl_close(hctl);
	}
	err = snd_hctl_open(&hctl, device_name, 0);
	if (err) {
		g_warning("Cannot open alsa:hardware_control_name '%s': %s", device_name, snd_strerror(err));
		g_key_file_free(keyfile);
		return err;
	}

	err = snd_hctl_load(hctl);
	if (err) {
		g_warning("Cannot load alsa:hardware_control_name '%s': %s", device_name, snd_strerror(err));
	}
	
	free(device_name);

	/*FIXME: add idle bt */
	_phoneui_utils_sound_init_set_control(keyfile, "idle", suffix, SOUND_STATE_IDLE, SOUND_STATE_TYPE_HANDSET);
	_phoneui_utils_sound_init_set_control(keyfile, "bluetooth", suffix, SOUND_STATE_CALL, SOUND_STATE_TYPE_BLUETOOTH);
	_phoneui_utils_sound_init_set_control(keyfile, "handset", suffix, SOUND_STATE_CALL, SOUND_STATE_TYPE_HANDSET);
	_phoneui_utils_sound_init_set_control(keyfile, "headset", suffix, SOUND_STATE_CALL, SOUND_STATE_TYPE_HEADSET);
	_phoneui_utils_sound_init_set_control(keyfile, "speaker", suffix, SOUND_STATE_SPEAKER, SOUND_STATE_TYPE_HANDSET);

	snd_hctl_nonblock(hctl, 1);

	poll_fd_count = snd_hctl_poll_descriptors_count(hctl);
	poll_fds = malloc(sizeof(struct pollfd) * poll_fd_count);
	snd_hctl_poll_descriptors(hctl, poll_fds, poll_fd_count);

	source_alsa_poll = g_source_new(&funcs, sizeof(GSource));
	for (f = 0; f < poll_fd_count; f++) {
		g_source_add_poll(source_alsa_poll, (GPollFD *)&poll_fds[f]);
	}
	g_source_attach(source_alsa_poll, NULL);

	/*Register for HEADPHONE insertion */
	phoneui_info_register_input_events(_input_events_cb, NULL);

	fso_audio = (FreeSmartphoneDeviceAudio *)_fso
		(FREE_SMARTPHONE_DEVICE_TYPE_AUDIO_PROXY,
		 FSO_FRAMEWORK_DEVICE_ServiceDBusName,
		 FSO_FRAMEWORK_DEVICE_AudioServicePath,
		 FSO_FRAMEWORK_DEVICE_AudioServiceFace);

	g_key_file_free(keyfile);
	return err;
}
static void
run (const gchar      *name,
     gint              nparams,
     const GimpParam  *param,
     gint             *nreturn_vals,
     GimpParam       **return_vals)
{
  static GimpParam   values[1];
  gint32             image_ID;
  GimpRunMode        run_mode;
  GimpPDBStatusType  status    = GIMP_PDB_SUCCESS;
  gboolean           no_dialog;

  run_mode = param[0].data.d_int32;

  INIT_I18N ();

  no_dialog = (strcmp (name, "plug-in-sel2path") == 0);

  *nreturn_vals = 1;
  *return_vals = values;

  values[0].type = GIMP_PDB_STATUS;
  values[0].data.d_status = status;

  image_ID = param[1].data.d_image;
  if (image_ID < 0)
    {
      g_warning ("plug-in-sel2path needs a valid image ID");
      return;
    }

  if (gimp_selection_is_empty (image_ID))
    {
      g_message (_("No selection to convert"));
      return;
    }

  fit_set_default_params (&selVals);

  if (!no_dialog)
    {
      switch (run_mode)
        {
        case GIMP_RUN_INTERACTIVE:
          if (gimp_get_data_size ("plug-in-sel2path-advanced") > 0)
            {
              gimp_get_data ("plug-in-sel2path-advanced", &selVals);
            }

          if (!sel2path_dialog (&selVals))
            return;

          /* Get the current settings */
          fit_set_params (&selVals);
          break;

        case GIMP_RUN_NONINTERACTIVE:
          if (nparams != 23)
            status = GIMP_PDB_CALLING_ERROR;

          if (status == GIMP_PDB_SUCCESS)
            {
              selVals.align_threshold             =  param[3].data.d_float;
              selVals.corner_always_threshold     =  param[4].data.d_float;
              selVals.corner_surround             =  param[5].data.d_int8;
              selVals.corner_threshold            =  param[6].data.d_float;
              selVals.error_threshold             =  param[7].data.d_float;
              selVals.filter_alternative_surround =  param[8].data.d_int8;
              selVals.filter_epsilon              =  param[9].data.d_float;
              selVals.filter_iteration_count      = param[10].data.d_int8;
              selVals.filter_percent              = param[11].data.d_float;
              selVals.filter_secondary_surround   = param[12].data.d_int8;
              selVals.filter_surround             = param[13].data.d_int8;
              selVals.keep_knees                  = param[14].data.d_int8;
              selVals.line_reversion_threshold    = param[15].data.d_float;
              selVals.line_threshold              = param[16].data.d_float;
              selVals.reparameterize_improvement  = param[17].data.d_float;
              selVals.reparameterize_threshold    = param[18].data.d_float;
              selVals.subdivide_search            = param[19].data.d_float;
              selVals.subdivide_surround          = param[20].data.d_int8;
              selVals.subdivide_threshold         = param[21].data.d_float;
              selVals.tangent_surround            = param[22].data.d_int8;
              fit_set_params (&selVals);
            }
          break;

        case GIMP_RUN_WITH_LAST_VALS:
          if(gimp_get_data_size ("plug-in-sel2path-advanced") > 0)
            {
              gimp_get_data ("plug-in-sel2path-advanced", &selVals);

              /* Set up the last values */
              fit_set_params (&selVals);
            }
          break;

        default:
          break;
        }
    }

  sel2path (image_ID);
  values[0].data.d_status = status;

  if (status == GIMP_PDB_SUCCESS)
    {
      dialog_print_selVals(&selVals);
      if (run_mode == GIMP_RUN_INTERACTIVE && !no_dialog)
        gimp_set_data ("plug-in-sel2path-advanced", &selVals, sizeof(SELVALS));
    }
}
Exemplo n.º 4
0
int main(int argc, char **argv) {
	GOptionContext *context;
	RoccatDevice *konextdoptical;
	GError *local_error = NULL;
	int retval = EXIT_SUCCESS;
	KoneplusRmp *rmp = NULL;

	roccat_secure();
	roccat_textdomain();

	context = commandline_parse(&argc, &argv);

	if (parameter_just_print_version) {
		g_print(VERSION_STRING "\n");
		goto exit1;
	}

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

	konextdoptical = konextdoptical_device_first();
	if (konextdoptical == NULL) {
		g_critical(_("No %s found."), KONEXTDOPTICAL_DEVICE_NAME);
		retval = EXIT_FAILURE;
		goto exit1;
	}

	if (parameter_just_activate_driver_state) {
		if (!koneplus_device_state_write(konextdoptical, KONEPLUS_DEVICE_STATE_STATE_ON, &local_error)) {
			g_critical(_("Could not activate driver state: %s"), local_error->message);
			retval = EXIT_FAILURE;
		}
		goto exit2;
	}

	if (parameter_just_deactivate_driver_state) {
		if (!koneplus_device_state_write(konextdoptical, KONEPLUS_DEVICE_STATE_STATE_OFF, &local_error)) {
			g_critical(_("Could not deactivate driver state: %s"), local_error->message);
			retval = EXIT_FAILURE;
		}
		goto exit2;
	}

	if (parameter_just_update_firmware) {
		if (!update_firmware(konextdoptical, parameter_just_update_firmware, &local_error)) {
			g_critical(_("Could not update firmware: %s"), local_error->message);
			retval = EXIT_FAILURE;
		} else
			g_message(_("Firmware updated successfully. Please reconnect device."));
		goto exit2;
	}

	if (parameter_just_print_actual_profile) {
		if (!print_actual_profile(konextdoptical, &local_error)) {
			g_critical(_("Could not print actual profile: %s"), local_error->message);
			retval = EXIT_FAILURE;
		}
		goto exit2;
	}

	if (parameter_just_reset) {
		if (!reset(konextdoptical, &local_error)) {
			g_critical(_("Could not reset device: %s"), local_error->message);
			retval = EXIT_FAILURE;
		}
		goto exit2;
	}

	if (parameter_read_firmware) {
		if (!print_firmware(konextdoptical, &local_error)) {
			g_critical(_("Could not print firmware version: %s"), local_error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	}

	if (parameter_sensor_read) {
		if (!print_sensor_value(konextdoptical, &local_error)) {
			g_critical(_("Could not read sensor register: %s"), local_error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	}

	if (parameter_sensor_write != -1) {
		koneplus_sensor_write_register(konextdoptical, parameter_sensor_register, parameter_sensor_write, &local_error);
		if (local_error) {
			g_critical(_("Could not write sensor register: %s"), local_error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	}

	if (parameter_load != -1) {
		rmp = konextdoptical_rmp_load(konextdoptical, parameter_load - 1, &local_error);
		if (!rmp) {
			g_critical(_("Could not load profile %i: %s"), parameter_load, local_error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	} else if (parameter_in_rmp) {
		rmp = koneplus_rmp_read_with_path(parameter_in_rmp, konextdoptical_rmp_defaults(), &local_error);
		if (!rmp) {
			g_critical(_("Could not read rmp %s: %s"), parameter_in_rmp, local_error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	} else
		rmp = konextdoptical_default_rmp();

	koneplus_rmp_set_modified(rmp);

	if (parameter_save != -1) {
		if (!konextdoptical_rmp_save(konextdoptical, rmp, parameter_save - 1, &local_error)) {
			g_critical(_("Could not save profile %i: %s"), parameter_save, local_error->message);
			retval = EXIT_FAILURE;
			goto exit3;
		}
		konextdoptical_dbus_emit_profile_data_changed_outside_instant(parameter_save);
	}

	if (parameter_out_rmp) {
		if (!koneplus_rmp_write_with_path(parameter_out_rmp, rmp, &local_error)) {
			g_critical(_("Could not write rmp %s: %s"), parameter_out_rmp, local_error->message);
			retval = EXIT_FAILURE;
			goto exit3;
		}
	}

	if (parameter_activate_profile != -1) {
		if (!koneplus_actual_profile_write(konextdoptical, parameter_activate_profile -1, &local_error)) {
			g_critical(_("Could not activate profile %i: %s"), parameter_activate_profile, local_error->message);
			retval = EXIT_FAILURE;
			goto exit3;
		}
		konextdoptical_dbus_emit_profile_changed_outside_instant(parameter_activate_profile);
	}

exit3:
	koneplus_rmp_free(rmp);
exit2:
	g_object_unref(G_OBJECT(konextdoptical));
exit1:
	commandline_free(context);
	g_clear_error(&local_error);
	exit(retval);
}
Exemplo n.º 5
0
GNCLot *
gncOwnerCreatePaymentLot (const GncOwner *owner, Transaction *txn,
                          Account *posted_acc, Account *xfer_acc,
                          gnc_numeric amount, gnc_numeric exch, Timespec date,
                          const char *memo, const char *num)
{
    QofBook *book;
    Split *split;
    const char *name;
    gnc_commodity *commodity;
    Split *xfer_split = NULL;
    GNCLot *payment_lot;

    /* Verify our arguments */
    if (!owner || !posted_acc || !xfer_acc) return NULL;
    g_return_val_if_fail (owner->owner.undefined != NULL, NULL);

    /* Compute the ancillary data */
    book = gnc_account_get_book (posted_acc);
    name = gncOwnerGetName (gncOwnerGetEndOwner ((GncOwner*)owner));
    commodity = gncOwnerGetCurrency (owner);
//    reverse = use_reversed_payment_amounts(owner);

    if (txn)
    {
        /* Pre-existing transaction was specified. We completely clear it,
         * except for the split in the transfer account, unless the
         * transaction can't be reused (wrong currency, wrong transfer account).
         * In that case, the transaction is simply removed and an new
         * one created. */

        xfer_split = xaccTransFindSplitByAccount(txn, xfer_acc);

        if (xaccTransGetCurrency(txn) != gncOwnerGetCurrency (owner))
        {
            g_message("Uh oh, mismatching currency/commodity between selected transaction and owner. We fall back to manual creation of a new transaction.");
            xfer_split = NULL;
        }

        if (!xfer_split)
        {
            g_message("Huh? Asset account not found anymore. Fully deleting old txn and now creating a new one.");

            xaccTransBeginEdit (txn);
            xaccTransDestroy (txn);
            xaccTransCommitEdit (txn);

            txn = NULL;
        }
        else
        {
            int i = 0;
            xaccTransBeginEdit (txn);
            while (i < xaccTransCountSplits(txn))
            {
                Split *split = xaccTransGetSplit (txn, i);
                if (split == xfer_split)
                {
                    gnc_set_num_action (NULL, split, num, _("Payment"));
                    ++i;
                }
                else
                {
                    xaccSplitDestroy(split);
                }
            }
            /* Note: don't commit transaction now - that would insert an imbalance split.*/
        }
    }

    /* Create the transaction if we don't have one yet */
    if (!txn)
    {
        txn = xaccMallocTransaction (book);
        xaccTransBeginEdit (txn);
    }

    /* Insert a split for the transfer account if we don't have one yet */
    if (!xfer_split)
    {

        /* Set up the transaction */
        xaccTransSetDescription (txn, name ? name : "");
        /* set per book option */
        xaccTransSetCurrency (txn, commodity);
        xaccTransSetDateEnteredSecs (txn, gnc_time (NULL));
        xaccTransSetDatePostedTS (txn, &date);


        /* The split for the transfer account */
        split = xaccMallocSplit (book);
        xaccSplitSetMemo (split, memo);
        /* set per book option */
        gnc_set_num_action (NULL, split, num, _("Payment"));
        xaccAccountBeginEdit (xfer_acc);
        xaccAccountInsertSplit (xfer_acc, split);
        xaccAccountCommitEdit (xfer_acc);
        xaccTransAppendSplit (txn, split);

        if (gnc_commodity_equal(xaccAccountGetCommodity(xfer_acc), commodity))
        {
            xaccSplitSetBaseValue (split, amount, commodity);
        }
        else
        {
            /* Need to value the payment in terms of the owner commodity */
            gnc_numeric payment_value = gnc_numeric_mul(amount,
                                        exch, GNC_DENOM_AUTO, GNC_HOW_RND_ROUND_HALF_UP);

            xaccSplitSetAmount(split, amount);
            xaccSplitSetValue(split, payment_value);
        }
    }

    /* Add a split in the post account */
    split = xaccMallocSplit (book);
    xaccSplitSetMemo (split, memo);
    /* set per book option */
    gnc_set_num_action (NULL, split, num, _("Payment"));
    xaccAccountBeginEdit (posted_acc);
    xaccAccountInsertSplit (posted_acc, split);
    xaccAccountCommitEdit (posted_acc);
    xaccTransAppendSplit (txn, split);
    xaccSplitSetBaseValue (split, gnc_numeric_neg (amount), commodity);

    /* Create a new lot for the payment */
    payment_lot = gnc_lot_new (book);
    gncOwnerAttachToLot (owner, payment_lot);
    gnc_lot_add_split (payment_lot, split);

    /* Mark the transaction as a payment */
    gnc_set_num_action (txn, NULL, num, _("Payment"));
    xaccTransSetTxnType (txn, TXN_TYPE_PAYMENT);

    /* Commit this new transaction */
    xaccTransCommitEdit (txn);

    return payment_lot;
}
Exemplo n.º 6
0
GdkGLProc
gdk_gl_get_proc_address (const char *proc_name)
{
  typedef GdkGLProc (*__glXGetProcAddressProc) (const GLubyte *);
  static __glXGetProcAddressProc glx_get_proc_address = (__glXGetProcAddressProc) -1;
  gchar *file_name;
  GModule *module;
  GdkGLProc proc_address = NULL;

  GDK_GL_NOTE_FUNC ();

  if (strncmp ("glu", proc_name, 3) != 0)
    {
      if (glx_get_proc_address == (__glXGetProcAddressProc) -1)
        {
          /*
           * Look up glXGetProcAddress () function.
           */

          file_name = g_module_build_path (NULL, "GL");
          GDK_GL_NOTE (MISC, g_message (" - Open %s", file_name));
          module = g_module_open (file_name, G_MODULE_BIND_LAZY);
          g_free (file_name);

          if (module != NULL)
            {
              g_module_symbol (module, "glXGetProcAddress",
                               (gpointer) &glx_get_proc_address);
              if (glx_get_proc_address == NULL)
                {
                  g_module_symbol (module, "glXGetProcAddressARB",
                                   (gpointer) &glx_get_proc_address);
                  if (glx_get_proc_address == NULL)
                    {
                      g_module_symbol (module, "glXGetProcAddressEXT",
                                       (gpointer) &glx_get_proc_address);
                    }
                }
              GDK_GL_NOTE (MISC, g_message (" - glXGetProcAddress () - %s",
                                            glx_get_proc_address ? "supported" : "not supported"));
              g_module_close (module);
            }
          else
            {
              g_warning ("Cannot open %s", file_name);
              glx_get_proc_address = NULL;
              return NULL;
            }
        }

      /* Try glXGetProcAddress () */

      if (glx_get_proc_address != NULL)
        {
          proc_address = glx_get_proc_address (proc_name);
          GDK_GL_NOTE (IMPL, g_message (" ** glXGetProcAddress () - %s",
                                        proc_address ? "succeeded" : "failed"));
          if (proc_address != NULL)
            return proc_address;
        }

      /* Try g_module_symbol () */

      /* libGL */
      file_name = g_module_build_path (NULL, "GL");
      GDK_GL_NOTE (MISC, g_message (" - Open %s", file_name));
      module = g_module_open (file_name, G_MODULE_BIND_LAZY);
      g_free (file_name);

      if (module != NULL)
        {
          g_module_symbol (module, proc_name, (gpointer) &proc_address);
          GDK_GL_NOTE (MISC, g_message (" - g_module_symbol () - %s",
                                        proc_address ? "succeeded" : "failed"));
          g_module_close (module);
        }
      else
        {
          g_warning ("Cannot open %s", file_name);
        }

      if (proc_address == NULL)
        {
          /* libGLcore */
          file_name = g_module_build_path (NULL, "GLcore");
          GDK_GL_NOTE (MISC, g_message (" - Open %s", file_name));
          module = g_module_open (file_name, G_MODULE_BIND_LAZY);
          g_free (file_name);

          if (module != NULL)
            {
              g_module_symbol (module, proc_name, (gpointer) &proc_address);
              GDK_GL_NOTE (MISC, g_message (" - g_module_symbol () - %s",
                                            proc_address ? "succeeded" : "failed"));
              g_module_close (module);
            }
        }
    }
  else
    {
      /* libGLU */
      file_name = g_module_build_path (NULL, "GLU");
      GDK_GL_NOTE (MISC, g_message (" - Open %s", file_name));
      module = g_module_open (file_name, G_MODULE_BIND_LAZY);
      g_free (file_name);

      if (module != NULL)
        {
          g_module_symbol (module, proc_name, (gpointer) &proc_address);
          GDK_GL_NOTE (MISC, g_message (" - g_module_symbol () - %s",
                                        proc_address ? "succeeded" : "failed"));
          g_module_close (module);
        }
      else
        {
          g_warning ("Cannot open %s", file_name);
        }
    }

  return proc_address;
}
Exemplo n.º 7
0
int
main (gint argc, gchar *argv[])
{
	TrackerConfig *config;
	TrackerMiner *miner_files;
	TrackerMinerFilesIndex *miner_files_index;
	GOptionContext *context;
	GError *error = NULL;
	gchar *log_filename = NULL;
	gboolean do_mtime_checking;
	gboolean do_crawling;
	gboolean force_mtime_checking = FALSE;
	gboolean store_available;

	main_loop = NULL;

	setlocale (LC_ALL, "");

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

	/* Set timezone info */
	tzset ();

	/* Translators: this messagge will apper immediately after the
	 * usage string - Usage: COMMAND <THIS_MESSAGE>
	 */
	context = g_option_context_new (_("- start the tracker indexer"));

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

	if (error) {
		g_printerr ("%s\n", error->message);
		g_error_free (error);
		return EXIT_FAILURE;
	}

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

	if (eligible) {
		check_eligible ();
		return EXIT_SUCCESS;
	}

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

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

	if (initial_sleep > -1) {
		tracker_config_set_initial_sleep (config, initial_sleep);
	}

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

	sanity_check_option_values (config);

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

	main_loop = g_main_loop_new (NULL, FALSE);

	g_message ("Checking if we're running as a daemon:");
	g_message ("  %s %s",
	           no_daemon ? "No" : "Yes",
	           no_daemon ? "(forced by command line)" : "");

	/* Create new TrackerMinerFiles object */
	miner_files = tracker_miner_files_new (config, &error);
	if (!miner_files) {
		g_critical ("Couldn't create new Files miner: '%s'",
		            error ? error->message : "unknown error");
		g_object_unref (config);
		tracker_log_shutdown ();
		return EXIT_FAILURE;
	}

	tracker_writeback_init (TRACKER_MINER_FILES (miner_files),
	                        config,
	                        &error);

	if (error) {
		g_critical ("Couldn't create writeback handling: '%s'",
		            error ? error->message : "unknown error");
		g_object_unref (config);
		g_object_unref (miner_files);
		tracker_log_shutdown ();
		g_array_free (disable_options, TRUE);
		return EXIT_FAILURE;
	}

	/* Create new TrackerMinerFilesIndex object */
	miner_files_index = tracker_miner_files_index_new (TRACKER_MINER_FILES (miner_files));
	if (!miner_files_index) {
		g_object_unref (miner_files);
		tracker_writeback_shutdown ();
		g_object_unref (config);
		tracker_log_shutdown ();
		return EXIT_FAILURE;
	}

	/* Check if we should crawl and if we should force mtime
	 * checking based on the config.
	 */
	do_crawling = should_crawl (config, &force_mtime_checking);

	/* Get the last shutdown state to see if we need to perform a
	 * full mtime check against the db or not.
	 *
	 * Set to TRUE here in case we crash and miss file system
	 * events.
	 */
	g_message ("Checking whether to force mtime checking during crawling (based on last clean shutdown):");

	/* Override the shutdown state decision based on the config */
	if (force_mtime_checking) {
		do_mtime_checking = TRUE;
	} else {
		do_mtime_checking = tracker_db_manager_get_need_mtime_check ();
	}

	g_message ("  %s %s",
	           do_mtime_checking ? "Yes" : "No",
	           force_mtime_checking ? "(forced from config)" : "");

	/* Set the need for an mtime check to TRUE so we check in the
	 * event of a crash, this is changed back on shutdown if
	 * everything appears to be fine.
	 */
	tracker_db_manager_set_need_mtime_check (TRUE);

	/* Configure files miner */
	tracker_miner_fs_set_initial_crawling (TRACKER_MINER_FS (miner_files), do_crawling);
	tracker_miner_fs_set_mtime_checking (TRACKER_MINER_FS (miner_files), do_mtime_checking);
	g_signal_connect (miner_files, "finished",
			  G_CALLBACK (miner_finished_cb),
			  NULL);

	miners = g_slist_prepend (miners, miner_files);

	miner_handle_first (config, do_mtime_checking);

	initialize_signal_handler ();

	/* Go, go, go! */
	g_main_loop_run (main_loop);

	g_message ("Shutdown started");

	store_available = store_is_available ();

	if (miners_timeout_id == 0 &&
	    !miner_needs_check (miner_files, store_available)) {
		tracker_db_manager_set_need_mtime_check (FALSE);
	}

	g_main_loop_unref (main_loop);
	g_object_unref (config);
	g_object_unref (miner_files_index);

	g_slist_foreach (miners, (GFunc) finalize_miner, NULL);
	g_slist_free (miners);

	tracker_writeback_shutdown ();
	tracker_log_shutdown ();

	g_print ("\nOK\n\n");

	return EXIT_SUCCESS;
}
Exemplo n.º 8
0
void mwService_started(struct mwService *srvc) {
  g_return_if_fail(srvc != NULL);

  srvc->state = mwServiceState_STARTED;
  g_message("started service %s", NSTR(mwService_getName(srvc)));
}
Exemplo n.º 9
0
/// \brief Sets the samplerate of the oscilloscope.
/// \param samplerate The samplerate that should be met (S/s).
/// \return The samplerate that has been set.
unsigned long int fd_runtime_setsamplerate5200(FDRuntime* self, unsigned short int samplerateId)
{
	unsigned long int samplerate = self->samplerates[samplerateId];
	if(!fd_runtime_getdeviceisconnected(self) || samplerate == 0)
		return 0;

	// Pointers to needed commands
	FDCommandSetSamplerate5200* ss = (FDCommandSetSamplerate5200*)g_object_ref(self->commands[COMMAND_SETSAMPLERATE5200]);
	//FDCommandSetBuffer5200* sb = (FDCommandSetBuffer5200*)g_object_ref(self->commands[COMMAND_SETBUFFER5200]);
	FDCommandSetTrigger5200* st = (FDCommandSetTrigger5200*)g_object_ref(self->commands[COMMAND_SETTRIGGER5200]);

	unsigned char fastRate;
	unsigned short int value;
	unsigned char byte3;
	if (generate5200DividerValue(samplerate, &fastRate, &byte3, &value) < 0)
	{
		// Not using fastRate, because all fastRate modes are not dynamically generated.
		self->samplerateMax = self->samplerateChannelMax;
		if (fastRate)
			self->samplerateMax = self->samplerateFastMax;
		// The maximum sample rate depends on the buffer size
		unsigned int bufferDivider = 1;/*
		switch(commandSetBuffer5200->getBufferSize()) {
			case BUFFERID_ROLL:
				bufferDivider = 1000;
				break;
			case BUFFERID_LARGE:
				bufferDivider = 2;
				break;
			default:
				break;
		}*/

		// Get divider that would provide the requested rate, can't be zero
		self->samplerateMax /= bufferDivider;
		self->samplerateDivider = maxlong(self->samplerateMax / samplerate, (long unsigned int) 1);

		// Use normal mode if we need valueSlow or it would meet the rate at least as exactly as fast rate mode
		if(fastRate) {
			unsigned long int slowSamplerate = self->samplerateChannelMax / bufferDivider;
			unsigned long int slowDivider = maxlong(slowSamplerate / samplerate, (long unsigned int) 1);

			if(self->samplerateDivider > 4 || (abs((double) slowSamplerate / slowDivider - samplerate) <= abs(((double) self->samplerateMax / self->samplerateDivider) - samplerate))) {
				fastRate = FALSE;
				self->samplerateMax = slowSamplerate;
				self->samplerateDivider = slowDivider;
			}
		}
		g_message("Calculating new samplerate values. Requesting %lu S/s",samplerate);
		g_message("Using Samplerate: %lu  Using Divider: %lu", self->samplerateMax, self->samplerateDivider);
		// Split the resulting divider into the values understood by the device
		double computed = ((double)self->samplerateDivider - 3.0)/2.0;
		value = maxshort((unsigned short int)(computed+0.5), (unsigned short int)0);
	} else {
		self->samplerateMax = self->samplerateChannelMax;
		if (fastRate)
			self->samplerateMax = self->samplerateFastMax;
		self->samplerateDivider = maxlong(self->samplerateMax / samplerate, (long unsigned int) 1);
	}
	g_message("Value= %u  Byte3= %i  fastMode= %i",value, (unsigned int)byte3, (unsigned int)fastRate);

	// Store samplerate fast value
	fd_commandsetsamplerate5200_setSamplerateFast(ss, byte3);
	// Store samplerate slow value (two's complement)
	fd_commandsetsamplerate5200_setSamplerateSlow(ss, 0xffff - value);
	// Set fast rate when used
	fd_commandsettrigger5200_setFastRate(st, fastRate);
	g_object_unref(ss);
	g_object_unref(st);
	self->commandPending[COMMAND_SETSAMPLERATE5200] = TRUE;
	self->commandPending[COMMAND_SETTRIGGER5200] = TRUE;

	//self->updateBufferSize(self->bufferSize);
	//self->setTriggerSlope(self->triggerSlope);
	return self->samplerateMax / self->samplerateDivider;
}
Exemplo n.º 10
0
int main(int   argc,
	 char *argv[])
{
  if(setpgrp() < 0)
    perror("setpgrp()");

  if (parse_command_line(argc, argv) != 0)
    return 1;

#ifdef WIN32
  // if under windows, we need to define the locale directory
  bindtextdomain("poker2d", "./../locale");
#endif
  
  bind_textdomain_codeset("poker2d","UTF-8");    
  textdomain("poker2d");

  if (g_display)
  {
      char	tmp[64];
      snprintf(tmp, sizeof (tmp), "DISPLAY=%s", g_display);
      putenv(tmp);
  }
  
  if (g_gtk_rc_file)
  {
      char* file_name = strrchr(g_gtk_rc_file, '/')+1;

      int path_len = strlen(g_gtk_rc_file);
      int name_len = strlen(file_name);
      int newname_len = strlen(gettext(file_name));
      
      char* new_gtk_rc = malloc(sizeof(char)*(path_len-name_len+newname_len));
      memset(new_gtk_rc, 0, path_len-name_len+newname_len);
      memcpy(new_gtk_rc, g_gtk_rc_file, path_len-name_len);
      strcat(new_gtk_rc, gettext(file_name));
      
      char* tmp[2] = { new_gtk_rc, 0};
      gtk_rc_set_default_files(tmp);
      
      g_message("%s\n", new_gtk_rc);
      g_message(gettext("CANCEL"));
      
      g_free(g_gtk_rc_file);
      g_free(new_gtk_rc);
  }
  gtk_init (&argc, &argv);  

  set_verbose(g_want_verbose);

  if (!init_interface_io(g_hostname ? g_hostname : "127.0.0.1"))
    return 1;

  if (g_smiley_path)
    create_smiley_array(g_smiley_path, "smileys.xml");
  else
    create_smiley_array(".", "smileys.xml");
  gtk_main ();
  destroy_smiley_array();
  if (g_smiley_path) g_free(g_smiley_path);
  if (g_data_dir) g_free(g_data_dir);
  if (g_display) g_free(g_display);
  gui_set_glade_file(NULL);

  exit(0);
}
Exemplo n.º 11
0
/**
 * Remove cached file entry, logging success.
 */
static void
tth_cache_file_remove(const char *path, const char *reason)
{
	if (tth_cache_file_unlink(path, reason))
		g_message("removed %s TTH cache entry: %s", reason, path);
}
Exemplo n.º 12
0
/**
 * gimp_thumb_init:
 * @creator: an ASCII string that identifies the thumbnail creator
 * @thumb_basedir: an absolute path or %NULL to use the default
 *
 * This function initializes the thumbnail system. It must be called
 * before any other functions from libgimpthumb are used. You may call
 * it more than once if you want to change the @thumb_basedir but if
 * you do that, you should make sure that no thread is still using the
 * library. Apart from this function, libgimpthumb is multi-thread
 * safe.
 *
 * The @creator string must be 7bit ASCII and should contain the name
 * of the software that creates the thumbnails. It is used to handle
 * thumbnail creation failures. See the spec for more details.
 *
 * Usually you will pass %NULL for @thumb_basedir. Thumbnails will
 * then be stored in the user's personal thumbnail directory as
 * defined in the spec. If you wish to use libgimpthumb to store
 * application-specific thumbnails, you can specify a different base
 * directory here.
 *
 * Return value: %TRUE if the library was successfully initialized.
 **/
gboolean
gimp_thumb_init (const gchar *creator,
                 const gchar *thumb_basedir)
{
  GEnumClass *enum_class;
  GEnumValue *enum_value;
  gint        i;

  g_return_val_if_fail (creator != NULL, FALSE);
  g_return_val_if_fail (thumb_basedir == NULL ||
                        g_path_is_absolute (thumb_basedir), FALSE);

  if (gimp_thumb_initialized)
    gimp_thumb_exit ();

  if (thumb_basedir)
    {
      thumb_dir = g_strdup (thumb_basedir);
    }
  else
    {
      const gchar *home_dir = g_get_home_dir ();

      if (home_dir && g_file_test (home_dir, G_FILE_TEST_IS_DIR))
        {
          thumb_dir = g_build_filename (home_dir, ".thumbnails", NULL);
        }
      else
        {
          gchar *name = g_filename_display_name (g_get_tmp_dir ());

          g_message (_("Cannot determine a valid home directory.\n"
                       "Thumbnails will be stored in the folder for "
                       "temporary files (%s) instead."), name);
          g_free (name);

          thumb_dir = g_build_filename (g_get_tmp_dir (), ".thumbnails", NULL);
        }
    }

  enum_class = g_type_class_ref (GIMP_TYPE_THUMB_SIZE);

  thumb_num_sizes = enum_class->n_values;
  thumb_sizes     = g_new (gint, thumb_num_sizes);
  thumb_sizenames = g_new (const gchar *, thumb_num_sizes);
  thumb_subdirs   = g_new (gchar *, thumb_num_sizes);

  for (i = 0, enum_value = enum_class->values;
       i < enum_class->n_values;
       i++, enum_value++)
    {
      thumb_sizes[i]     = enum_value->value;
      thumb_sizenames[i] = enum_value->value_nick;
      thumb_subdirs[i]   = g_build_filename (thumb_dir,
                                             enum_value->value_nick, NULL);
    }

  thumb_fail_subdir = thumb_subdirs[0];
  thumb_subdirs[0]  = g_build_filename (thumb_fail_subdir, creator, NULL);

  g_type_class_unref (enum_class);

  gimp_thumb_initialized = TRUE;

  return gimp_thumb_initialized;
}
Exemplo n.º 13
0
void chassis_set_shutdown_location(const gchar* location) {
	if (signal_shutdown == 0) g_message("Initiating shutdown, requested from %s", (location != NULL ? location : "signal handler"));
	signal_shutdown = 1;
}
Exemplo n.º 14
0
int
main (int argc, char *argv[])
{
#ifdef ENABLE_NLS
	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (PACKAGE, "UTF-8");
#endif

	gtk_init (&argc, &argv);

	gmameui_init ();
	
	if (init_gui () == -1)
		return -1;

	/* Show a progress bar while the gamelist is being loaded */
	/* FIXME TODO These should be controlled via g_signal_emit
	   calls for loading the gamelist etc */
	gmameui_statusbar_start_pulse (main_gui.statusbar);
	gmameui_statusbar_set_progressbar_text (main_gui.statusbar,
	                                        _("Loading gamelist..."));
	
	if (!mame_gamelist_load (gui_prefs.gl)) {
		g_message (_("gamelist not found, need to rebuild one"));
		/* Loading the gamelist failed - prompt the user to recreate it */
		gamelist_check (mame_exec_list_get_current_executable (main_gui.exec_list));
	} else {
		//g_message (_("Time to load gamelist: %.02f seconds"), g_timer_elapsed (mytimer, NULL));

		gmameui_statusbar_set_progressbar_text (main_gui.statusbar,
	                                        _("Loading game data..."));
		if (!load_games_ini ())
			g_message (_("games.ini not loaded, using default values"));

		//g_message (_("Time to load games ini: %.02f seconds"), g_timer_elapsed (mytimer, NULL));

		/* Loading the catver file triggers the filters to be added to the
		   filter list, so the catver filters are added after the default ones */
		if (!load_catver_ini ())
			g_message (_("catver not loaded, using default values"));
	}
	
	/* FIXME TODO These should be controlled via g_signal_emit
	   calls for loading the gamelist etc */
	gmameui_statusbar_stop_pulse (main_gui.statusbar);
	
	mame_gamelist_view_repopulate_contents (main_gui.displayed_list);
	mame_gamelist_view_scroll_to_selected_game (main_gui.displayed_list);
	
	/* Load the default options */
	main_gui.options = mame_options_new ();
	main_gui.legacy_options = mame_options_legacy_new ();

	/* If no executables were found, prompt the user to open the directories
	   window to add at least one */
	if (mame_exec_list_size (main_gui.exec_list) == 0) {
		GtkWidget *dir_dlg, *msg_dlg;
		gint response;
		
		msg_dlg = gtk_message_dialog_new (GTK_WINDOW (MainWindow),
						  GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
						  GTK_MESSAGE_QUESTION,
						  GTK_BUTTONS_YES_NO,
						  _("No MAME executables were found"));
		gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (msg_dlg),
							  _("Do you want to locate a MAME executable now?"));
		
		response = gtk_dialog_run (GTK_DIALOG (msg_dlg));
		gtk_widget_destroy (msg_dlg);
		
		if (response == GTK_RESPONSE_YES) {
			dir_dlg = mame_directories_dialog_new (GTK_WINDOW (MainWindow));
			gtk_widget_show (dir_dlg);
		}
		
	} 

	GMAMEUI_DEBUG ("init done, starting main loop");
	gtk_main ();
	
	return 0;
}
Exemplo n.º 15
0
int
main (int argc, char **argv)
{
  gboolean arg_version = FALSE;
  gboolean arg_display_properties = FALSE;
  gboolean arg_display_about = FALSE;
  gboolean arg_consider_new_mail_as_read = FALSE;
  gboolean arg_update = FALSE;
  gboolean arg_print_summary = FALSE;
  gboolean arg_unset_obsolete_configuration = FALSE;
  gboolean arg_quit = FALSE;
  const GOptionEntry options[] = {
    {
      "version",
      'v',
      0,
      G_OPTION_ARG_NONE,
      &arg_version,
      N_("Show version information"),
      NULL
    },
    {
      "enable-info",
      'i',
      0,
      G_OPTION_ARG_NONE,
      &arg_enable_info,
      N_("Enable informational output"),
      NULL
    },
    {
      "display-properties",
      'p',
      0,
      G_OPTION_ARG_NONE,
      &arg_display_properties,
      N_("Display the properties dialog"),
      NULL
    },
    {
      "display-about",
      'a',
      0,
      G_OPTION_ARG_NONE,
      &arg_display_about,
      N_("Display the about dialog"),
      NULL
    },
    {
      "consider-new-mail-as-read",
      'r',
      0,
      G_OPTION_ARG_NONE,
      &arg_consider_new_mail_as_read,
      N_("Consider new mail as read"),
      NULL
    },
    {
      "update",
      'u',
      0,
      G_OPTION_ARG_NONE,
      &arg_update,
      N_("Update the mail status"),
      NULL
    },
    {
      "print-summary",
      's',
      0,
      G_OPTION_ARG_NONE,
      &arg_print_summary,
      N_("Print a XML mail summary"),
      NULL
    },
    {
      "unset-obsolete-configuration",
      '\0',
      0,
      G_OPTION_ARG_NONE,
      &arg_unset_obsolete_configuration,
      N_("Unset obsolete GConf configuration"),
      NULL
    },
    {
      "quit",
      'q',
      0,
      G_OPTION_ARG_NONE,
      &arg_quit,
      N_("Quit Mail Notification"),
      NULL
    },
    { NULL }
  };
  GOptionContext *option_context;
  DBusGConnection *bus;
  DBusGProxy *bus_proxy;

  g_log_set_fatal_mask(NULL, G_LOG_LEVEL_CRITICAL);
  g_log_set_handler(NULL, G_LOG_LEVEL_INFO, info_log_cb, NULL);

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

  g_set_application_name(_("Mail Notification"));

  g_thread_init(NULL);
  if (! g_thread_supported())
    /*
     * We cannot use mn_fatal_error_dialog() because gtk_init() has
     * not been called yet.
     */
    g_critical(_("multi-threading is not available"));
  gdk_threads_init();

  GDK_THREADS_ENTER();

  option_context = g_option_context_new(NULL);
  g_option_context_add_main_entries(option_context, options, GETTEXT_PACKAGE);

  gnome_program_init(PACKAGE,
		     VERSION,
		     LIBGNOME_MODULE,
		     argc,
		     argv,
		     GNOME_PARAM_HUMAN_READABLE_NAME, _("Mail Notification"),
		     GNOME_PROGRAM_STANDARD_PROPERTIES,
		     GNOME_PARAM_GOPTION_CONTEXT, option_context,
		     NULL);

  gtk_init(&argc, &argv);

  if (arg_version)
    {
      print_version();
      goto end;
    }

  if (arg_unset_obsolete_configuration)
    {
      mn_conf_unset_obsolete();
      goto end;
    }

  ensure_icon_path();
  gtk_window_set_default_icon_name("mail-notification");

  mn_stock_init();

  bus = connect_to_session_bus();
  bus_proxy = get_bus_proxy(bus);

  if (mn_server_start(bus, bus_proxy)) /* not already running */
    {
      if (arg_quit)
	g_message(_("Mail Notification is not running"));
      else
	{
	  mn_mailbox_init_types();
#if WITH_MBOX || WITH_MOZILLA || WITH_MH || WITH_MAILDIR || WITH_SYLPHEED
	  mn_vfs_mailbox_init_types();
#endif

	  /* mn-client-session uses sockets, we don't want to die on SIGPIPE */
	  signal(SIGPIPE, SIG_IGN);

	  if (! gnome_vfs_init())
	    mn_show_fatal_error_dialog(NULL, _("Unable to initialize the GnomeVFS library."));

#if !GTK_CHECK_VERSION(3,0,0)
	  gnome_authentication_manager_init();
#endif

	  /* must be called before init_gmime() */
	  mn_conf_init();

#if WITH_GMIME
	  init_gmime();
#endif

	  if (! notify_init(_("Mail Notification")))
	    mn_show_error_dialog(NULL,
				 _("An initialization error has occurred in Mail Notification"),
				 _("Unable to initialize the notification library. Message popups will not be displayed."));

	  /*
	   * Work around
	   * http://bugzilla.gnome.org/show_bug.cgi?id=64764:
	   * initialize the classes we will be using concurrently
	   * before any thread is created.
	   */
	  init_classes();

	  mn_shell_new(bus, bus_proxy);

	  /* also display the properties dialog if there are no mailboxes */
	  if (! mn_shell->mailboxes->list)
	    arg_display_properties = TRUE;

	  if (arg_display_properties)
	    mn_shell_show_properties_dialog(mn_shell, 0);
	  if (arg_display_about)
	    mn_shell_show_about_dialog(mn_shell, 0);
	  if (arg_consider_new_mail_as_read)
	    report_option_ignored("--consider-new-mail-as-read");
	  if (arg_update)
	    report_option_ignored("--update");
	  if (arg_print_summary)
	    report_option_ignored("--print-summary");

	  /* in case no window has been displayed */
	  gdk_notify_startup_complete();

	  gtk_main();
	}
    }
  else				/* already running */
    {
      DBusGProxy *proxy;
      GError *err = NULL;

      proxy = dbus_g_proxy_new_for_name(bus,
					MN_SERVER_SERVICE,
					MN_SERVER_PATH,
					MN_SERVER_INTERFACE);

      if (arg_quit)
	{
	  g_message(_("quitting Mail Notification"));
	  CALL_SERVER(org_gnome_MailNotification_quit(proxy, &err));
	}
      else
	{
	  /* also display the properties dialog if there are no mailboxes */
	  if (! arg_display_properties)
	    {
	      gboolean has;
	      CALL_SERVER(org_gnome_MailNotification_has_mailboxes(proxy, &has, &err));
	      arg_display_properties = ! has;
	    }

	  if (arg_display_properties)
	    CALL_SERVER(org_gnome_MailNotification_display_properties(proxy, &err));
	  if (arg_display_about)
	    CALL_SERVER(org_gnome_MailNotification_display_about(proxy, &err));
	  if (arg_consider_new_mail_as_read)
	    {
	      g_message(_("considering new mail as read"));
	      CALL_SERVER(org_gnome_MailNotification_consider_new_mail_as_read(proxy, &err));
	    }
	  if (arg_update)
	    {
	      g_message(_("updating the mail status"));
	      CALL_SERVER(org_gnome_MailNotification_update(proxy, &err));
	    }
	  if (arg_print_summary)
	    {
	      char *summary;

	      CALL_SERVER(org_gnome_MailNotification_get_summary(proxy, &summary, &err));
	      g_print("%s", summary);
	      g_free(summary);
	    }

	  if (! (arg_display_properties
		 || arg_display_about
		 || arg_consider_new_mail_as_read
		 || arg_update
		 || arg_print_summary))
	    g_message(_("Mail Notification is already running"));
	}

      /*
       * Do not unref the proxy, since it might break when the
       * DBusGProxy memory management issue is fixed
       * (https://bugs.freedesktop.org/show_bug.cgi?id=14030).
       */

      /* no window has been displayed by this process */
      gdk_notify_startup_complete();
    }

 end:
  GDK_THREADS_LEAVE();

  return 0;
}
Exemplo n.º 16
0
int fd_runtime_connectdevice(FDRuntime* self)
{
	FDDeviceClass *deviceclass = FD_DEVICE_GET_CLASS(FD_DEVICE(self->device));
	char* out = g_malloc0(256 * sizeof(char));
	pthread_mutex_lock(&FD_DEVICE(self->device)->deviceMutex);
	deviceclass->search(FD_DEVICE(self->device), &out); //search for device, grab a usb handle and model number.
	pthread_mutex_unlock(&FD_DEVICE(self->device)->deviceMutex);
	g_message("%s\n",out); //output of search function.
	g_free(out);
	switch (FD_DEVICE(self->device)->model)
	{
	case MODEL_DSO2090:
	case MODEL_DSO2100:
	case MODEL_DSO2150:
	case MODEL_DSO2250:
		self->gaincount = 9;
		double tempgains1[9] = {0.010, 0.020, 0.050, 0.100, 0.200, 0.500, 1.0, 2.0, 5.0};
		self->gains = g_malloc(sizeof(double)*self->gaincount);
		memcpy(self->gains, tempgains1, sizeof(double)*self->gaincount);
		self->sampleratecount = 16;
		unsigned long int tempsr1[16] = {100e6, 50e6, 25e6, 10e6, 5e6, 25e5, 1e6, 500e3, 250e3, 100e3, 50e3, 25e3, 10e3, 5e3, 25e2, 1e3};
		self->samplerates = g_malloc(sizeof(unsigned long int)*self->sampleratecount);
		memcpy(self->samplerates, tempsr1, sizeof(unsigned long int)*self->sampleratecount);
		break;

	case MODEL_DSO5200:
	case MODEL_DSO5200A:
		self->gaincount = 10;
		double tempgains2[10] = {0.010, 0.020, 0.050, 0.100, 0.200, 0.500, 1.0, 2.0, 5.0, 10.0};
		self->gains = g_malloc(sizeof(double)*self->gaincount);
		memcpy(self->gains, tempgains2, sizeof(double)*self->gaincount);
		self->sampleratecount = 17;
		unsigned long int tempsr2[17] = {250e6, 100e6, 50e6, 25e6, 10e6, 5e6, 25e5, 1e6, 500e3, 250e3, 100e3, 50e3, 25e3, 10e3, 5e3, 25e2, 1e3};
		self->samplerates = g_malloc(sizeof(unsigned long int)*self->sampleratecount);
		memcpy(self->samplerates, tempsr2, sizeof(unsigned long int)*self->sampleratecount);
		unsigned short int tempRanges[10] = {186, 370, 458, 916, 366, 450, 900, 368, 458, 908};
		self->ranges = g_malloc(sizeof(unsigned short int)*self->gaincount);
		memcpy(self->ranges, tempRanges, sizeof(unsigned short int)*self->gaincount);
		self->cal5200Data = g_malloc(sizeof(unsigned char)*6);
		break;

	case MODEL_UNKNOWN:
	default:
		self->gaincount = 6;
		double tempgains3[6] = {0.100, 0.200, 0.500, 1.0, 2.0, 5.0};
		self->gains = g_malloc(sizeof(double)*self->gaincount);
		memcpy(self->gains, tempgains3, sizeof(double)*self->gaincount);
		self->sampleratecount = 13;
		unsigned long int tempsr3[13] = {10e6, 5e6, 25e5, 1e6, 500e3, 250e3, 100e3, 50e3, 25e3, 10e3, 5e3, 25e2, 1e3};
		self->samplerates = g_malloc(sizeof(unsigned long int)*self->sampleratecount);
		memcpy(self->samplerates, tempsr3, sizeof(unsigned long int)*self->sampleratecount);
		break;
	}
	populateSamplerateComboBox(FD_UI(self->ui), self->samplerates, self->sampleratecount);
	populateGainComboBoxs(FD_UI(self->ui), self->gains, self->gaincount);
	self->samplerateFastMax = self->samplerates[0];
	self->samplerateChannelMax = self->samplerates[1];
	self->calibrationData = g_malloc(((sizeof(unsigned short int)*self->gaincount)*HANTEK_CHANNELS)*OFFSET_COUNT);
	getCalibrationData(self); //gets the channel level calibration data.
	printCalibrationData(self);
	self->calibration2Data = g_malloc(sizeof(unsigned char)*4);
	getCalibration2Data(self); //gets another calibration
	if (self->cal5200Data)
		getCal5200Data(self);
	self->currentAveraging[0] = 0;
	self->currentAveraging[1] = 0;
	fd_runtime_setdeviceisconnected(self, TRUE);
	fd_runtime_settriggersource(self, FALSE, 0);
	fd_runtime_settriggerposition(self, 0.5);
	fd_runtime_settriggerlevel(self, 0, 0.0);
	fd_runtime_settriggerslope(self, SLOPE_POSITIVE);
	fd_runtime_setbuffersize(self, 10240);
	fd_runtime_setchannelused(self, 1, FALSE);
	fd_runtime_setchannelused(self, 0, TRUE);
	fd_runtime_setoffset(self, 0, 0.5);
	fd_runtime_setoffset(self, 1, 0.5);
	setDefaultParameters(self);
	return 0;
}
Exemplo n.º 17
0
GdkGLProc
gdk_gl_get_proc_address (const char *proc_name)
{
  typedef GdkGLProc (*__glXGetProcAddressProc) (const GLubyte *);
  static __glXGetProcAddressProc glx_get_proc_address = (__glXGetProcAddressProc) -1;
  const char *image_name;
  static const struct mach_header *libgl_image = NULL;
  static const struct mach_header *libglu_image = NULL;
  NSSymbol symbol;
  char *symbol_name;
  GdkGLProc proc_address;

  GDK_GL_NOTE_FUNC ();

  if (strncmp ("glu", proc_name, 3) != 0)
    {
      /* libGL */

      if (libgl_image == NULL)
        {
          image_name = g_getenv ("GDK_GL_LIBGL_PATH");
          if (image_name == NULL)
            image_name = _GDK_GL_LIBGL_PATH;

          GDK_GL_NOTE (MISC, g_message (" - Add Mach-O image %s", image_name));

          libgl_image = NSAddImage (image_name, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
          if (libgl_image == NULL)
            {
              g_warning ("Cannot add Mach-O image %s", image_name);
              return NULL;
            }
        }

      if (glx_get_proc_address == (__glXGetProcAddressProc) -1)
        {
          /*
           * Look up glXGetProcAddress () function.
           */

          symbol = NSLookupSymbolInImage (libgl_image,
                                          "_glXGetProcAddress",
                                          NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                          NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
          if (symbol == NULL)
            {
              symbol = NSLookupSymbolInImage (libgl_image,
                                              "_glXGetProcAddressARB",
                                              NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                              NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
              if (symbol == NULL)
                {
                  symbol = NSLookupSymbolInImage (libgl_image,
                                                  "_glXGetProcAddressEXT",
                                                  NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                                  NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
                }
            }
          GDK_GL_NOTE (MISC, g_message (" - glXGetProcAddress () - %s",
                                        symbol ? "supported" : "not supported"));
          if (symbol != NULL)
            glx_get_proc_address = NSAddressOfSymbol (symbol);
          else
            glx_get_proc_address = NULL;
        }

      /* Try glXGetProcAddress () */

      if (glx_get_proc_address != NULL)
        {
          proc_address = glx_get_proc_address (proc_name);
          GDK_GL_NOTE (IMPL, g_message (" ** glXGetProcAddress () - %s",
                                        proc_address ? "succeeded" : "failed"));
          if (proc_address != NULL)
            return proc_address;
        }

      /* Try Mach-O dyld */

      symbol_name = g_strconcat ("_", proc_name, NULL);

      symbol = NSLookupSymbolInImage (libgl_image,
                                      symbol_name,
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
      GDK_GL_NOTE (MISC, g_message (" - NSLookupSymbolInImage () - %s",
                                    symbol ? "succeeded" : "failed"));

      g_free (symbol_name);

      if (symbol != NULL)
        return NSAddressOfSymbol (symbol);
    }
  else
    {
      /* libGLU */

      if (libglu_image == NULL)
        {
          image_name = g_getenv ("GDK_GL_LIBGLU_PATH");
          if (image_name == NULL)
            image_name = _GDK_GL_LIBGLU_PATH;

          GDK_GL_NOTE (MISC, g_message (" - Add Mach-O image %s", image_name));

          libglu_image = NSAddImage (image_name, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
          if (libglu_image == NULL)
            {
              g_warning ("Cannot add Mach-O image %s", image_name);
              return NULL;
            }
        }

      symbol_name = g_strconcat ("_", proc_name, NULL);

      symbol = NSLookupSymbolInImage (libglu_image,
                                      symbol_name,
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
                                      NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
      GDK_GL_NOTE (MISC, g_message (" - NSLookupSymbolInImage () - %s",
                                    symbol ? "succeeded" : "failed"));

      g_free (symbol_name);

      if (symbol != NULL)
        return NSAddressOfSymbol (symbol);
    }

  return NULL;
}
Exemplo n.º 18
0
void fd_runtime_run(void* arg)
{
	FDRuntime* self = FD_RUNTIME(arg);
	struct timespec interval, remainder;
	interval.tv_sec = 0;
	interval.tv_nsec = 49910000; //~50ms;
	unsigned short int x;
	int errorCode = 0;
	gboolean firstRun = TRUE;
	int captureState = CAPTURE_WAITING;
	//int lastCaptureState = -1;
	gboolean samplingStarted = FALSE;
	TriggerMode lastTriggerMode = (TriggerMode) -1;
	while (!fd_runtime_getdeviceisconnected(self))
	{
		sched_yield();
		nanosleep(&interval, &remainder);
		sched_yield();
	}
	while (captureState != LIBUSB_ERROR_NO_DEVICE && !fd_runtime_getstoprunning(self))
	{
		pthread_mutex_lock(&FD_DEVICE(self->device)->deviceMutex);
		for (x = 0; x < COMMAND_COUNT; x++)	{
			if (self->commandPending[x]) {
				fd_device_sendcommand(FD_DEVICE(self->device), self->commands[x]);
				self->commandPending[x] = FALSE;
			}
		}
		for (x = 0; x < CONTROLINDEX_COUNT; x++) {
			if (self->controlPending[x]) {
				fd_device_sendcontrol(FD_DEVICE(self->device), self->controls[x]);
				self->controlPending[x] = FALSE;
			}
		}
		pthread_mutex_unlock(&FD_DEVICE(self->device)->deviceMutex);
		sched_yield();
		nanosleep(&interval, &remainder);
		if(!self->sampling) {
			samplingStarted = FALSE;
			sched_yield();
			continue; //skip the rest of the loop.
		}
		sched_yield();
		pthread_mutex_lock(&FD_DEVICE(self->device)->deviceMutex);
		//lastCaptureState = captureState;
		if (!firstRun)
			captureState = fd_runtime_getcapturestate(self);
		//if(captureState != lastCaptureState)
			//g_message("Capture state changed to %i", captureState);

		switch(captureState) {
		case CAPTURE_READY:
		case CAPTURE_READY5200:
			// Get data and process it, if we're still sampling
			errorCode = getSamples(self, samplingStarted);
			if(errorCode < 0)
				g_message("Getting sample data failed: %i", errorCode);

			// Check if we're in single trigger mode
			if(self->triggerMode == TRIGGERMODE_SINGLE && samplingStarted)
				fd_runtime_stopsampling(self);

			// Sampling completed, restart it when necessary
			samplingStarted = FALSE;

			// Start next capture if necessary by leaving out the break statement
			if(!self->sampling)
				break;

		case CAPTURE_WAITING:
			if(samplingStarted && lastTriggerMode == self->triggerMode)
				break;
			if (firstRun)
				firstRun = FALSE;
			// Start capturing
			errorCode = fd_device_sendcommand(FD_DEVICE(self->device), self->commands[COMMAND_STARTSAMPLING]);
			if(errorCode < 0) {
				if(errorCode == LIBUSB_ERROR_NO_DEVICE)
					captureState = LIBUSB_ERROR_NO_DEVICE;
				break;
			}
			//g_message("Starting to capture");

			// Enable trigger
			errorCode = fd_device_sendcommand(FD_DEVICE(self->device), self->commands[COMMAND_ENABLETRIGGER]);
			if(errorCode < 0) {
				if(errorCode == LIBUSB_ERROR_NO_DEVICE)
					captureState = LIBUSB_ERROR_NO_DEVICE;
				break;
			}
			//g_message("Enabling trigger");

			if(self->triggerMode == TRIGGERMODE_AUTO) {
				// Force triggering
				errorCode = fd_device_sendcommand(FD_DEVICE(self->device), self->commands[COMMAND_FORCETRIGGER]);
				if(errorCode == LIBUSB_ERROR_NO_DEVICE)
					captureState = LIBUSB_ERROR_NO_DEVICE;
				//g_message("Forcing trigger");
			}
			samplingStarted = TRUE;
			lastTriggerMode = self->triggerMode;
			break;

		case CAPTURE_SAMPLING:
			break;
		default:
			if(captureState < 0)
				g_message("Getting capture state failed: %i", captureState);
			break;
		}
		pthread_mutex_unlock(&FD_DEVICE(self->device)->deviceMutex);
	}
}
Exemplo n.º 19
0
sc_bool sc_fs_storage_initialize(const gchar *path, sc_bool clear)
{
    g_message("Initialize sc-storage from path: %s", path);
    g_snprintf(segments_path, MAX_PATH_LENGTH, "%s/%s", path, seg_dir);
    repo_path = g_strdup(path);

    g_message("\tFile memory engine: %s", sc_config_fm_engine());
    // load engine extension

#ifdef WIN32
    g_snprintf(fm_engine_module_path, MAX_PATH_LENGTH, "sc-fm-%s.dll", sc_config_fm_engine());
#else
    g_snprintf(fm_engine_module_path, MAX_PATH_LENGTH, "libsc-fm-%s.so", sc_config_fm_engine());
#endif

    // try to load engine extension

    fFmEngineInitFunc func;
    fm_engine_module = g_module_open(fm_engine_module_path, G_MODULE_BIND_LOCAL);

    // skip non module files
    if (g_str_has_suffix(fm_engine_module_path, G_MODULE_SUFFIX) == TRUE)
    {
        if (fm_engine_module == nullptr)
        {
            g_critical("Can't load module: %s. Error: %s", fm_engine_module_path, g_module_error());
        }else
        {
            g_message("Initialize file memory engine from: %s", fm_engine_module_path);
            if (g_module_symbol(fm_engine_module, "initialize", (gpointer*) &func) == FALSE)
            {
                g_critical("Can't find 'initialize' symbol in module: %s", fm_engine_module_path);
            }else
            {
                fm_engine = func(repo_path);
                if (fm_engine == 0)
                {
                    g_critical("Can't create file memory engine from: %s", fm_engine_module_path);
                    return SC_FALSE;
                }
            }
        }
    }

    // clear repository if needs
    if (clear == SC_TRUE)
    {
        g_message("Clear file memory");
        if (g_file_test(segments_path, G_FILE_TEST_IS_DIR))
        {
            // remove all segments
            GDir *dir = 0;
            const gchar *fname = 0;
            char path[MAX_PATH_LENGTH];

            dir = g_dir_open(segments_path, 0, 0);
            g_assert( dir != (GDir*)0 );
            // calculate files
            fname = g_dir_read_name(dir);
            while (fname != 0)
            {
                g_snprintf(path, MAX_PATH_LENGTH, "%s/%s", segments_path, fname);

                if (g_file_test(path, G_FILE_TEST_IS_REGULAR))
                {
                    if (g_remove(path) == -1)
                    {
                        g_critical("Can't remove segment: %s", path);
                        g_dir_close(dir);
                        return SC_FALSE;
                    }
                }
                fname = g_dir_read_name(dir);
            }

            g_dir_close(dir);
        }

        if (sc_fm_clear(fm_engine) != SC_RESULT_OK)
        {
            g_critical("Can't clear file memory");
            return SC_FALSE;
        }
    }

    return SC_TRUE;
}
Exemplo n.º 20
0
int session_save(char *filename)
{
	GSList *l, *d;
	struct device *device;
	struct datastore *ds;
	struct zip *zipfile;
	struct zip_source *src;
	int bufcnt, devcnt, tmpfile, ret, error;
	char version[1], rawname[16], metafile[32], *buf;

	/* Quietly delete it first, libzip wants replace ops otherwise. */
	unlink(filename);

	if (!(zipfile = zip_open(filename, ZIP_CREATE, &error)))
		return SIGROK_ERR;

	/* Version */
	version[0] = '1';
	if (!(src = zip_source_buffer(zipfile, version, 1, 0)))
		return SIGROK_ERR;
	if (zip_add(zipfile, "version", src) == -1) {
		g_message("error saving version into zipfile: %s",
			  zip_strerror(zipfile));
		return SIGROK_ERR;
	}

	/* Metadata */
	strcpy(metafile, "sigrok-meta-XXXXXX");
	if ((tmpfile = g_mkstemp(metafile)) == -1)
		return SIGROK_ERR;
	close(tmpfile);
	make_metadata(metafile);
	if (!(src = zip_source_file(zipfile, metafile, 0, -1)))
		return SIGROK_ERR;
	if (zip_add(zipfile, "metadata", src) == -1)
		return SIGROK_ERR;
	unlink(metafile);

	/* Raw */
	devcnt = 1;
	for (l = session->devices; l; l = l->next) {
		device = l->data;
		ds = device->datastore;
		if (ds) {
			buf = malloc(ds->num_units * ds->ds_unitsize +
				   DATASTORE_CHUNKSIZE);
			bufcnt = 0;
			for (d = ds->chunklist; d; d = d->next) {
				memcpy(buf + bufcnt, d->data,
				       DATASTORE_CHUNKSIZE);
				bufcnt += DATASTORE_CHUNKSIZE;
			}
			if (!(src = zip_source_buffer(zipfile, buf,
				       ds->num_units * ds->ds_unitsize, TRUE)))
				return SIGROK_ERR;
			snprintf(rawname, 15, "raw-%d", devcnt);
			if (zip_add(zipfile, rawname, src) == -1)
				return SIGROK_ERR;
		}
		devcnt++;
	}

	if ((ret = zip_close(zipfile)) == -1) {
		g_message("error saving zipfile: %s", zip_strerror(zipfile));
		return SIGROK_ERR;
	}

	return SIGROK_OK;
}
Exemplo n.º 21
0
static void
gdict_applet_init (GdictApplet *applet)
{
  GdictAppletPrivate *priv;
  gchar *data_dir;

  priv = GDICT_APPLET_GET_PRIVATE (applet);
  applet->priv = priv;
      
  if (!priv->loader)
    priv->loader = gdict_source_loader_new ();

  /* add our data dir inside $HOME to the loader's search paths */
  data_dir = gdict_get_data_dir ();
  gdict_source_loader_add_search_path (priv->loader, data_dir);
  g_free (data_dir);
  
  gtk_window_set_default_icon_name ("accessories-dictionary");
  
  mate_panel_applet_set_flags (MATE_PANEL_APPLET (applet),
			  MATE_PANEL_APPLET_EXPAND_MINOR);

  priv->settings = g_settings_new (GDICT_SETTINGS_SCHEMA);
  priv->desktop_settings = g_settings_new (DESKTOP_SETTINGS_SCHEMA);

  g_signal_connect (priv->settings, "changed",
                    G_CALLBACK (gdict_applet_settings_changed_cb), applet);

  g_signal_connect (priv->desktop_settings, "changed",
                    G_CALLBACK (gdict_applet_settings_changed_cb), applet);

#ifndef GDICT_APPLET_STAND_ALONE
  mate_panel_applet_set_background_widget (MATE_PANEL_APPLET (applet),
		  		      GTK_WIDGET (applet));

  priv->size = mate_panel_applet_get_size (MATE_PANEL_APPLET (applet));

  switch (mate_panel_applet_get_orient (MATE_PANEL_APPLET (applet)))
    {
    case MATE_PANEL_APPLET_ORIENT_LEFT:
    case MATE_PANEL_APPLET_ORIENT_RIGHT:
      priv->orient = GTK_ORIENTATION_VERTICAL;
      break;
    case MATE_PANEL_APPLET_ORIENT_UP:
    case MATE_PANEL_APPLET_ORIENT_DOWN:
      priv->orient = GTK_ORIENTATION_HORIZONTAL;
      break;
    }
#else
  priv->size = 24;
  priv->orient = GTK_ORIENTATION_HORIZONTAL;
  g_message ("(in %s) applet { size = %d, orient = %s }",
  	     G_STRFUNC,
  	     priv->size,
  	     (priv->orient == GTK_ORIENTATION_HORIZONTAL ? "H" : "V"));
#endif /* !GDICT_APPLET_STAND_ALONE */

  priv->icon = gtk_icon_theme_load_icon (gtk_icon_theme_get_default (),
		  			 "accessories-dictionary",
					 48,
					 0,
					 NULL);
  
  /* force first draw */
  gdict_applet_draw (applet);

  /* force retrieval of the configuration from settings */
  gdict_applet_set_source_name (applet, NULL);
  gdict_applet_set_defbox_font (applet, NULL);
  gdict_applet_set_print_font (applet, NULL);
}
Exemplo n.º 22
0
static J4statusPluginContext *
_j4status_nl_init(J4statusCoreInterface *core)
{
    gchar **interfaces = NULL;
    guint64 addresses = ADDRESSES_ALL;

    GKeyFile *key_file;
    key_file = j4status_config_get_key_file("Netlink");
    if ( key_file != NULL )
    {
        interfaces = g_key_file_get_string_list(key_file, "Netlink", "Interfaces", NULL, NULL);
        j4status_config_key_file_get_enum(key_file, "Netlink", "Addresses", _j4status_nl_addresses, G_N_ELEMENTS(_j4status_nl_addresses), &addresses);

        g_key_file_free(key_file);
    }

    if ( interfaces == NULL )
    {
        g_message("No interface to monitor, aborting");
        return NULL;
    }

    gint err;
    J4statusPluginContext *self;

    self = g_new0(J4statusPluginContext, 1);
    self->addresses = addresses;

    self->sections = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, _j4status_nl_section_free);

    self->source = g_water_nl_source_new_cache_mngr(NULL, NETLINK_ROUTE, NL_AUTO_PROVIDE, &err);
    if ( self->source == NULL )
    {
        g_warning("Couldn't subscribe to events: %s", nl_geterror(err));
        goto error;
    }
    self->sock = g_water_nl_source_get_sock(self->source);
    self->cache_mngr = g_water_nl_source_get_cache_mngr(self->source);

    err = rtnl_link_alloc_cache(self->sock, AF_UNSPEC, &self->link_cache);
    if ( err < 0 )
    {
        g_warning("Couldn't allocate links cache: %s", nl_geterror(err));
        goto error;
    }

    err = nl_cache_mngr_add_cache(self->cache_mngr, self->link_cache, _j4status_nl_cache_change, self);
    if ( err < 0 )
    {
        g_warning("Couldn't manage links cache: %s", nl_geterror(err));
        goto error;
    }

    err = rtnl_addr_alloc_cache(self->sock, &self->addr_cache);
    if ( err < 0 )
    {
        g_warning("Couldn't allocate addresses cache: %s", nl_geterror(err));
        goto error;
    }

    err = nl_cache_mngr_add_cache(self->cache_mngr, self->addr_cache, _j4status_nl_cache_change, self);
    if ( err < 0 )
    {
        g_warning("Couldn't manage addresses cache: %s", nl_geterror(err));
        goto error;
    }

    gchar **interface;
    for ( interface = interfaces ; *interface != NULL ; ++interface )
    {
        J4statusNlSection *section;
        section = _j4status_nl_section_new(self, core, *interface);
        if ( section != NULL )
            g_hash_table_insert(self->sections, GINT_TO_POINTER(section->ifindex), section);
        else
            g_free(*interface);
    }

    g_free(interfaces);


    if ( g_hash_table_size(self->sections) < 1 )
        goto error;

    self->formats.up   = j4status_format_string_parse(NULL, _j4status_nl_format_up_tokens, G_N_ELEMENTS(_j4status_nl_format_up_tokens), J4STATUS_NL_DEFAULT_UP_FORMAT,   NULL);
    self->formats.down = j4status_format_string_parse(NULL, NULL,                          0,                                           J4STATUS_NL_DEFAULT_DOWN_FORMAT, NULL);


    return self;

error:
    _j4status_nl_uninit(self);
    return NULL;
}
Exemplo n.º 23
0
gboolean
biji_lazy_deserialize_internal (BijiLazyDeserializer *self)
{
  BijiNoteObj* n = self->priv->note;
  const gchar *path;
  xmlDocPtr doc;
  xmlNodePtr cur;
  xmlChar     *version; 

  path = biji_item_get_uuid (BIJI_ITEM (n));
  doc = xmlParseFile (path);

  if (doc == NULL ) 
  {
    g_warning ("File not parsed successfully");
    return FALSE;
  }

  cur = xmlDocGetRootElement (doc);

  if (cur == NULL) 
  {
    g_warning ("File empty");
    xmlFreeDoc(doc);
    return FALSE;
  }

  if (xmlStrcmp(cur->name, (const xmlChar *) "note")) 
  {
    g_message ("document of the wrong type, root node != note");
    xmlFreeDoc(doc);
    return FALSE;
  }

  /* Switch there for note type
   * Despite not yet handled */

  version = xmlGetNoNsProp (cur, BAD_CAST "version");

  /* Bijiben type */
  if (g_strcmp0 ((gchar*) cur->ns->href, BIJI_NS) ==0) {
    self->priv->type = BIJIBEN_1;
  }

  /* Tomboy type */
  else {
    if (g_strcmp0 ((gchar*) cur->ns->href, TOMBOY_NS) == 0)
    {
      if (g_strcmp0 ((const gchar*) version, "0.1") == 0)
        self->priv->type = TOMBOY_1;

      if (g_strcmp0 ((const gchar*) version, "0.2") == 0)
        self->priv->type = TOMBOY_2;

      if (g_strcmp0 ((const gchar*) version, "0.3") == 0)
        self->priv->type = TOMBOY_3;
    }

  /* Wow this note won't be loaded i guess */
    else {
      self->priv->type = NO_TYPE;
    }
  }

  xmlFree (version);

  path = biji_item_get_uuid (BIJI_ITEM (n));
  self->priv->r = xmlNewTextReaderFilename (path);

  biji_parse_file (self);
  xmlFreeDoc (doc);

  return TRUE ;
}
/* Obligatory basic callback */
static void print_hello( GtkWidget *w,
                         gpointer   data )
{
  g_message ("Hello, World!\n");
}
Exemplo n.º 25
0
static void
_phoneui_utils_sound_init_set_control(GKeyFile *keyfile, const char *_field,
			const char *suffix, enum SoundState state, enum SoundStateType type)
{
	char *field;
	char *speaker = NULL;
	char *microphone = NULL;
	char *speaker_mute = NULL;
	char *microphone_mute = NULL;
	int state_index = calc_state_index(state, type);

	if (controls[state_index][CONTROL_SPEAKER].name) {
		g_warning("Trying to allocate already allocated index %d.", state_index);
		return;
	}
	/*FIXME: split to a generic function for both speaker and microphone */
	field = malloc(strlen(_field) + strlen(suffix) + strlen("alsa_control_") + 1);
	if (field) {
		/* init for now and for the next if */
		strcpy(field, "alsa_control_");
		strcat(field, _field);
		strcat(field, suffix);

		speaker = g_key_file_get_string(keyfile, field, "speaker", NULL);
		microphone = g_key_file_get_string(keyfile, field, "microphone", NULL);
		speaker_mute = g_key_file_get_string(keyfile, field, "speaker_mute", NULL);
		microphone_mute = g_key_file_get_string(keyfile, field, "microphone_mute", NULL);

		/* does not yet free field because of the next if */
	}
	if (!speaker) {
		g_message("No speaker value for %s found, using none", _field);
		speaker = strdup("");
	}
	if (!microphone) {
		g_message("No microphone value for %s found, using none", _field);
		microphone = strdup("");
	}
	controls[state_index][CONTROL_SPEAKER].mute_element = NULL;
	controls[state_index][CONTROL_MICROPHONE].mute_element = NULL;
	if (speaker_mute) {
		_phoneui_utils_sound_init_set_volume_mute_control(state, type, CONTROL_SPEAKER, speaker_mute);
		free(speaker_mute);
	}
	if (microphone_mute) {
		_phoneui_utils_sound_init_set_volume_mute_control(state, type, CONTROL_MICROPHONE, microphone_mute);
		free(microphone_mute);
	}

	controls[state_index][CONTROL_SPEAKER].name = speaker;
	controls[state_index][CONTROL_MICROPHONE].name = microphone;
	_phoneui_utils_sound_init_set_volume_control(state, type, CONTROL_SPEAKER);
	_phoneui_utils_sound_init_set_volume_control(state, type, CONTROL_MICROPHONE);

	/* Load min, max and count from alsa and init to zero before instead
	 * of handling errors, hackish but fast. */
	controls[state_index][CONTROL_SPEAKER].min = controls[state_index][CONTROL_SPEAKER].max = 0;
	controls[state_index][CONTROL_MICROPHONE].min = controls[state_index][CONTROL_MICROPHONE].max = 0;
	controls[state_index][CONTROL_MICROPHONE].count = 0;
	/* The function handles the case where the control has no element */
	_phoneui_utils_sound_volume_load_stats(&controls[state_index][CONTROL_SPEAKER]);
	_phoneui_utils_sound_volume_load_stats(&controls[state_index][CONTROL_MICROPHONE]);

	if (field) {
		int tmp;

		/* If the user specifies his own min and max for that control,
		 * check values for sanity and then apply them. */
		if (g_key_file_has_key(keyfile, field, "microphone_min", NULL)) {
			tmp = g_key_file_get_integer(keyfile, field, "microphone_min", NULL);
			if (tmp > controls[state_index][CONTROL_MICROPHONE].min &&
				tmp < controls[state_index][CONTROL_MICROPHONE].max) {

				controls[state_index][CONTROL_MICROPHONE].min = tmp;
			}
		}
		if (g_key_file_has_key(keyfile, field, "microphone_max", NULL)) {
			tmp = g_key_file_get_integer(keyfile, field, "microphone_max", NULL);
			if (tmp > controls[state][CONTROL_MICROPHONE].min &&
				tmp < controls[state_index][CONTROL_MICROPHONE].max) {

				controls[state_index][CONTROL_MICROPHONE].max = tmp;
			}
		}
		if (g_key_file_has_key(keyfile, field, "speaker_min", NULL)) {
			tmp = g_key_file_get_integer(keyfile, field, "speaker_min", NULL);
			if (tmp > controls[state_index][CONTROL_SPEAKER].min &&
				tmp < controls[state_index][CONTROL_SPEAKER].max) {

				controls[state_index][CONTROL_SPEAKER].min = tmp;
				g_debug("settisg speaker_min to %d", (int) tmp);
			}
		}
		if (g_key_file_has_key(keyfile, field, "speaker_max", NULL)) {
			tmp = g_key_file_get_integer(keyfile, field, "speaker_max", NULL);
			if (tmp > controls[state_index][CONTROL_SPEAKER].min &&
				tmp < controls[state_index][CONTROL_SPEAKER].max) {

				controls[state_index][CONTROL_SPEAKER].max = tmp;
			}
		}
		free(field);
	}

}
Exemplo n.º 26
0
int
main (int argc, char **argv)
{
    GError *err = NULL;
    GOptionContext *g_option_context;
    double x_zoom = 1.0;
    double y_zoom = 1.0;
    double dpi_x = -1.0;
    double dpi_y = -1.0;
    int width = -1;
    int height = -1;
    int bVersion = 0;
    char *bg_color = NULL;
    char *base_uri = NULL;
    int bKeepAspect = 0;
    char *id = NULL;

    int xid = -1;
    int from_stdin = 0;
    ViewerCbInfo info;

    struct RsvgSizeCallbackData size_data;

    char **args = NULL;
    gint n_args = 0;

    GOptionEntry options_table[] = {
#ifdef ENABLE_XEMBED
        {"xid", 'i', 0, G_OPTION_ARG_INT, &xid, N_("XWindow ID [for X11 embedding]"), N_("<int>")},
#endif
        {"stdin", 's', 0, G_OPTION_ARG_NONE, &from_stdin, N_("Read from stdin instead of a file"),
         NULL},
        {"dpi-x", 'd', 0, G_OPTION_ARG_DOUBLE, &dpi_x, N_("Set the # of Pixels Per Inch"),
         N_("<float>")},
        {"dpi-y", 'p', 0, G_OPTION_ARG_DOUBLE, &dpi_y, N_("Set the # of Pixels Per Inch"),
         N_("<float>")},
        {"x-zoom", 'x', 0, G_OPTION_ARG_DOUBLE, &x_zoom, N_("Set the x zoom factor"),
         N_("<float>")},
        {"y-zoom", 'y', 0, G_OPTION_ARG_DOUBLE, &y_zoom, N_("Set the y zoom factor"),
         N_("<float>")},
        {"width", 'w', 0, G_OPTION_ARG_INT, &width, N_("Set the image's width"), N_("<int>")},
        {"height", 'h', 0, G_OPTION_ARG_INT, &height, N_("Set the image's height"), N_("<int>")},
        {"bg-color", 'b', 0, G_OPTION_ARG_STRING, &bg_color,
         N_("Set the image background color (default: transparent)"), N_("<string>")},
        {"base-uri", 'u', 0, G_OPTION_ARG_STRING, &base_uri, N_("Set the base URI (default: none)"),
         N_("<string>")},
        {"id", 0, 0, G_OPTION_ARG_STRING, &id, N_("Only show one node (default: all)"),
         N_("<string>")},
        {"keep-aspect", 'k', 0, G_OPTION_ARG_NONE, &bKeepAspect,
         N_("Preserve the image's aspect ratio"), NULL},
        {"version", 'v', 0, G_OPTION_ARG_NONE, &bVersion, N_("Show version information"), NULL},
        {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &args, NULL, N_("[FILE...]")},
        {NULL}
    };

    g_thread_init (NULL);

    info.pixbuf = NULL;
    info.svg_bytes = NULL;
    info.window = NULL;
    info.popup_menu = NULL;

    g_option_context = g_option_context_new ("- SVG Viewer");
    g_option_context_add_main_entries (g_option_context, options_table, NULL);
    g_option_context_add_group (g_option_context, gtk_get_option_group (TRUE));
    g_option_context_set_help_enabled (g_option_context, TRUE);
    if (!g_option_context_parse (g_option_context, &argc, &argv, NULL)) {
        exit (1);
    }

    g_option_context_free (g_option_context);

    if (bVersion != 0) {
        g_message (_("rsvg-view version %s\n"), VERSION);
        return 0;
    }

    if (args) {
        while (args[n_args] != NULL)
            n_args++;
    }

    if ((!from_stdin) && (n_args != 1)) {
        g_print (_("No files specified, and not using --stdin\n"));
        return 1;
    }

    /* initialize gtk+ and rsvg */
    rsvg_init ();

    rsvg_set_default_dpi_x_y (dpi_x, dpi_y);

    /* if both are unspecified, assume user wants to zoom the pixbuf in at least 1 dimension */
    if (width == -1 && height == -1) {
        size_data.type = RSVG_SIZE_ZOOM;
        size_data.x_zoom = x_zoom;
        size_data.y_zoom = y_zoom;
    }
    /* if both are unspecified, assume user wants to resize pixbuf in at least 1 dimension */
    else if (x_zoom == 1.0 && y_zoom == 1.0) {
        size_data.type = RSVG_SIZE_WH;
        size_data.width = width;
        size_data.height = height;
    }
    /* assume the user wants to zoom the pixbuf, but cap the maximum size */
    else {
        size_data.type = RSVG_SIZE_ZOOM_MAX;
        size_data.x_zoom = x_zoom;
        size_data.y_zoom = y_zoom;
        size_data.width = width;
        size_data.height = height;
    }

    size_data.keep_aspect_ratio = bKeepAspect;

    if (!from_stdin) {
        if (base_uri == NULL)
            base_uri = (char *) args[0];

        info.svg_bytes = _rsvg_acquire_xlink_href_resource (args[0], base_uri, NULL);
    } else {
        info.svg_bytes = g_byte_array_new ();

        for (;;) {
            unsigned char buf[1024 * 8];
            size_t nread = fread (buf, 1, sizeof (buf), stdin);

            if (nread > 0)
                g_byte_array_append (info.svg_bytes, buf, nread);

            if (nread < sizeof (buf)) {
                if (ferror (stdin)) {
                    g_print (_("Error reading\n"));
                    g_byte_array_free (info.svg_bytes, TRUE);
                    fclose (stdin);

                    return 1;
                } else if (feof (stdin))
                    break;
            }
        }

        fclose (stdin);
    }

    if (!info.svg_bytes || !info.svg_bytes->len) {
        g_print (_("Couldn't open %s\n"), args[0]);
        return 1;
    }

    info.base_uri = base_uri;
    info.id = id;

    info.pixbuf = 
        pixbuf_from_data_with_size_data (info.svg_bytes->data, info.svg_bytes->len, &size_data,
                                         base_uri, id, &err);

    if (!info.pixbuf) {
        g_print (_("Error displaying image"));

        if (err) {
            g_print (": %s", err->message);
            g_error_free (err);
        }

        g_print ("\n");

        return 1;
    }

    info.accel_group = gtk_accel_group_new ();

    view_pixbuf (&info, xid, bg_color);

    /* run the gtk+ main loop */
    gtk_main ();

    g_object_unref (G_OBJECT (info.pixbuf));
    g_byte_array_free (info.svg_bytes, TRUE);
    rsvg_term ();

    return 0;
}
Exemplo n.º 27
0
// Main
int main(int argc, char* argv[])
{
    // Setup cmd
    const gchar* cmd_drv_rx = "pcap";
    const gchar* cmd_mode_rx = "file";
    const gchar* cmd_dev_rx = "test-rx.pcap";
    const gchar* cmd_drv_tx = "none";
    const gchar* cmd_mode_tx = "file";
    const gchar* cmd_dev_tx = "test-tx.pcap";
    GOptionEntry cmd_entry_main[] = {
        { "rx-drv", '\0', 0, G_OPTION_ARG_STRING, &cmd_drv_rx, "RX driver" },
        { "rx-mode", '\0', 0, G_OPTION_ARG_STRING, &cmd_mode_rx, "RX mode (dev / file)" },
        { "rx-dev", '\0', 0, G_OPTION_ARG_STRING, &cmd_dev_rx, "RX device (wlan0 / eth0 / file.pcap)" },
        { "tx-drv", '\0', 0, G_OPTION_ARG_STRING, &cmd_drv_tx, "TX driver" },
        { "tx-mode", '\0', 0, G_OPTION_ARG_STRING, &cmd_mode_tx, "TX mode (dev / file)" },
        { "tx-dev", '\0', 0, G_OPTION_ARG_STRING, &cmd_dev_tx, "TX device (wlan0 / eth0 / file.pcap)" },
        { NULL }
    };
    gboolean cmd_list_pcap = false;
    gboolean cmd_list_lorcon = false;
    gboolean cmd_list_netlink = false;
    GOptionEntry cmd_entry_driver[] = {
        #ifdef PCAP_FOUND
            { "list-pcap", '\0', 0, G_OPTION_ARG_NONE, &cmd_list_pcap, "PCAP device list" },
        #endif
        #ifdef LORCON_FOUND
            { "list-lorcon", '\0', 0, G_OPTION_ARG_NONE, &cmd_list_lorcon, "LORCON device list" },
        #endif
        #ifdef NETLINK_FOUND
            { "list-netlink", '\0', 0, G_OPTION_ARG_NONE, &cmd_list_netlink, "NETLINK device list" },
        #endif
        { NULL }
    };
    
    // Parse cmd
    GError* cmd_error = NULL;
    GOptionContext* cmd_ctx = g_option_context_new("- packet injection tool");
    g_option_context_add_main_entries(cmd_ctx, cmd_entry_main, NULL);
    GOptionGroup* cmd_lgrp = g_option_group_new("list", "Driver devices", "Driver devices", NULL, NULL);
    g_option_group_add_entries(cmd_lgrp, cmd_entry_driver);
    g_option_context_add_group(cmd_ctx, cmd_lgrp);
    g_option_context_set_description(cmd_ctx,
        "Supported drivers:\n"
        #ifdef PCAP_FOUND
            "  * pcap\n"
        #endif
        #ifdef LORCON_FOUND
            "  * lorcon\n"
        #endif
        #ifdef NETLINK_FOUND
            "  * netlink\n"
        #endif
    );
    if (!g_option_context_parse(cmd_ctx, &argc, &argv, &cmd_error)) {
        g_message("Option parsing failed: %s", cmd_error->message);
        exit(1);
    }

    // Signal setup
    if (signal(SIGINT, ao_signal) == SIG_ERR) {
        g_critical("[sys] failed to set SIGINT signal handler!");
    } else if (signal(SIGWINCH, ao_signal) == SIG_ERR) {
        g_critical("[sys] failed to set SIGWINCH signal handler!");
    }
    
    // Threads
    g_thread_init(NULL);
    
    // Lists
    if (cmd_list_pcap || cmd_list_lorcon || cmd_list_netlink) {
        // Console
        c_ui_console* ui = new c_ui_console();
        ui->init();
        
        // Show
        if (cmd_list_pcap) {
            #ifdef PCAP_FOUND
                c_drv_pcap::help();
            #else
                g_critical("Pcap driver not compiled in this binary!");
            #endif
        }
        if (cmd_list_lorcon) {
            #ifdef LORCON_FOUND
                c_drv_lorcon::help();
            #else
                g_critical("Lorcon driver not compiled in this binary!");
            #endif
        }
        if (cmd_list_netlink) {
            #ifdef NETLINK_FOUND
                c_drv_netlink::help();
            #else
                g_critical("Netlink driver not compiled in this binary!");
            #endif
        }
        
        // Quit
        exit(0);
    }
    
    // Context
    ao_inst = new c_context();
    if (ao_inst->init(cmd_drv_rx, cmd_mode_rx, cmd_dev_rx, cmd_drv_tx, cmd_mode_tx, cmd_dev_tx)) {
        ao_inst->run();
    }
    delete ao_inst;

	// Return
	return 0;
}
Exemplo n.º 28
0
static void
gegl_tile_backend_swap_entry_read (GeglTileBackendSwap *self,
                                   SwapEntry           *entry,
                                   guchar              *dest)
{
  gint    tile_size  = gegl_tile_backend_get_tile_size (GEGL_TILE_BACKEND (self));
  gint    to_be_read = tile_size;
  guint64 offset     = entry->offset;

  gegl_tile_backend_swap_ensure_exist ();

  if (entry->link || in_progress)
    {
      ThreadParams *queued_op = NULL;
      g_mutex_lock (&mutex);

      if (entry->link)
        queued_op = entry->link->data;
      else if (in_progress && in_progress->entry == entry)
        queued_op = in_progress;

      if (queued_op)
        {
          memcpy (dest, queued_op->source, to_be_read);
          g_mutex_unlock (&mutex);

          GEGL_NOTE(GEGL_DEBUG_TILE_BACKEND, "read entry %i, %i, %i from queue", entry->x, entry->y, entry->z);

          return;
        }

      g_mutex_unlock (&mutex);
    }

  if (in_offset != offset)
    {
      if (lseek (in_fd, offset, SEEK_SET) < 0)
        {
          g_warning ("unable to seek to tile in buffer: %s", g_strerror (errno));
          return;
        }
      in_offset = offset;
    }

  while (to_be_read > 0)
    {
      GError *error = NULL;
      gint    byte_read;

      byte_read = read (in_fd, dest + tile_size - to_be_read, to_be_read);
      if (byte_read <= 0)
        {
          g_message ("unable to read tile data from swap: "
                     "%s (%d/%d bytes read) %s",
                     g_strerror (errno), byte_read, to_be_read, error?error->message:"--");
          return;
        }
      to_be_read -= byte_read;
      in_offset  += byte_read;
    }

  GEGL_NOTE(GEGL_DEBUG_TILE_BACKEND, "read entry %i, %i, %i from %i", entry->x, entry->y, entry->z, (gint)offset);
}
Exemplo n.º 29
0
int main (int argc, char **argv)
{
	CamelSession *session;
	CamelCipherContext *ctx;
	CamelException *ex;
	CamelCipherValidity *valid;
	CamelStream *stream1, *stream2;
	struct _CamelMimePart *sigpart, *conpart, *encpart, *outpart;
	CamelDataWrapper *dw;
	GPtrArray *recipients;
	GByteArray *buf;
	char *before, *after;
	int ret;

	if (getenv("CAMEL_TEST_GPG") == NULL)
		return 77;

	camel_test_init (argc, argv);

	/* clear out any camel-test data */
	system ("/bin/rm -rf /tmp/camel-test");
	system ("/bin/mkdir /tmp/camel-test");
	setenv ("GNUPGHOME", "/tmp/camel-test/.gnupg", 1);

	/* import the gpg keys */
	if ((ret = system ("gpg < /dev/null > /dev/null 2>&1")) == -1)
		return 77;
	else if (WEXITSTATUS (ret) == 127)
		return 77;

	g_message ("gpg --import " TEST_DATA_DIR "/camel-test.gpg.pub > /dev/null 2>&1");
	system ("gpg --import " TEST_DATA_DIR "/camel-test.gpg.pub > /dev/null 2>&1");
	g_message ("gpg --import " TEST_DATA_DIR "/camel-test.gpg.sec > /dev/null 2>&1");
	system ("gpg --import " TEST_DATA_DIR "/camel-test.gpg.sec > /dev/null 2>&1");

	session = camel_pgp_session_new ("/tmp/camel-test");

	ex = camel_exception_new ();

	ctx = camel_gpg_context_new (session);
	camel_gpg_context_set_always_trust (CAMEL_GPG_CONTEXT (ctx), TRUE);

	camel_test_start ("Test of PGP functions");

	stream1 = camel_stream_mem_new ();
	camel_stream_write (stream1, "Hello, I am a test stream.\n", 27);
	camel_stream_reset (stream1);

	conpart = camel_mime_part_new();
	dw = camel_data_wrapper_new();
	camel_data_wrapper_construct_from_stream(dw, stream1);
	camel_medium_set_content_object((CamelMedium *)conpart, dw);
	camel_object_unref(stream1);
	camel_object_unref(dw);

	sigpart = camel_mime_part_new();

	camel_test_push ("PGP signing");
	camel_cipher_sign (ctx, "*****@*****.**", CAMEL_CIPHER_HASH_SHA1, conpart, sigpart, ex);
	if (camel_exception_is_set(ex)) {
		printf("PGP signing failed assuming non-functional environment\n%s", camel_exception_get_description (ex));
		camel_test_pull();
		return 77;
	}
	camel_test_pull ();

	camel_exception_clear (ex);

	camel_test_push ("PGP verify");
	valid = camel_cipher_verify (ctx, sigpart, ex);
	check_msg (!camel_exception_is_set (ex), "%s", camel_exception_get_description (ex));
	check_msg (camel_cipher_validity_get_valid (valid), "%s", camel_cipher_validity_get_description (valid));
	camel_cipher_validity_free (valid);
	camel_test_pull ();

	camel_object_unref(conpart);
	camel_object_unref(sigpart);

	stream1 = camel_stream_mem_new ();
	camel_stream_write (stream1, "Hello, I am a test of encryption/decryption.", 44);
	camel_stream_reset (stream1);

	conpart = camel_mime_part_new();
	dw = camel_data_wrapper_new();
	camel_stream_reset(stream1);
	camel_data_wrapper_construct_from_stream(dw, stream1);
	camel_medium_set_content_object((CamelMedium *)conpart, dw);
	camel_object_unref(stream1);
	camel_object_unref(dw);

	encpart = camel_mime_part_new();

	camel_exception_clear (ex);

	camel_test_push ("PGP encrypt");
	recipients = g_ptr_array_new ();
	g_ptr_array_add (recipients, "*****@*****.**");
	camel_cipher_encrypt (ctx, "*****@*****.**", recipients, conpart, encpart, ex);
	check_msg (!camel_exception_is_set (ex), "%s", camel_exception_get_description (ex));
	g_ptr_array_free (recipients, TRUE);
	camel_test_pull ();

	camel_exception_clear (ex);

	camel_test_push ("PGP decrypt");
	outpart = camel_mime_part_new();
	valid = camel_cipher_decrypt (ctx, encpart, outpart, ex);
	check_msg (!camel_exception_is_set (ex), "%s", camel_exception_get_description (ex));
	check_msg (valid->encrypt.status == CAMEL_CIPHER_VALIDITY_ENCRYPT_ENCRYPTED, "%s", valid->encrypt.description);

	stream1 = camel_stream_mem_new();
	stream2 = camel_stream_mem_new();

	camel_data_wrapper_write_to_stream((CamelDataWrapper *)conpart, stream1);
	camel_data_wrapper_write_to_stream((CamelDataWrapper *)outpart, stream2);

	buf = CAMEL_STREAM_MEM (stream1)->buffer;
	before = g_strndup (buf->data, buf->len);
	buf = CAMEL_STREAM_MEM (stream2)->buffer;
	after = g_strndup (buf->data, buf->len);
	check_msg (string_equal (before, after), "before = '%s', after = '%s'", before, after);
	g_free (before);
	g_free (after);

	camel_object_unref(stream1);
	camel_object_unref(stream2);
	camel_object_unref(conpart);
	camel_object_unref(encpart);
	camel_object_unref(outpart);

	camel_test_pull ();

	camel_object_unref (CAMEL_OBJECT (ctx));
	camel_object_unref (CAMEL_OBJECT (session));

	camel_test_end ();

	return 0;
}
Exemplo n.º 30
0
int
main (int argc, char *argv[])
{
	GMainContext *ctx;
	GMainLoop *loop;

	/*
	 * The mate-keyring startup is not as simple as I wish it could be.
	 *
	 * It's often started in the primordial stages of a session, where
	 * there's no DBus, and no proper X display. This is the strange world
	 * of PAM.
	 *
	 * When started with the --login option, we do as little initialization
	 * as possible. We expect a login password on the stdin, and unlock
	 * or create the login keyring.
	 *
	 * Then later we expect mate-keyring-dameon to be run again with the
	 * --start option. This second mate-keyring-daemon will hook the
	 * original daemon up with environment variables necessary to initialize
	 * itself and bring it into the session. This second daemon usually exits.
	 *
	 * Without either of these options, we follow a more boring and
	 * predictable startup.
	 */

	/*
	 * Before we do ANYTHING, we drop privileges so we don't become
	 * a security issue ourselves.
	 */
	gkd_capability_obtain_capability_and_drop_privileges ();

#ifdef WITH_TESTS
	g_setenv ("DBUS_FATAL_WARNINGS", "1", FALSE);
	if (!g_getenv ("G_DEBUG"))
		g_log_set_always_fatal (G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING);
#endif

	g_type_init ();
	g_thread_init (NULL);

#ifdef HAVE_LOCALE_H
	/* internationalisation */
	setlocale (LC_ALL, "");
#endif

#ifdef HAVE_GETTEXT
	bindtextdomain (GETTEXT_PACKAGE, MATELOCALEDIR);
	textdomain (GETTEXT_PACKAGE);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif

	egg_libgcrypt_initialize ();

	/* Send all warning or error messages to syslog */
	prepare_logging ();

	parse_arguments (&argc, &argv);

	/* The --version option. This is machine parseable output */
	if (run_version) {
		g_print ("mate-keyring-daemon: %s\n", VERSION);
		g_print ("testing: %s\n",
#ifdef WITH_TESTS
		         "enabled");
#else
		         "disabled");
#endif
		exit (0);
	}

	/* The --start option */
	if (run_for_start) {
		if (discover_other_daemon (initialize_daemon_at, TRUE)) {
			/*
			 * Another daemon was initialized, print out environment
			 * for any callers, and quit or go comatose.
			 */
			print_environment (0);
			if (run_foreground)
				while (sleep(0x08000000) == 0);
			cleanup_and_exit (0);
		}

	/* The --replace option */
	} else if (run_for_replace) {
		discover_other_daemon (replace_daemon_at, FALSE);
		if (control_directory)
			g_message ("replacing daemon at: %s", control_directory);
	}

	/* Initialize the main directory */
	gkd_util_init_master_directory (control_directory);

	/* Initialize our daemon main loop and threading */
	loop = g_main_loop_new (NULL, FALSE);
	ctx = g_main_loop_get_context (loop);

	/* Initialize our control socket */
	if (!gkd_control_listen ())
		return FALSE;

	/* The --login option. Delayed initialization */
	if (run_for_login) {
		login_password = read_login_password (STDIN);
		atexit (clear_login_password);
		timeout_id = g_timeout_add_seconds (LOGIN_TIMEOUT, (GSourceFunc) on_login_timeout, NULL);

	/* Not a login daemon. Startup stuff now.*/
	} else {
		/* These are things that can run before forking */
		if (!gkr_daemon_startup_steps (run_components))
			cleanup_and_exit (1);
	}

	/* The whole forking and daemonizing dance starts here. */
	fork_and_print_environment();

	setup_signal_handling (loop);

	/* Prepare logging a second time, since we may be in a different process */
	prepare_logging();

	/* Remainder initialization after forking, if initialization not delayed */
	if (!run_for_login) {
		gkr_daemon_initialize_steps (run_components);
	}

	g_main_loop_run (loop);

	/* This wraps everything up in order */
	egg_cleanup_perform ();

	/* Wrap up signal handling here */
	cleanup_signal_handling ();

	g_free (control_directory);

	return 0;
}