Ejemplo n.º 1
0
int
main (int argc, char **argv)
{
  GtkWidget *w1;
  gchar *path;

  gtk_init (&argc, &argv);

  toplevel = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  grid = gtk_grid_new ();

  w1 = gtk_label_new ("File:");
  gtk_widget_set_halign (w1, GTK_ALIGN_START);
  gtk_grid_attach (GTK_GRID (grid),
                   w1, 0, 0, 1, 1);

  file_l = gtk_button_new ();
  path = g_build_filename (g_get_current_dir (), "apple-red.png", NULL);
  file = g_file_new_for_path (path);
  gtk_button_set_label (GTK_BUTTON (file_l), path);
  g_free (path);

  gtk_widget_set_halign (file_l, GTK_ALIGN_START);
  gtk_grid_attach_next_to (GTK_GRID (grid), file_l,
                           w1, GTK_POS_RIGHT, 3, 1);
  g_signal_connect (file_l, "clicked",
                    G_CALLBACK (button_clicked), NULL);

  radio_file = gtk_radio_button_new_with_label (NULL, "Use GFile");
  radio_content = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (radio_file),
                                                               "Use content type");

  gtk_grid_attach (GTK_GRID (grid), radio_file,
                   0, 1, 1, 1);
  gtk_grid_attach_next_to (GTK_GRID (grid), radio_content,
                           radio_file, GTK_POS_BOTTOM, 1, 1);

  open = gtk_button_new_with_label ("Trigger App Chooser dialog");
  gtk_grid_attach_next_to (GTK_GRID (grid), open,
                           radio_content, GTK_POS_BOTTOM, 1, 1);

  recommended = gtk_check_button_new_with_label ("Show recommended");
  gtk_grid_attach_next_to (GTK_GRID (grid), recommended,
                           open, GTK_POS_BOTTOM, 1, 1);
  g_object_set (recommended, "active", TRUE, NULL);

  fallback = gtk_check_button_new_with_label ("Show fallback");
  gtk_grid_attach_next_to (GTK_GRID (grid), fallback,
                           recommended, GTK_POS_RIGHT, 1, 1);

  other = gtk_check_button_new_with_label ("Show other");
  gtk_grid_attach_next_to (GTK_GRID (grid), other,
                           fallback, GTK_POS_RIGHT, 1, 1);

  all = gtk_check_button_new_with_label ("Show all");
  gtk_grid_attach_next_to (GTK_GRID (grid), all,
                           other, GTK_POS_RIGHT, 1, 1);

  def = gtk_check_button_new_with_label ("Show default");
  gtk_grid_attach_next_to (GTK_GRID (grid), def,
                           all, GTK_POS_RIGHT, 1, 1);

  g_object_set (recommended, "active", TRUE, NULL);
  prepare_dialog ();
  g_signal_connect (open, "clicked",
                    G_CALLBACK (display_dialog), NULL);

  gtk_container_add (GTK_CONTAINER (toplevel), grid);

  gtk_widget_show_all (toplevel);
  g_signal_connect (toplevel, "delete-event",
                    G_CALLBACK (gtk_main_quit), NULL);

  gtk_main ();

  return EXIT_SUCCESS;
}
Ejemplo n.º 2
0
gchar *
lgm_filename_to_uri (const gchar *filename)
{
  gchar *uri, *path;
  GError *err = NULL;

#ifdef G_OS_WIN32
  if (g_path_is_absolute(filename) || !gst_uri_is_valid (filename)) {
#else
  if (!gst_uri_is_valid (filename)) {
#endif
    if (!g_path_is_absolute (filename)) {
      gchar *cur_dir;

      cur_dir = g_get_current_dir ();
      path = g_build_filename (cur_dir, filename, NULL);
      g_free (cur_dir);
    } else {
      path = g_strdup (filename);
    }

    uri = g_filename_to_uri (path, NULL, &err);
    g_free (path);
    path = NULL;

    if (err != NULL) {
      g_error_free (err);
      return NULL;
    }
  } else {
    uri = g_strdup (filename);
  }
  return uri;
}

GstDiscovererResult
lgm_discover_uri (
    const gchar *filename, guint64 *duration, guint *width,
    guint *height, guint *fps_n, guint *fps_d, guint *par_n, guint *par_d,
    gchar **container, gchar **video_codec, gchar **audio_codec,
    GError **err)
{
  GstDiscoverer *discoverer;
  GstDiscovererInfo *info;
  GList *videos = NULL, *audios = NULL;
  GstDiscovererStreamInfo *sinfo = NULL;
  GstDiscovererVideoInfo *vinfo = NULL;
  GstDiscovererAudioInfo *ainfo = NULL;
  GstDiscovererResult ret;
  gchar *uri;

  uri = lgm_filename_to_uri (filename);
  if (uri == NULL) {
    return GST_DISCOVERER_URI_INVALID;
  }

  *duration = *width = *height = *fps_n = *fps_d = *par_n = *par_d = 0;
  *container = *audio_codec = *video_codec = NULL;

  discoverer = gst_discoverer_new (4 * GST_SECOND, err);
  if (*err != NULL) {
    g_free (uri);
    return GST_DISCOVERER_ERROR;
  }

  info = gst_discoverer_discover_uri (discoverer, uri, err);
  g_free (uri);
  if (*err != NULL) {
    if (info != NULL) {
      return gst_discoverer_info_get_result (info);
    } else {
      return GST_DISCOVERER_ERROR;
    }
  }

  sinfo = gst_discoverer_info_get_stream_info (info);
  *duration = gst_discoverer_info_get_duration (info);

  if (GST_IS_DISCOVERER_CONTAINER_INFO (sinfo)) {
    GstCaps *caps;

    caps = gst_discoverer_stream_info_get_caps (
        GST_DISCOVERER_STREAM_INFO(sinfo));
    *container = gst_pb_utils_get_codec_description (caps);
    gst_caps_unref (caps);
  }

  if (GST_IS_DISCOVERER_AUDIO_INFO (sinfo)) {
    ainfo = GST_DISCOVERER_AUDIO_INFO (sinfo);
  } else {
    audios = gst_discoverer_info_get_audio_streams (info);
    if (audios != NULL) {
      ainfo = audios->data;
    }
  }

  if (ainfo != NULL) {
    GstCaps *caps;

    caps = gst_discoverer_stream_info_get_caps (
        GST_DISCOVERER_STREAM_INFO (ainfo));
    *audio_codec = gst_pb_utils_get_codec_description (caps);
    gst_caps_unref (caps);
  }
  if (audios != NULL) {
    gst_discoverer_stream_info_list_free (audios);
  }

  if (GST_IS_DISCOVERER_VIDEO_INFO (sinfo)) {
    vinfo = GST_DISCOVERER_VIDEO_INFO (sinfo);
  } else {
    videos = gst_discoverer_info_get_video_streams (info);
    if (videos != NULL) {
      vinfo = videos->data;
    }
  }

  if (vinfo != NULL) {
    GstCaps *caps;

    caps = gst_discoverer_stream_info_get_caps (
        GST_DISCOVERER_STREAM_INFO (vinfo));
    *video_codec = gst_pb_utils_get_codec_description (caps);
    gst_caps_unref (caps);
    *height = gst_discoverer_video_info_get_height (vinfo);
    *width = gst_discoverer_video_info_get_width (vinfo);
    *fps_n = gst_discoverer_video_info_get_framerate_num (vinfo);
    *fps_d = gst_discoverer_video_info_get_framerate_denom (vinfo);
    *par_n = gst_discoverer_video_info_get_par_num (vinfo);
    *par_d = gst_discoverer_video_info_get_par_denom (vinfo);
  }
  if (videos != NULL) {
    gst_discoverer_stream_info_list_free (videos);
  }

  ret = gst_discoverer_info_get_result (info);
  gst_discoverer_info_unref (info);
  g_object_unref (discoverer);

  return ret;
}
Ejemplo n.º 3
0
static GslWaveFileInfo*
gslwave_load_file_info (gpointer      data,
			const gchar  *_file_name,
			GslErrorType *error_p)
{
  FileInfo *fi = NULL;
  gboolean in_wave = FALSE, abort = FALSE;
  GslRing *wave_names = NULL;
  GScanner *scanner;
  gchar *cwd, *file_name;
  gint fd;
  guint i;

  if (g_path_is_absolute (_file_name))
    {
      gchar *p = strrchr (_file_name, G_DIR_SEPARATOR);

      g_assert (p != NULL);
      cwd = g_strndup (_file_name, p - _file_name + 1);
      file_name = g_strdup (_file_name);
    }
  else
    {
      cwd = g_get_current_dir ();
      file_name = g_strdup_printf ("%s%c%s", cwd, G_DIR_SEPARATOR, _file_name);
    }

  fd = open (file_name, O_RDONLY);
  if (fd < 0)
    {
      *error_p = GSL_ERROR_OPEN_FAILED;
      g_free (cwd);
      g_free (file_name);
      return NULL;
    }

  scanner = g_scanner_new (NULL);
  scanner->config->symbol_2_token = TRUE;
  g_scanner_scope_add_symbol (scanner, 0, "wave", GUINT_TO_POINTER (GSL_WAVE_TOKEN_WAVE));
  g_scanner_scope_add_symbol (scanner, 0, "name", GUINT_TO_POINTER (GSL_WAVE_TOKEN_NAME));
  g_scanner_input_file (scanner, fd);
  while (!abort)
    {
      g_scanner_get_next_token (scanner);
      switch (scanner->token)
	{
	case GSL_WAVE_TOKEN_WAVE:
	  if (g_scanner_peek_next_token (scanner) == '{')
	    {
	      g_scanner_get_next_token (scanner); /* eat '{' */
	      in_wave = TRUE;
	    }
	  break;
	case '{':
	  if (gslwave_skip_rest_statement (scanner, 1) != G_TOKEN_NONE)
	    abort = TRUE;
	  break;
	case GSL_WAVE_TOKEN_NAME:
	  if (in_wave && g_scanner_peek_next_token (scanner) == '=')
	    {
	      g_scanner_get_next_token (scanner); /* eat '=' */
	      if (g_scanner_peek_next_token (scanner) == G_TOKEN_STRING)
		{
		  gchar *wave_name;
		  
		  g_scanner_get_next_token (scanner); /* eat string */
		  wave_name = g_strdup (scanner->value.v_string);
		  if (gslwave_skip_rest_statement (scanner, 1) == G_TOKEN_NONE)
		    {
		      in_wave = FALSE;
		      wave_names = gsl_ring_append (wave_names, wave_name);
		    }
		  else
		    {
		      g_free (wave_name);
		      abort = TRUE;
		    }
		}
	    }
	  break;
	default:
	  if (scanner->token == G_TOKEN_EOF || scanner->token == G_TOKEN_ERROR)
	    abort = TRUE;
	  break;
	}
    }
  g_scanner_destroy (scanner);
  close (fd);

  if (wave_names)
    {
      GslRing *ring;

      fi = gsl_new_struct0 (FileInfo, 1);
      fi->wfi.n_waves = gsl_ring_length (wave_names);
      fi->wfi.waves = g_malloc0 (sizeof (fi->wfi.waves[0]) * fi->wfi.n_waves);
      for (i = 0, ring = wave_names; i < fi->wfi.n_waves; i++, ring = ring->next)
	fi->wfi.waves[i].name = ring->data;
      gsl_ring_free (wave_names);
      fi->cwd = cwd;
    }
  else
    g_free (cwd);
  g_free (file_name);

  /* FIXME: empty wave error? */

  return fi ? &fi->wfi : NULL;
}
Ejemplo n.º 4
0
void
app_run (const gchar         *full_prog_name,
         const gchar        **filenames,
         GFile               *alternate_system_gimprc,
         GFile               *alternate_gimprc,
         const gchar         *session_name,
         const gchar         *batch_interpreter,
         const gchar        **batch_commands,
         gboolean             as_new,
         gboolean             no_interface,
         gboolean             no_data,
         gboolean             no_fonts,
         gboolean             no_splash,
         gboolean             be_verbose,
         gboolean             use_shm,
         gboolean             use_cpu_accel,
         gboolean             console_messages,
         gboolean             use_debug_handler,
         gboolean             show_playground,
         GimpStackTraceMode   stack_trace_mode,
         GimpPDBCompatMode    pdb_compat_mode)
{
  GimpInitStatusFunc  update_status_func = NULL;
  Gimp               *gimp;
  GMainLoop          *loop;
  GMainLoop          *run_loop;
  GFile              *default_folder = NULL;
  GFile              *gimpdir;

  if (filenames && filenames[0] && ! filenames[1] &&
      g_file_test (filenames[0], G_FILE_TEST_IS_DIR))
    {
      if (g_path_is_absolute (filenames[0]))
        {
          default_folder = g_file_new_for_path (filenames[0]);
        }
      else
        {
          gchar *absolute = g_build_path (G_DIR_SEPARATOR_S,
                                          g_get_current_dir (),
                                          filenames[0],
                                          NULL);
          default_folder = g_file_new_for_path (absolute);
          g_free (absolute);
        }

      filenames = NULL;
    }

  /*  Create an instance of the "Gimp" object which is the root of the
   *  core object system
   */
  gimp = gimp_new (full_prog_name,
                   session_name,
                   default_folder,
                   be_verbose,
                   no_data,
                   no_fonts,
                   no_interface,
                   use_shm,
                   use_cpu_accel,
                   console_messages,
                   show_playground,
                   stack_trace_mode,
                   pdb_compat_mode);

  if (default_folder)
    g_object_unref (default_folder);

  gimp_cpu_accel_set_use (use_cpu_accel);

  errors_init (gimp, full_prog_name, use_debug_handler, stack_trace_mode);

  units_init (gimp);

  /*  Check if the user's gimp_directory exists
   */
  gimpdir = gimp_directory_file (NULL);

  if (g_file_query_file_type (gimpdir, G_FILE_QUERY_INFO_NONE, NULL) !=
      G_FILE_TYPE_DIRECTORY)
    {
      GimpUserInstall *install = gimp_user_install_new (be_verbose);

#ifdef GIMP_CONSOLE_COMPILATION
      gimp_user_install_run (install);
#else
      if (! (no_interface ?
	     gimp_user_install_run (install) :
	     user_install_dialog_run (install)))
	exit (EXIT_FAILURE);
#endif

      gimp_user_install_free (install);
    }

  g_object_unref (gimpdir);

  gimp_load_config (gimp, alternate_system_gimprc, alternate_gimprc);

  /*  change the locale if a language if specified  */
  language_init (gimp->config->language);

  /*  initialize lowlevel stuff  */
  gimp_gegl_init (gimp);

  /*  Connect our restore_after callback before gui_init() connects
   *  theirs, so ours runs first and can grab the initial monitor
   *  before the GUI's restore_after callback resets it.
   */
  g_signal_connect_after (gimp, "restore",
                          G_CALLBACK (app_restore_after_callback),
                          NULL);

#ifndef GIMP_CONSOLE_COMPILATION
  if (! no_interface)
    update_status_func = gui_init (gimp, no_splash);
#endif

  if (! update_status_func)
    update_status_func = app_init_update_noop;

  /*  Create all members of the global Gimp instance which need an already
   *  parsed gimprc, e.g. the data factories
   */
  gimp_initialize (gimp, update_status_func);

  /*  Load all data files
   */
  gimp_restore (gimp, update_status_func);

  /*  enable autosave late so we don't autosave when the
   *  monitor resolution is set in gui_init()
   */
  gimp_rc_set_autosave (GIMP_RC (gimp->edit_config), TRUE);

  loop = run_loop = g_main_loop_new (NULL, FALSE);

  g_signal_connect_after (gimp, "exit",
                          G_CALLBACK (app_exit_after_callback),
                          &run_loop);

  /*  Load the images given on the command-line.
   */
  if (filenames)
    {
      gint i;

      for (i = 0; filenames[i] != NULL; i++)
        {
          if (run_loop)
            {
              GFile *file = g_file_new_for_commandline_arg (filenames[i]);

              file_open_from_command_line (gimp, file, as_new,
                                           initial_screen,
                                           initial_monitor);

              g_object_unref (file);
            }
        }
    }

  if (run_loop)
    gimp_batch_run (gimp, batch_interpreter, batch_commands);

  if (run_loop)
    {
      gimp_threads_leave (gimp);
      g_main_loop_run (loop);
      gimp_threads_enter (gimp);
    }

  g_main_loop_unref (loop);

  g_object_unref (gimp);

  gimp_debug_instances ();

  errors_exit ();
  gegl_exit ();
}
Ejemplo n.º 5
0
void import_radarsat2(const char *inBaseName, radiometry_t radiometry,
		      const char *outBaseName, int ampOnly)
{
  FILE *fp;
  radarsat2_meta *radarsat2;
  meta_parameters *meta;
  char **inDataNames=NULL, inDataName[1024], *inMetaName=NULL;
  char *outDataName=NULL, str[512];
  float *amp = NULL, *phase = NULL, *tmp = NULL, re, im;
  int band, sample;

  // Check radiometry
  if (radiometry != r_AMP) {
    asfPrintWarning("Radiometry other than AMPLITUDE is currently not "
		    "supported.\n");
    radiometry = r_AMP;
  }
  
  if (!fileExists(inBaseName))
    inMetaName = appendExt(inBaseName, ".xml");
  else {
    inMetaName = (char *) MALLOC(sizeof(char)*1024);
    strcpy(inMetaName, inBaseName);
  }
  outDataName = appendExt(outBaseName, ".img");

  radarsat2 = read_radarsat2_meta(inMetaName);
  asfPrintStatus("   DataType: %s, ProductType: %s\n",
		 radarsat2->dataType, radarsat2->productType);
  if (strcmp_case(radarsat2->dataType, "COMPLEX") != 0)
    asfPrintError("Currently only complex data supported!\n");
  meta = radarsat2meta(radarsat2);
  meta_write(meta, outDataName);

  // Let's check the GeoTIFF data.
  // Unfortunately, there is no identifier in the GeoTIFF that would identify
  // the data as Radarsat-2 data.
  //
  // The only thing that we can actually do is to look whether the data in the
  // GeoTIFF file fit the general bill. We can the image dimensions. The data
  // needs to have 2 bands (I and Q) and 16 bit. The citation geokey needs to
  // be the really non-descriptive "Uncorrected Satellite Data".

  TIFF *tiff = NULL;
  GTIF *gtif = NULL;
  data_type_t data_type;
  short sample_format, bits_per_sample, planar_config;
  short num_bands;
  int is_scanline_format, is_palette_color_tiff, wrong=FALSE;
  char *error_message = (char *) MALLOC(sizeof(char)*2048);

  inDataNames = extract_band_names(meta->general->basename, 
				   meta->general->band_count);
  fp = FOPEN(outDataName, "wb");

  int band_count = radarsat2->band_count;
  if (ampOnly) {
    strcpy(meta->general->bands, "AMP");
    meta->general->band_count = 1;
    band_count = 1;
  }
  for (band=0; band<band_count; band++) {

    // path from the xml (metadata) file
    char *path = get_dirname(inBaseName);
    if (strlen(path)>0) {
      strcpy(inDataName, path);
      if (inDataName[strlen(inDataName)-1] != '/')
        strcat(inDataName, "/");
    }
    else
      strcpy(inDataName, "");
    free(path);
    strcat(inDataName, inDataNames[band]);

    tiff = XTIFFOpen(inDataName, "r");
    if (!tiff)
      asfPrintError("Could not open data file (%s)\n", inDataName);
    gtif = GTIFNew(tiff);
    if (!gtif)
      asfPrintError("Could not read GeoTIFF keys from data file (%s)\n",
		    inDataName);

    // Check image dimensions
    uint32 tif_sample_count;
    uint32 tif_line_count;

    TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &tif_line_count);
    TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &tif_sample_count);
    if ((meta->general->sample_count != tif_sample_count) ||
	(meta->general->line_count != tif_line_count))
      asfPrintError(error_message, 
		    "Problem with image dimensions. Was looking for %d lines "
		    "and %d samples.\nFound %ld lines and %ld samples instead!"
		    "\n", 
		    meta->general->line_count, meta->general->sample_count, 
		    tif_line_count, tif_sample_count);

    // Check general TIFF tags
    get_tiff_data_config(tiff, &sample_format, &bits_per_sample, &planar_config,
			 &data_type, &num_bands, &is_scanline_format, 
			 &is_palette_color_tiff, REPORT_LEVEL_WARNING);

    // The specs say the data is supposed to be unsigned but it is not.
    // Let is pass as long as we are talking about integer data here
    strcpy(error_message, "");
    if (sample_format != SAMPLEFORMAT_UINT && 
	sample_format != SAMPLEFORMAT_INT) {
      strcat(error_message, 
	     "Problem with sampling format. Was looking for integer, ");
      if (sample_format == SAMPLEFORMAT_COMPLEXIEEEFP)
	strcat(error_message, "found complex floating point instead!\n");
      else if (sample_format == SAMPLEFORMAT_COMPLEXINT)
	strcat(error_message, "found complex integer instead!\n");
      else if (sample_format == SAMPLEFORMAT_IEEEFP)
	strcat(error_message, "found floating point instead!\n");
      else if (sample_format == SAMPLEFORMAT_VOID)
	strcat(error_message, "found void instead!\n");
      wrong = TRUE;
    }
    if (bits_per_sample != 16) {
      sprintf(str, "Problem with bits per sample. Was looking for 16, found %d "
	      "instead!\n", bits_per_sample);
      strcat(error_message, str);
      wrong = TRUE;
    }
    if (data_type != INTEGER16) {
      strcat(error_message, "Problem with data type. Was looking INTEGER16, ");
      if (data_type == ASF_BYTE)
	strcat(error_message, "found BYTE instead!\n");
      else if (data_type == INTEGER32)
	strcat(error_message, "found INTEGER32 instead!\n");
      else if (data_type == REAL32)
	strcat(error_message, "found REAL32 instead!\n");
      else if (data_type == REAL64)
	strcat(error_message, "found REAL64 instead!\n");
      else if (data_type == COMPLEX_BYTE)
	strcat(error_message, "found COMPLEX_BYTE instead!\n");
      else if (data_type == COMPLEX_INTEGER16)
	strcat(error_message, "found COMPLEX_INTEGER16 instead!\n");
      else if (data_type == COMPLEX_INTEGER32)
	strcat(error_message, "found COMPLEX_INTEGER32 instead!\n");
      else if (data_type == COMPLEX_REAL32)
	strcat(error_message, "found COMPLEX_REAL32 instead!\n");
      else if (data_type == COMPLEX_REAL64)
	strcat(error_message, "found COMPLEX_REAL64 instead!\n");
      wrong = TRUE;
    }
    if (num_bands != 2) {
      sprintf(str, "Problem with number of bands. Was looking for 2, "
	      "found %d instead!\n", num_bands);
      strcat(error_message, str);
      wrong = TRUE;
    }
    if (wrong)
      asfPrintError(error_message);

    // Check GTCitationGeoKey
    char *citation = NULL;
    int citation_length, typeSize;
    tagtype_t citation_type;

    citation_length = GTIFKeyInfo(gtif, GTCitationGeoKey, &typeSize,
				  &citation_type);
    if (citation_length > 0) {
      citation = (char *) MALLOC(citation_length * typeSize);
      GTIFKeyGet(gtif, GTCitationGeoKey, citation, 0, citation_length);
      if (citation && 
	  strcmp_case(citation, "UNCORRECTED SATELLITE DATA") != 0) {
	asfPrintError("Problem with GTCitationGeoKey. Was looking for "
		      "'Uncorrected Satellite Data',\nfound '%s' instead!\n", 
		      citation);
      }
    }
    else
      asfPrintError("Problem with GTCitationGeoKey. Was looking for "
		    "'Uncorrected Satellite Data',\ndid not find any key!\n");

    tiff_type_t tiffInfo;
    get_tiff_type(tiff, &tiffInfo);
    if (tiffInfo.format != SCANLINE_TIFF &&
	tiffInfo.format != STRIP_TIFF    &&
	tiffInfo.format != TILED_TIFF)
      asfPrintError("Can't read the GeoTIFF file (%s). Unrecognized TIFF "
		    "type!\n", inDataNames[band]);

    // If we made it here, we are reasonably sure that we have the file that
    // we are looking for.
    asfPrintStatus("\n   Importing %s ...\n", inDataNames[band]);

    uint32 scanlineSize = TIFFScanlineSize(tiff);
    tdata_t *tiff_real_buf = _TIFFmalloc(scanlineSize);
    tdata_t *tiff_imag_buf = _TIFFmalloc(scanlineSize);
    if (!tiff_real_buf || !tiff_imag_buf)
      asfPrintError("Can't allocate buffer for reading TIFF lines!\n");

    amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count);
    phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count);

    // Check whether we need to flip the image in any fashion
    int flip_vertical = FALSE;
    if (strcmp_case(radarsat2->lineTimeOrdering, "DECREASING") == 0) {
      asfPrintStatus("   Data will be flipped vertically while ingesting!\n");
      flip_vertical = TRUE;
    }
    int flip_horizontal = FALSE;
    if (strcmp_case(radarsat2->pixelTimeOrdering, "DECREASING") == 0) {
      asfPrintStatus("   Data will be flipped horizontally while ingesting!\n");
      flip_horizontal = TRUE;
    }
    if (flip_horizontal)
      tmp = (float *) MALLOC(sizeof(float)*meta->general->sample_count);

    // FIXME: still need to implement flipping vertically
    // Read file line by line
    uint32 row;
    int sample_count = meta->general->sample_count;
    int line_count = meta->general->line_count;
    for (row=0; row<(uint32)meta->general->line_count; row++) {
      asfLineMeter(row, meta->general->line_count);
      if (flip_vertical) {
	switch (tiffInfo.format) 
	  {
	  case SCANLINE_TIFF:
	    TIFFReadScanline(tiff, tiff_real_buf, line_count-row-1, 0);
	    TIFFReadScanline(tiff, tiff_imag_buf, line_count-row-1, 1);
	    break;
	  case STRIP_TIFF:
	    ReadScanline_from_TIFF_Strip(tiff, tiff_real_buf, 
					 line_count-row-1, 0);
	    ReadScanline_from_TIFF_Strip(tiff, tiff_imag_buf, 
					 line_count-row-1, 1);
	    break;
	  case TILED_TIFF:
	    ReadScanline_from_TIFF_TileRow(tiff, tiff_real_buf, 
					   line_count-row-1, 0);
	    ReadScanline_from_TIFF_TileRow(tiff, tiff_imag_buf, 
					   line_count-row-1, 1);
	    break;
	  default:
	    asfPrintError("Can't read this TIFF format!\n");
	    break;
	  }
      }
      else {
	switch (tiffInfo.format) 
	  {
	  case SCANLINE_TIFF:
	    TIFFReadScanline(tiff, tiff_real_buf, row, 0);
	    TIFFReadScanline(tiff, tiff_imag_buf, row, 1);
	    break;
	  case STRIP_TIFF:
	    ReadScanline_from_TIFF_Strip(tiff, tiff_real_buf, row, 0);
	    ReadScanline_from_TIFF_Strip(tiff, tiff_imag_buf, row, 1);
	    break;
	  case TILED_TIFF:
	    ReadScanline_from_TIFF_TileRow(tiff, tiff_real_buf, row, 0);
	    ReadScanline_from_TIFF_TileRow(tiff, tiff_imag_buf, row, 1);
	    break;
	  default:
	    asfPrintError("Can't read this TIFF format!\n");
	    break;
	  }
      }
      for (sample=0; sample<sample_count; sample++) {
	switch (sample_format)
	  {
	  case SAMPLEFORMAT_UINT:
	    re = (float)(((uint16*)tiff_real_buf)[sample]);
	    im = (float)(((uint16*)tiff_imag_buf)[sample]);
	    break;
	  case SAMPLEFORMAT_INT:
	    re = (float)(((int16*)tiff_real_buf)[sample]);
	    im = (float)(((int16*)tiff_imag_buf)[sample]);
	    break;
	  }
	amp[sample] = sqrt(re*re + im*im);
	phase[sample] = atan2(im, re);
      }
      if (flip_horizontal) {
	for (sample=0; sample<sample_count; sample++)
	  tmp[sample] = amp[sample];
	for (sample=0; sample<sample_count; sample++)
	  amp[sample] = tmp[sample_count-sample-1];
      }
	  
      put_band_float_line(fp, meta, band*2, (int)row, amp);
      if (!ampOnly)
	put_band_float_line(fp, meta, band*2+1, (int)row, phase);
    }
      
    FREE(amp);
    FREE(phase);
    if (tmp)
      FREE(tmp);
    _TIFFfree(tiff_real_buf);
    _TIFFfree(tiff_imag_buf);
    GTIFFree(gtif);
    XTIFFClose(tiff);
  }

  // update the name field with directory name
  char *path = get_dirname(inBaseName);
  if (strlen(path)<=0)
    path = g_get_current_dir();
  char *p = path, *q = path;
  while (q) {
    if ((q = strchr(p, DIR_SEPARATOR)) != NULL)
      p = q+1;
  }
  sprintf(meta->general->basename, "%s", p);
  FREE(path);
  meta_write(meta, outDataName);

  meta_free(meta);
  FREE(radarsat2);
  FCLOSE(fp);
}
Ejemplo n.º 6
0
int bt_obex(int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;

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

	g_type_init();
	dbus_init();

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

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

	g_option_context_free(context);

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

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

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

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

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

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

		server_transfers = g_hash_table_new(g_str_hash, g_str_equal);

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

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

		g_free(root_folder);

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

		mainloop = g_main_loop_new(NULL, FALSE);

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

		g_main_loop_run(mainloop);

		/* Waiting for connections... */

		g_main_loop_unref(mainloop);

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

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

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

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

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

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

		g_object_unref(adapter);

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

		mainloop = g_main_loop_new(NULL, FALSE);

		OBEXClient *client = g_object_new(OBEXCLIENT_TYPE, NULL);

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

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

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

		g_main_loop_run(mainloop);

		/* Sending files process here ?? */

		g_main_loop_unref(mainloop);

		g_object_unref(agent);
		g_object_unref(client);

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

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

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

		g_object_unref(device);
		g_object_unref(adapter);

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

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

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

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

		g_print("FTP session opened\n");

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

				g_free(cmd);
				continue;
			}

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

					if (folders) g_ptr_array_unref(folders);

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

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

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

			g_strfreev(f_argv);
			g_free(cmd);
		}

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

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

		g_free(src_address);
		g_free(dst_address);
	}

	dbus_disconnect();

	exit(EXIT_SUCCESS);
}
Ejemplo n.º 7
0
int
main (int   argc,
      char *argv[])
{
  GtkWidget *win, *vbox, *frame, *alignment, *group_box;
  GtkWidget *hbox, *label, *chooser, *button;
  GtkSizeGroup *label_group;
  GOptionContext *context;
  gchar *cwd;

  context = g_option_context_new ("- test GtkFileChooserButton widget");
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  g_option_context_add_group (context, gtk_get_option_group (TRUE));
  g_option_context_parse (context, &argc, &argv, NULL);
  g_option_context_free (context);

  gtk_init (&argc, &argv);

  /* to test rtl layout, use "--right-to-left" */
  if (rtl)
    gtk_widget_set_default_direction (GTK_TEXT_DIR_RTL);

  cwd = g_get_current_dir();
  gtk_src_dir = g_path_get_dirname (cwd);
  g_free (cwd);

  win = gtk_dialog_new_with_buttons ("TestFileChooserButton", NULL, 0,
				     "_Quit", GTK_RESPONSE_CLOSE, NULL);
  g_signal_connect (win, "style-set", G_CALLBACK (win_style_set_cb), NULL);
  g_signal_connect (win, "response", G_CALLBACK (gtk_main_quit), NULL);

  vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 18);
  gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area (GTK_DIALOG (win))), vbox);

  frame = gtk_frame_new ("<b>GtkFileChooserButton</b>");
  gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_NONE);
  gtk_label_set_use_markup (GTK_LABEL (gtk_frame_get_label_widget (GTK_FRAME (frame))), TRUE);
  gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);

  alignment = gtk_alignment_new (0.0, 0.0, 1.0, 1.0);
  gtk_alignment_set_padding (GTK_ALIGNMENT (alignment), 6, 0, 12, 0);
  gtk_container_add (GTK_CONTAINER (frame), alignment);
  
  label_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
  
  group_box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
  gtk_container_add (GTK_CONTAINER (alignment), group_box);

  /* OPEN */
  hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
  gtk_box_pack_start (GTK_BOX (group_box), hbox, FALSE, FALSE, 0);

  label = gtk_label_new_with_mnemonic ("_Open:");
  gtk_size_group_add_widget (GTK_SIZE_GROUP (label_group), label);
  gtk_misc_set_alignment (GTK_MISC (label), 0.0, 0.5);
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);

  chooser = gtk_file_chooser_button_new ("Select A File - testfilechooserbutton",
                                         GTK_FILE_CHOOSER_ACTION_OPEN);
  gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_file_chooser_remove_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), chooser);
  g_signal_connect (chooser, "current-folder-changed",
		    G_CALLBACK (chooser_current_folder_changed_cb), NULL);
  g_signal_connect (chooser, "selection-changed", G_CALLBACK (chooser_selection_changed_cb), NULL);
  g_signal_connect (chooser, "file-activated", G_CALLBACK (chooser_file_activated_cb), NULL);
  g_signal_connect (chooser, "update-preview", G_CALLBACK (chooser_update_preview_cb), NULL);
  gtk_box_pack_start (GTK_BOX (hbox), chooser, TRUE, TRUE, 0);

  button = gtk_button_new_with_label ("Properties");
  g_signal_connect (button, "clicked", G_CALLBACK (properties_button_clicked_cb), chooser);
  gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0);

  button = gtk_button_new_with_label ("Tests");
  g_signal_connect (button, "clicked", G_CALLBACK (tests_button_clicked_cb), chooser);
  gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0);

  /* SELECT_FOLDER */
  hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
  gtk_box_pack_start (GTK_BOX (group_box), hbox, FALSE, FALSE, 0);

  label = gtk_label_new_with_mnemonic ("Select _Folder:");
  gtk_size_group_add_widget (GTK_SIZE_GROUP (label_group), label);
  gtk_misc_set_alignment (GTK_MISC (label), 0.0, 0.5);
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);

  chooser = gtk_file_chooser_button_new ("Select A Folder - testfilechooserbutton",
                                         GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
  gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_file_chooser_remove_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (chooser), gtk_src_dir, NULL);
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), chooser);
  g_signal_connect (chooser, "current-folder-changed",
		    G_CALLBACK (chooser_current_folder_changed_cb), NULL);
  g_signal_connect (chooser, "selection-changed", G_CALLBACK (chooser_selection_changed_cb), NULL);
  g_signal_connect (chooser, "file-activated", G_CALLBACK (chooser_file_activated_cb), NULL);
  g_signal_connect (chooser, "update-preview", G_CALLBACK (chooser_update_preview_cb), NULL);
  gtk_box_pack_start (GTK_BOX (hbox), chooser, TRUE, TRUE, 0);

  button = gtk_button_new_with_label ("Properties");
  g_signal_connect (button, "clicked", G_CALLBACK (properties_button_clicked_cb), chooser);
  gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0);

  button = gtk_button_new_with_label ("Tests");
  g_signal_connect (button, "clicked", G_CALLBACK (tests_button_clicked_cb), chooser);
  gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0);

  g_object_unref (label_group);

  gtk_widget_show_all (win);
  gtk_window_present (GTK_WINDOW (win));

  gtk_main ();

  return 0;
}
Ejemplo n.º 8
0
int
handle_tree (int argc, char *argv[], gboolean do_help)
{
  GOptionContext *context;
  GError *error = NULL;
  GFile *file;
  gchar *param;
  int i;

  g_set_prgname ("gio tree");

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

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

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

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

  g_option_context_free (context);

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

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

  return 0;
}
Ejemplo n.º 9
0
gboolean ipc_init_check(int argc, char **argv){
	GDir *dir;
	const char *entry, *user_name, *tmp_path;
	char *prefix;
	guint prefix_len;
	char *cur_dir_tmp;
	char *cur_dir;
	char *to_open;
	
	g_return_val_if_fail(input == NULL, FALSE);
	
	tmp_path=g_get_tmp_dir();
	dir=g_dir_open(tmp_path, 0, NULL);
	g_return_val_if_fail(dir != NULL, FALSE);
	
	user_name=g_get_user_name();
	prefix=g_strdup_printf(IPC_PIPE_PREFIX, user_name, GETTEXT_PACKAGE);
	prefix_len=strlen(prefix);

	cur_dir_tmp=g_get_current_dir();
	cur_dir=g_strdup_printf("%s/", cur_dir_tmp);
	uber_free(cur_dir_tmp);
	
	/* if another process creates a pipe while we are doing this,
	 * we may not get that pipe here. dunno if it's a problem */
	while((entry=g_dir_read_name(dir)) ){
		if(strncmp( entry, prefix, prefix_len ))
			continue;
		
		const char *pid_string;
		pid_t pid;
		char *filename;
		
		errno=0;
		pid_string=entry+prefix_len;
		/* this is not right, but should not cause real problems */
		pid=strtol(pid_string, NULL, 10);
		filename=g_build_filename(tmp_path, entry, NULL);
		
		if(errno && pid <= 0 && kill(pid, 0)){
			unlink(filename);
			uber_free(filename);
			continue;
		}
		/* it would be cool to check that the file is indeed a fifo,
		 * but again, who cares? */
		int fd;
		if((fd=open(filename, O_WRONLY | O_NONBLOCK)) == -1 ){
			perror("open");
			unlink(filename);
			uber_free(filename);
			continue;
		}
		
		/* TODO: validate argumants. */
		gboolean write_check=FALSE;
		if(!(write_check=write(fd, "", 1) )){
			close(fd);
			uber_free(filename);
			g_dir_close(dir);
			uber_free(prefix);
			return FALSE;
		}
		
		for(int i=0; i < argc; ++i) {
			to_open=NULL;
			if(!g_path_is_absolute(argv[i]))
				to_open=g_build_filename(cur_dir, argv[1], NULL);
			else
				to_open=g_build_filename(argv[i], NULL);
			if(!(write_check=write(fd, to_open, strlen(to_open) + 1)) )
				debug("**WARNING:** Failed to write: %s to %s", to_open, filename);
			uber_free(to_open);
		}
		close(fd);
		uber_free(filename);
		g_dir_close(dir);
		uber_free(prefix);
		return TRUE;
	}
	
	g_dir_close(dir);
	uber_free(prefix);
	ipc_main();
	return FALSE;
}
Ejemplo n.º 10
0
static gboolean
test_button_folder_states_for_action (GtkFileChooserAction action, gboolean use_dialog, gboolean set_folder_on_dialog)
{
  gboolean passed;
  GtkWidget *window;
  GtkWidget *button;
  char *folder;
  GtkWidget *dialog;
  char *current_working_dir;
  gboolean must_have_cwd;

  passed = TRUE;

  current_working_dir = g_get_current_dir ();
  must_have_cwd = !(use_dialog && set_folder_on_dialog);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  if (use_dialog)
    {
      dialog = gtk_file_chooser_dialog_new ("Test", NULL, action,
					    GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
					    GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
					    NULL);
      button = gtk_file_chooser_button_new_with_dialog (dialog);

      if (set_folder_on_dialog)
	gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), g_get_home_dir ());
    }
  else
    {
      button = gtk_file_chooser_button_new ("Test", action);
      dialog = NULL; /* keep gcc happy */
    }

  gtk_container_add (GTK_CONTAINER (window), button);

  /* Pre-map; no folder is set */
  wait_for_idle ();

  folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (button));
  if (must_have_cwd)
    passed = passed && (g_strcmp0 (folder, current_working_dir) == 0);
  else
    passed = passed && (g_strcmp0 (folder, g_get_home_dir()) == 0);

  log_test (passed, "test_button_folder_states_for_action(): %s, use_dialog=%d, set_folder_on_dialog=%d, pre-map, %s",
	    get_action_name (action),
	    use_dialog,
	    set_folder_on_dialog,
	    must_have_cwd ? "must have $cwd" : "must have explicit folder");

  /* Map; folder should be set */

  gtk_widget_show_all (window);
  gtk_widget_show_now (window);

  wait_for_idle ();

  folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (button));

  if (must_have_cwd)
    passed = passed && (g_strcmp0 (folder, current_working_dir) == 0);
  else
    passed = passed && (g_strcmp0 (folder, g_get_home_dir()) == 0);

  log_test (passed, "test_button_folder_states_for_action(): %s, use_dialog=%d, set_folder_on_dialog=%d, mapped, %s",
	    get_action_name (action),
	    use_dialog,
	    set_folder_on_dialog,
	    must_have_cwd ? "must have $cwd" : "must have explicit folder");
  g_free (folder);

  /* Unmap; folder should be set */

  gtk_widget_hide (window);
  wait_for_idle ();
  folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (button));

  if (must_have_cwd)
    passed = passed && (g_strcmp0 (folder, current_working_dir) == 0);
  else
    passed = passed && (g_strcmp0 (folder, g_get_home_dir()) == 0);

  log_test (passed, "test_button_folder_states_for_action(): %s, use_dialog=%d, set_folder_on_dialog=%d, unmapped, %s",
	    get_action_name (action),
	    use_dialog,
	    set_folder_on_dialog,
	    must_have_cwd ? "must have $cwd" : "must have explicit folder");
  g_free (folder);

  /* Re-map; folder should be set */

  gtk_widget_show_now (window);
  folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (button));

  if (must_have_cwd)
    passed = passed && (g_strcmp0 (folder, current_working_dir) == 0);
  else
    passed = passed && (g_strcmp0 (folder, g_get_home_dir()) == 0);
  wait_for_idle ();
  log_test (passed, "test_button_folder_states_for_action(): %s, use_dialog=%d, set_folder_on_dialog=%d, re-mapped, %s",
	    get_action_name (action),
	    use_dialog,
	    set_folder_on_dialog,
	    must_have_cwd ? "must have $cwd" : "must have explicit folder");
  g_free (folder);

  g_free (current_working_dir);

  gtk_widget_destroy (window);

  return passed;
}
Ejemplo n.º 11
0
static void
test_folder_switch_and_filters (void)
{
  gboolean passed;
  char *cwd;
  char *base_dir;
  GtkFilePath *cwd_path;
  GtkFilePath *base_dir_path;
  GtkWidget *dialog;
  GtkFileFilter *all_filter;
  GtkFileFilter *txt_filter;
  GtkFileChooserDefault *impl;

  passed = TRUE;

  cwd = g_get_current_dir ();
  base_dir = g_build_filename (cwd, "file-chooser-test-dir", NULL);

  dialog = gtk_file_chooser_dialog_new ("Test", NULL, GTK_FILE_CHOOSER_ACTION_OPEN,
					GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
					GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
					NULL);
  impl = get_impl_from_dialog (dialog);

  cwd_path = gtk_file_system_filename_to_path (impl->file_system, cwd);
  base_dir_path = gtk_file_system_filename_to_path (impl->file_system, base_dir);

  passed = passed && gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), base_dir);
  g_assert (passed);

  /* All files filter */

  all_filter = gtk_file_filter_new ();
  gtk_file_filter_set_name (all_filter, "All files");
  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), all_filter);

  /* *.txt filter */

  txt_filter = gtk_file_filter_new ();
  gtk_file_filter_set_name (all_filter, "*.txt");
  gtk_file_filter_add_pattern (txt_filter, "*.txt");
  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), txt_filter);

  /* Test filter set */

  gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dialog), all_filter);
  passed = passed && (gtk_file_chooser_get_filter (GTK_FILE_CHOOSER (dialog)) == all_filter);
  g_assert (passed);

  gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dialog), txt_filter);
  passed = passed && (gtk_file_chooser_get_filter (GTK_FILE_CHOOSER (dialog)) == txt_filter);
  log_test (passed, "test_folder_switch_and_filters(): set and get filter");
  g_assert (passed);

  gtk_widget_show (dialog);

  /* Test that filter is unchanged when we switch folders */

  gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), cwd);
  sleep_in_main_loop (0.5);
  passed = passed && (gtk_file_chooser_get_filter (GTK_FILE_CHOOSER (dialog)) == txt_filter);
  g_assert (passed);

  gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), base_dir);
  sleep_in_main_loop (0.25);

  g_signal_emit_by_name (impl->browse_path_bar, "path-clicked",
			 (GtkFilePath *) cwd_path,
			 (GtkFilePath *) base_dir_path,
			 FALSE);
  sleep_in_main_loop (0.25);
  passed = passed && (gtk_file_chooser_get_filter (GTK_FILE_CHOOSER (dialog)) == txt_filter);
  log_test (passed, "test_folder_switch_and_filters(): filter after changing folder");
  g_assert (passed);

  /* cleanups */
  g_free (cwd);
  g_free (base_dir);
  gtk_file_path_free (cwd_path);
  gtk_file_path_free (base_dir_path);

  gtk_widget_destroy (dialog);

  log_test (passed, "test_folder_switch_and_filters(): all filter tests");
}
Ejemplo n.º 12
0
static gboolean
test_reload_sequence (gboolean set_folder_before_map)
{
  GtkWidget *dialog;
  GtkFileChooserDefault *impl;
  gboolean passed;
  char *folder;
  char *current_working_dir;

  passed = TRUE;

  current_working_dir = g_get_current_dir ();

  dialog = gtk_file_chooser_dialog_new ("Test file chooser",
					NULL,
					GTK_FILE_CHOOSER_ACTION_OPEN,
					GTK_STOCK_CANCEL,
					GTK_RESPONSE_CANCEL,
					GTK_STOCK_OK,
					GTK_RESPONSE_ACCEPT,
					NULL);
  impl = get_impl_from_dialog (dialog);

  if (set_folder_before_map)
    {
      gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), g_get_home_dir ());

      wait_for_idle ();

      passed = passed && (impl->current_folder != NULL
			  && impl->browse_files_model != NULL
			  && (impl->load_state == LOAD_PRELOAD || impl->load_state == LOAD_LOADING || impl->load_state == LOAD_FINISHED)
			  && impl->reload_state == RELOAD_HAS_FOLDER
			  && (impl->load_state == LOAD_PRELOAD ? (impl->load_timeout_id != 0) : TRUE)
			  && ((impl->load_state == LOAD_LOADING || impl->load_state == LOAD_FINISHED)
			      ? (impl->load_timeout_id == 0 && impl->sort_model != NULL)
			      : TRUE));

      wait_for_idle ();

      folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (dialog));
      passed = passed && (g_strcmp0 (folder, g_get_home_dir()) == 0);
      g_free (folder);
    }
  else
    {
      /* Initially, no folder is not loaded or pending */
      passed = passed && (impl->current_folder == NULL
			  && impl->sort_model == NULL
			  && impl->browse_files_model == NULL
			  && impl->load_state == LOAD_EMPTY
			  && impl->reload_state == RELOAD_EMPTY
			  && impl->load_timeout_id == 0);

      wait_for_idle ();

      folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (dialog));
      passed = passed && (g_strcmp0 (folder, current_working_dir) == 0);
    }

  log_test (passed, "test_reload_sequence(): initial status");

  /* After mapping, it is loading some folder, either the one that was explicitly set or the default one */

  gtk_widget_show_now (dialog);

  wait_for_idle ();

  passed = passed && (impl->current_folder != NULL
		      && impl->browse_files_model != NULL
		      && (impl->load_state == LOAD_PRELOAD || impl->load_state == LOAD_LOADING || impl->load_state == LOAD_FINISHED)
		      && impl->reload_state == RELOAD_HAS_FOLDER
		      && (impl->load_state == LOAD_PRELOAD ? (impl->load_timeout_id != 0) : TRUE)
		      && ((impl->load_state == LOAD_LOADING || impl->load_state == LOAD_FINISHED)
			  ? (impl->load_timeout_id == 0 && impl->sort_model != NULL)
			  : TRUE));

  folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (dialog));
  if (set_folder_before_map)
    passed = passed && (g_strcmp0 (folder, g_get_home_dir()) == 0);
  else
    passed = passed && (g_strcmp0 (folder, current_working_dir) == 0);

  g_free (folder);

  log_test (passed, "test_reload_sequence(): status after map");

  /* Unmap it; we should still have a folder */

  gtk_widget_hide (dialog);

  wait_for_idle ();

  passed = passed && (impl->current_folder != NULL
		      && impl->browse_files_model != NULL
		      && (impl->load_state == LOAD_PRELOAD || impl->load_state == LOAD_LOADING || impl->load_state == LOAD_FINISHED)
		      && (impl->load_state == LOAD_PRELOAD ? (impl->load_timeout_id != 0) : TRUE)
		      && ((impl->load_state == LOAD_LOADING || impl->load_state == LOAD_FINISHED)
			  ? (impl->load_timeout_id == 0 && impl->sort_model != NULL)
			  : TRUE));

  folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (dialog));
  if (set_folder_before_map)
    passed = passed && (g_strcmp0 (folder, g_get_home_dir()) == 0);
  else
    passed = passed && (g_strcmp0 (folder, current_working_dir) == 0);

  g_free (folder);

  log_test (passed, "test_reload_sequence(): status after unmap");

  /* Map it again! */

  gtk_widget_show_now (dialog);

  wait_for_idle ();

  passed = passed && (impl->current_folder != NULL
		      && impl->browse_files_model != NULL
		      && (impl->load_state == LOAD_PRELOAD || impl->load_state == LOAD_LOADING || impl->load_state == LOAD_FINISHED)
		      && impl->reload_state == RELOAD_HAS_FOLDER
		      && (impl->load_state == LOAD_PRELOAD ? (impl->load_timeout_id != 0) : TRUE)
		      && ((impl->load_state == LOAD_LOADING || impl->load_state == LOAD_FINISHED)
			  ? (impl->load_timeout_id == 0 && impl->sort_model != NULL)
			  : TRUE));

  folder = gtk_file_chooser_get_current_folder (GTK_FILE_CHOOSER (dialog));
  if (set_folder_before_map)
    passed = passed && (g_strcmp0 (folder, g_get_home_dir()) == 0);
  else
    passed = passed && (g_strcmp0 (folder, current_working_dir) == 0);

  g_free (folder);

  log_test (passed, "test_reload_sequence(): status after re-map");

  gtk_widget_destroy (dialog);
  g_free (current_working_dir);

  return passed;
}
Ejemplo n.º 13
0
/* Main */
int main(int ac, char *av[])
{
	const char *name;
	char *env;
	gchar *glade_file;

#ifndef LKC_DIRECT_LINK
	kconfig_load();
#endif

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

	/* GTK stuffs */
	gtk_set_locale();
	gtk_init(&ac, &av);
	glade_init();

	//add_pixmap_directory (PACKAGE_DATA_DIR "/" PACKAGE "/pixmaps");
	//add_pixmap_directory (PACKAGE_SOURCE_DIR "/pixmaps");

	/* Determine GUI path */
	env = getenv(SRCTREE);
	if (env)
		glade_file = g_strconcat(env, "/scripts/kconfig/gconf.glade", NULL);
	else if (av[0][0] == '/')
		glade_file = g_strconcat(av[0], ".glade", NULL);
	else
		glade_file = g_strconcat(g_get_current_dir(), "/", av[0], ".glade", NULL);

	/* Load the interface and connect signals */
	init_main_window(glade_file);
	init_tree_model();
	init_left_tree();
	init_right_tree();

	/* Conf stuffs */
	if (ac > 1 && av[1][0] == '-') {
		switch (av[1][1]) {
		case 'a':
			//showAll = 1;
			break;
		case 'h':
		case '?':
			printf("%s <config>\n", av[0]);
			exit(0);
		}
		name = av[2];
	} else
		name = av[1];

	conf_parse(name);
	fixup_rootmenu(&rootmenu);
	conf_read(NULL);

	switch (view_mode) {
	case SINGLE_VIEW:
		display_tree_part();
		break;
	case SPLIT_VIEW:
		display_list();
		break;
	case FULL_VIEW:
		display_tree(&rootmenu);
		break;
	}

	gtk_main();

	return 0;
}
Ejemplo n.º 14
0
/*! \brief gattrib_main -- main gattrib fcn. 
 *
 *  \par
 *
 *------------------------------------------------------------------*/
void gattrib_main(void *closure, int argc, char *argv[])
{
  /* TOPLEVEL *pr_current is a global */
  /* SHEET_DATA *sheet_head is a global */
  /* GtkWidget *main_window is a global */

  int argv_index;
  gchar *cwd;
  gchar *logfile;

#ifdef HAVE_GTHREAD
  /* Gattrib isn't threaded, but some of GTK's file chooser
   * backends uses threading so we need to call g_thread_init().
   * GLib requires threading be initialised before any other GLib
   * functions are called. Do it now if its not already setup.  */
  if (!g_thread_supported ()) g_thread_init (NULL);
#endif

  /* Initialize gEDA stuff */
  libgeda_init();

  /* Ensure object->sel_func can be used to correctly determine object
   * locking when the project is saved out */
  select_func = s_toplevel_select_object;

  /* Note that argv_index holds index to first non-flag command line option 
   * (that is, to the first file name) */
  argv_index = parse_commandline(argc, argv);
  
  /* ----------  create log file right away ---------- */
  /* ----------  even if logging is enabled ---------- */
  cwd = g_get_current_dir();
  logfile = g_build_filename (cwd, "gattrib.log", NULL);
  s_log_init (logfile);
  g_free (logfile);
  g_free (cwd);

  s_log_message
    ("gEDA/gattrib version %s%s.%s\n", PREPEND_VERSION_STRING, 
     DOTTED_VERSION, DATE_VERSION);
  s_log_message
    ("gEDA/gattrib comes with ABSOLUTELY NO WARRANTY; see COPYING for more details.\n");
  s_log_message
    ("This is free software, and you are welcome to redistribute it under certain\n");
  s_log_message
    ("conditions; please see the COPYING file for more details.\n\n");
  
  if (!quiet_mode) {
    fflush(stderr);
    fflush(stdout);
    fprintf(stderr, 
	    "gEDA/gattrib version %s%s.%s\n", PREPEND_VERSION_STRING, 
            DOTTED_VERSION, DATE_VERSION);
    fprintf(stderr,
	    "gEDA/gattrib comes with ABSOLUTELY NO WARRANTY; see COPYING for more details.\n");
    fprintf(stderr,
	    "This is free software, and you are welcome to redistribute it under certain\n");
    fprintf(stderr,
	    "conditions; please see the COPYING file for more details.\n\n");
  }

  /* ------  register guile (scheme) functions.  Necessary to parse RC file.  ------ */
  g_register_funcs();

  /* ---------- Start creation of new project: (TOPLEVEL *pr_current) ---------- */
  pr_current = s_toplevel_new();

  /* ----- Read in RC files.   ----- */
  g_rc_parse(pr_current, "gattribrc", NULL);

  i_vars_set(pr_current);

  gtk_init(&argc, &argv);

  x_window_init();  
  
  /* ---------- Initialize SHEET_DATA data structure ---------- */
  sheet_head = s_sheet_data_new();   /* sheet_head was declared in globals.h */

  GSList *file_list = NULL;
  if (argv_index >= argc) {
     /* No files specified on the command line, pop up the File open dialog. */
     file_list = x_fileselect_open();
     if(file_list == NULL)
        exit(0);
  } else {
     /* Construct the list of filenames from the command line.
      * argv_index holds the position of the first filename  */
     while (argv_index < argc) {
        gchar *filename = f_normalize_filename(argv[argv_index], NULL);
        if (filename != NULL) {
            file_list = g_slist_append(file_list, filename);
        } else {
            fprintf(stderr, "Couldn't find file [%s]\n", argv[argv_index]);
            exit(1);
        }
        argv_index++;
     }
  }

  /* Load the files */
  if(x_fileselect_load_files(file_list) == FALSE) {
     /* just exit the program */
     exit(1);
  }
  
  g_slist_foreach(file_list, (GFunc)g_free, NULL);
  g_slist_free(file_list);

  gtk_main();
  exit(0);
}
Ejemplo n.º 15
0
int
main(int argc, char **argv)
{
    /* These may be absolute or relative to top_builddir, depending whether
     * GJS_TOP_SRCDIR is absolute or not */
    const char * const path_directories[] = {
        GJS_TOP_SRCDIR"/modules",
        GJS_TOP_SRCDIR"/test/js/modules",
        ".libs:",
        NULL
    };

    char *js_test_dir;
    char *working_dir;
    char *gjs_unit_path;
    char *gjs_unit_dir;
    char *top_builddir;
    char *data_home;
    GString *path;
    size_t i;
    GSList *all_tests, *iter;
    GSList *test_filenames = NULL;
    int retval;

    working_dir = g_get_current_dir();

    gjs_unit_path = build_absolute_filename(argv[0], NULL);

    gjs_unit_dir = g_path_get_dirname(gjs_unit_path);
    g_free(gjs_unit_path);
    /* the gjs-unit executable will be in <top_builddir>/.libs */
    top_builddir = g_path_get_dirname(gjs_unit_dir);
    g_free(gjs_unit_dir);
    top_srcdir = build_absolute_filename(top_builddir, GJS_TOP_SRCDIR, NULL);

    /* Normalize, not strictly necessary */
    g_chdir(top_builddir);
    g_free(top_builddir);
    top_builddir = g_get_current_dir();

    g_chdir(top_srcdir);
    g_free(top_srcdir);
    top_srcdir = g_get_current_dir();

    g_chdir(working_dir);
    g_free(working_dir);

    /* we're always going to use uninstalled files, set up necessary
     * environment variables, but don't overwrite if already set */

    data_home = g_build_filename(top_builddir, "test_user_data", NULL);
    path = g_string_new(NULL);
    for(i = 0; i < G_N_ELEMENTS(path_directories); i++) {
        char *directory;

        if (i != 0)
            g_string_append_c(path, ':');

        directory = build_absolute_filename(top_builddir, path_directories[i], NULL);
        g_string_append(path, directory);
        g_free(directory);
    }

    g_setenv("TOP_SRCDIR", top_srcdir, FALSE);
    g_setenv("BUILDDIR", top_builddir, FALSE);
    g_free(top_builddir);
    g_setenv("XDG_DATA_HOME", data_home, FALSE);
    g_free(data_home);
    g_setenv("GJS_PATH", path->str, FALSE);
    g_string_free(path, TRUE);
    /* The tests are known to fail in the presence of the JIT;
     * we leak objects.
     * https://bugzilla.gnome.org/show_bug.cgi?id=616193
     */
    g_setenv("GJS_DISABLE_JIT", "1", FALSE);

    {
        const char *timeout_str = g_getenv("GJS_TEST_TIMEOUT");
        if (timeout_str != NULL) {
            guint timeout = (guint)g_ascii_strtoull(timeout_str, NULL, 10);
            if (timeout > 0)
                gjs_crash_after_timeout(timeout);
        }
    }

    setlocale(LC_ALL, "");
    g_test_init(&argc, &argv, NULL);

    /* iterate through all 'test*.js' files in ${top_srcdir}/test/js */
    js_test_dir = g_build_filename(top_srcdir, "test", "js", NULL);

    all_tests = read_all_dir_sorted(js_test_dir);
    for (iter = all_tests; iter; iter = iter->next) {
        char *name = iter->data;
        char *test_name;
        char *file_name;

        if (!(g_str_has_prefix(name, "test") &&
              g_str_has_suffix(name, ".js"))) {
            g_free(name);
            continue;
        }
        if (g_str_has_prefix (name, "testCairo") && g_getenv ("GJS_TEST_SKIP_CAIRO"))
            continue;

        /* pretty print, drop 'test' prefix and '.js' suffix from test name */
        test_name = g_strconcat("/js/", name + 4, NULL);
        test_name[strlen(test_name)-3] = '\0';

        file_name = g_build_filename(js_test_dir, name, NULL);
        g_test_add(test_name, GjsTestJSFixture, file_name, setup, test, teardown);
        g_free(name);
        g_free(test_name);
        test_filenames = g_slist_prepend(test_filenames, file_name);
        /* not freeing file_name yet as it's needed while running the test */
    }
    g_free(js_test_dir);
    g_slist_free(all_tests);

    retval =  g_test_run ();
    g_slist_foreach(test_filenames, (GFunc)g_free, test_filenames);
    g_slist_free(test_filenames);
    g_free(top_srcdir);
    return retval;
}
Ejemplo n.º 16
0
/* Find the prefix part of a dir ... name is the name of this prog from argv0.
 *
 * dir					name		guess prefix
 *
 * /home/john/vips-7.6.4/bin/vips-7.6	vips-7.6	/home/john/vips-7.6.4
 * /usr/local/bin/ip			ip		/usr/local
 *
 * all other forms ... return NULL.
 */
static char *
extract_prefix( const char *dir, const char *name )
{
	char edir[VIPS_PATH_MAX];
	char vname[VIPS_PATH_MAX];
	int i;

#ifdef DEBUG
	printf( "extract_prefix: trying for dir = \"%s\", name = \"%s\"\n", 
		dir, name );
#endif /*DEBUG*/

	/* Is dir relative? Prefix with cwd.
	 */
	if( !g_path_is_absolute( dir ) ) {
		char *cwd; 

		cwd = g_get_current_dir();
		vips_snprintf( edir, VIPS_PATH_MAX, 
			"%s" G_DIR_SEPARATOR_S "%s", cwd, dir );
		g_free( cwd );
	}
	else {
		vips_strncpy( edir, dir, VIPS_PATH_MAX );
	}

	/* Chop off the trailing prog name, plus the trailing
	 * G_DIR_SEPARATOR_S.
	 */
	if( !vips_ispostfix( edir, name ) ) 
		return( NULL );
	vips_strncpy( vname, edir, VIPS_PATH_MAX );
	vname[strlen( edir ) - strlen( name ) - 1] = '\0';

	/* Remove any "/./", any trailing "/.", any trailing "/".
	 */
	for( i = 0; i < (int) strlen( vname ); i++ ) 
		if( vips_isprefix( G_DIR_SEPARATOR_S "." G_DIR_SEPARATOR_S, 
			vname + i ) )
			memcpy( vname + i, vname + i + 2, 
				strlen( vname + i + 2 ) + 1 );
	if( vips_ispostfix( vname, G_DIR_SEPARATOR_S "." ) )
		vname[strlen( vname ) - 2] = '\0';
	if( vips_ispostfix( vname, G_DIR_SEPARATOR_S ) )
		vname[strlen( vname ) - 1] = '\0';

#ifdef DEBUG
	printf( "extract_prefix: canonicalised path = \"%s\"\n", vname );
#endif /*DEBUG*/

	/* Ought to be a "/bin" at the end now.
	 */
	if( !vips_ispostfix( vname, G_DIR_SEPARATOR_S "bin" ) ) 
		return( NULL );
	vname[strlen( vname ) - strlen( G_DIR_SEPARATOR_S "bin" )] = '\0';

#ifdef DEBUG
	printf( "extract_prefix: found \"%s\"\n", vname );
#endif /*DEBUG*/

	return( vips_strdup( NULL, vname ) );
}
Ejemplo n.º 17
0
Archivo: fmon.c Proyecto: bhuisgen/fmon
void
parse_command_line(gint argc, gchar *argv[])
{
  GOptionContext *context;
  GOptionGroup *watcher;
  GError *error = NULL;
  gchar *help;
  gchar *current_dir, *file;
  gchar *config_file = NULL;
  gboolean verbose = FALSE;
  gint show_version = 0;
  gchar *watcher_path = NULL;
  gboolean watcher_recursive = CONFIG_KEY_WATCHER_RECURSIVE_DEFAULT;
  gint watcher_maxdepth = CONFIG_KEY_WATCHER_MAXDEPTH_DEFAULT;
  gchar *watcher_event = NULL;
  gboolean watcher_mount = CONFIG_KEY_WATCHER_MOUNT_DEFAULT;
  gboolean watcher_readable = CONFIG_KEY_WATCHER_READABLE_DEFAULT;
  gboolean watcher_writable = CONFIG_KEY_WATCHER_WRITABLE_DEFAULT;
  gboolean watcher_executable = CONFIG_KEY_WATCHER_EXECUTABLE_DEFAULT;
  gchar *watcher_size = NULL;
  gchar *watcher_type = NULL;
  gchar *watcher_user = NULL;
  gchar *watcher_group = NULL;
  gchar *watcher_include = NULL;
  gchar *watcher_exclude = NULL;
  gchar *watcher_exec = NULL;
  gboolean watcher_print = FALSE;
  gboolean watcher_print0 = FALSE;

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

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

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

  g_option_context_add_main_entries(context, main_entries, PACKAGE);

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

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

      g_free(help);
      g_option_context_free(context);

      exit(1);
    }

  g_option_context_free(context);

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

      exit(0);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          g_free(current_dir);
          g_free(config_file);

          config_file = file;
        }

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

          exit(1);
        }
    }

  app->verbose = verbose;
}
Ejemplo n.º 18
0
/* Guess a value for the install PREFIX.
 */
static const char *
guess_prefix( const char *argv0, const char *name )
{
	char *prefix;

	/* Try to guess from argv0.
	 */
	if( argv0 ) {
		if( g_path_is_absolute( argv0 ) ) {
			/* Must point to our executable.
			 */
			if( (prefix = extract_prefix( argv0, name )) ) {
#ifdef DEBUG
				printf( "vips_guess_prefix: found \"%s\" from "
					"argv0\n", prefix );
#endif /*DEBUG*/
				return( prefix );
			} 
		}

		/* Look along path for name.
		 */
		if( (prefix = find_file( name )) ) {
#ifdef DEBUG
			printf( "vips_guess_prefix: found \"%s\" from "
				"PATH\n", prefix );
#endif /*DEBUG*/
			return( prefix );
		}
        }

#ifdef HAVE_REALPATH
	/* Try to guess from cwd. Only if this is a relative path, though. No
 	 * realpath on winders, but fortunately it seems to always generate
 	 * a full path in argv[0].
	 */
	if( !g_path_is_absolute( argv0 ) ) {
		char full_path[VIPS_PATH_MAX];
		char *resolved;
		char *dir;

		dir = g_get_current_dir(); 
		vips_snprintf( full_path, VIPS_PATH_MAX, 
			"%s" G_DIR_SEPARATOR_S "%s", dir, argv0 );
		g_free( dir ); 

		if( (resolved = realpath( full_path, NULL )) ) {
			prefix = extract_prefix( resolved, name );
			free( resolved ); 
			if( prefix ) { 
#ifdef DEBUG
				printf( "vips_guess_prefix: found \"%s\" "
					"from cwd\n", prefix );
#endif /*DEBUG*/
				return( prefix );
			}
		}
	}
#endif /*HAVE_REALPATH*/

	/* Fall back to the configure-time prefix.
	 */
	return( VIPS_PREFIX );
}
Ejemplo n.º 19
0
int
main (int   arg,
      char *argv[])
{
  GModule *module_self, *module_a, *module_b;
  gchar *string;
  gchar *plugin_a, *plugin_b;
  SimpleFunc f_a, f_b, f_self;
  GModuleFunc gmod_f;

  string = g_get_current_dir ();
  g_print ("testgmodule (%s):\n", string);

#ifdef NATIVE_WIN32
  plugin_a = g_strconcat (string, "\\libgplugin_a.dll", NULL);
  plugin_b = g_strconcat (string, "\\libgplugin_b.dll", NULL);
#elif (G_MODULE_IMPL == G_MODULE_IMPL_DLD)
  plugin_a = g_strconcat (string, "/.libs/", "libgplugin_a.sl", NULL);
  plugin_b = g_strconcat (string, "/.libs/", "libgplugin_b.sl", NULL);
#else /* G_MODULE_IMPL != G_MODULE_IMPL_DLD && !NATIVE_WIN32 */
  plugin_a = g_strconcat (string, "/.libs/", "libgplugin_a.so", NULL);
  plugin_b = g_strconcat (string, "/.libs/", "libgplugin_b.so", NULL);
#endif /* G_MODULE_IMPL != G_MODULE_IMPL_DLD && !NATIVE_WIN32 */
  g_free (string);

  /* module handles
   */
  g_print ("get main module handle\n");
  module_self = g_module_open (NULL, G_MODULE_BIND_LAZY);
  if (!module_self)
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("check that not yet bound symbols in shared libraries of main module are retrievable:\n");
  string = "g_module_close";
  g_print ("retrive symbol `%s' from \"%s\":\n", string, g_basename (g_module_name (module_self)));
  if (!g_module_symbol (module_self, string, (gpointer) &f_self))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("retrived symbol `%s' as %p\n", string, f_self);
  g_print ("load plugin from \"%s\"\n", plugin_a);
  module_a = g_module_open (plugin_a, G_MODULE_BIND_LAZY);
  if (!module_a)
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("load plugin from \"%s\"\n", plugin_b);
  module_b = g_module_open (plugin_b, G_MODULE_BIND_LAZY);
  if (!module_b)
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }

  /* get plugin specific symbols and call them
   */
  string = "gplugin_a_func";
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_a)));
  if (!g_module_symbol (module_a, string, (gpointer) &f_a))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  string = "gplugin_b_func";
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_b)));
  if (!g_module_symbol (module_b, string, (gpointer) &f_b))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("call plugin function(%p) A: ", f_a);
  f_a ();
  g_print ("call plugin function(%p) B: ", f_b);
  f_b ();

  /* get and call globally clashing functions
   */
  string = "g_clash_func";
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_self)));
  if (!g_module_symbol (module_self, string, (gpointer) &f_self))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_a)));
  if (!g_module_symbol (module_a, string, (gpointer) &f_a))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_b)));
  if (!g_module_symbol (module_b, string, (gpointer) &f_b))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("call plugin function(%p) self: ", f_self);
  f_self ();
  g_print ("call plugin function(%p) A: ", f_a);
  f_a ();
  g_print ("call plugin function(%p) B: ", f_b);
  f_b ();

  /* get and call clashing plugin functions
   */
  string = "gplugin_clash_func";
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_self)));
  if (!g_module_symbol (module_self, string, (gpointer) &f_self))
    f_self = NULL;
  g_print ("retrived function `%s' from self: %p\n", string, f_self);
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_a)));
  if (!g_module_symbol (module_a, string, (gpointer) &f_a))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_b)));
  if (!g_module_symbol (module_b, string, (gpointer) &f_b))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("call plugin function(%p) A: ", f_a);
  plugin_clash_func = f_a;
  plugin_clash_func ();
  g_print ("call plugin function(%p) B: ", f_b);
  plugin_clash_func = f_b;
  plugin_clash_func ();

  /* call gmodule function form A
   */
  string = "gplugin_a_module_func";
  g_print ("retrive symbol `%s' from \"%s\"\n", string, g_basename (g_module_name (module_a)));
  if (!g_module_symbol (module_a, string, (gpointer) &gmod_f))
    {
      g_print ("error: %s\n", g_module_error ());
      return 1;
    }
  g_print ("call plugin A's module function(%p):\n{\n", gmod_f);
  gmod_f (module_b);
  g_print ("}\n");


  /* unload plugins
   */
  g_print ("unload plugin A:\n");
  if (!g_module_close (module_a))
    g_print ("error: %s\n", g_module_error ());
  g_print ("unload plugin B:\n");
  if (!g_module_close (module_b))
    g_print ("error: %s\n", g_module_error ());

#if 0
  g_log_set_fatal_mask ("GModule", G_LOG_FATAL_MASK|G_LOG_LEVEL_WARNING);
  g_module_symbol (0, 0, 0);
  g_warning("jahooo");
  g_on_error_query (".libs/testgmodule");
#endif

  return 0;
}
Ejemplo n.º 20
0
static void
tree_expand_node (DirTree * dt, GtkCTreeNode * node, gboolean expand)
{
    GtkCTreeNode *child;
    DirTreeNode *parent_node;
    DirTreeNode *child_node;
    DIR    *dir;
    struct stat stat_buff;
    struct dirent *entry;
    gboolean has_subdirs, has_link, has_access;
    char   *old_path;
    char   *subdir = "?";
    char   *file_name;
    GtkWidget *top = gtk_widget_get_toplevel (GTK_WIDGET (dt));
    old_path = g_get_current_dir ();

    if (!old_path)
	return;

    parent_node = gtk_ctree_node_get_row_data (GTK_CTREE (dt), node);

    if (chdir (parent_node->path))
    {
	g_free (old_path);
	return;
    }

    dir = opendir (".");

    if (!dir)
    {
	chdir (old_path);
	g_free (old_path);
	return;
    }

    dirtree_set_cursor (top, GDK_WATCH);

    gtk_clist_freeze (GTK_CLIST (dt));

    tree_collapse (GTK_CTREE (dt), node);

    child = NULL;

    while ((entry = readdir (dir)))
    {
	if (!stat (entry->d_name, &stat_buff) && S_ISDIR (stat_buff.st_mode)
	    && tree_is_dotfile (entry->d_name, dt->show_dotfile))
	{
	    child_node = g_malloc0 (sizeof (DirTreeNode));

	    child_node->path =
		g_strconcat (parent_node->path, "/", entry->d_name, NULL);

	    has_link = islink (entry->d_name);
	    has_access = access (entry->d_name, X_OK);

	    file_name = entry->d_name;

	    if (has_access)
	    {
		child = gtk_ctree_insert_node (GTK_CTREE (dt),
					       node, child,
					       &file_name,
					       CTREE_SPACING,
					       lckfolder_pixmap,
					       lckfolder_mask, NULL,
					       NULL, 1, 0);
		has_subdirs = FALSE;
	    }
	    else if (!strcmp (entry->d_name, "."))
	    {
		child = gtk_ctree_insert_node (GTK_CTREE (dt),
					       node, child,
					       &file_name,
					       CTREE_SPACING,
					       gofolder_pixmap,
					       gofolder_mask, NULL,
					       NULL, 1, 0);

		has_subdirs = FALSE;
	    }
	    else if (!strcmp (entry->d_name, ".."))
	    {
		child = gtk_ctree_insert_node (GTK_CTREE (dt),
					       node, child,
					       &file_name,
					       CTREE_SPACING,
					       upfolder_pixmap,
					       upfolder_mask, NULL,
					       NULL, 1, 0);

		has_subdirs = FALSE;
	    }
	    else
	    {
		if (dt->check_dir)
		{
		    if (dt->check_hlinks)
		    {
			if (stat_buff.st_nlink == 2 && dt->show_dotfile)
			    has_subdirs = TRUE;
			else if (stat_buff.st_nlink > 2)
			    has_subdirs = TRUE;
			else if (stat_buff.st_nlink == 1)
			    has_subdirs =
				tree_is_subdirs (entry->d_name,
						 dt->show_dotfile);
			else
			    has_subdirs = FALSE;
		    }
		    else
			has_subdirs =
			    tree_is_subdirs (entry->d_name, dt->show_dotfile);

		}
		else
		    has_subdirs = TRUE;

		if (access (entry->d_name, X_OK) != 0)
		{
		    has_subdirs = FALSE;
		}

		if (has_link)
		    child = gtk_ctree_insert_node (GTK_CTREE (dt),
						   node, child,
						   &file_name,
						   CTREE_SPACING,
						   lfolder_pixmap,
						   lfolder_mask,
						   lofolder_pixmap,
						   lofolder_mask,
						   !has_subdirs, 0);
		else
		    child = gtk_ctree_insert_node (GTK_CTREE (dt),
						   node, child,
						   &file_name,
						   CTREE_SPACING,
						   folder_pixmap,
						   folder_mask,
						   ofolder_pixmap,
						   ofolder_mask,
						   !has_subdirs, 0);
	    }

	    if (child)
	    {
		gtk_ctree_node_set_row_data_full (GTK_CTREE (dt), child,
						  child_node,
						  dirtree_destroy_tree);

		if (has_subdirs)
		    gtk_ctree_insert_node (GTK_CTREE (dt),
					   child, NULL,
					   &subdir,
					   CTREE_SPACING,
					   NULL, NULL, NULL, NULL, 0, 0);
	    }
	}

	if (dt->check_events)
	    while (gtk_events_pending ())
		gtk_main_iteration ();
    }

    closedir (dir);

    chdir (old_path);
    g_free (old_path);

    gtk_ctree_sort_node (GTK_CTREE (dt), node);

    if (expand == TRUE)
	gtk_ctree_expand (GTK_CTREE (dt), node);

    gtk_clist_thaw (GTK_CLIST (dt));

    dirtree_set_cursor (top, -1);
}
Ejemplo n.º 21
0
void main_prog(void *closure, int argc, char *argv[])
{
    int i;
    int argv_index;
    char *cwd;
    gchar *str;
    gchar *filename;

    TOPLEVEL *pr_current;

    /* set default output filename */
    output_filename = g_strdup("output.net");

    argv_index = parse_commandline(argc, argv);
    cwd = g_get_current_dir();

    scm_set_program_arguments (argc, argv, NULL);

    /* this is a kludge to make sure that spice mode gets set */
    /*  Hacked by SDB to allow spice netlisters of arbitrary name
     *        as long as they begin with "spice".  For example, this spice
     *  netlister is valid: "spice-sdb".
     */
    if (guile_proc) {
        if (strncmp(guile_proc, "spice", 5) == 0) {
            netlist_mode = SPICE;
        }
    }

    libgeda_init();

    /* create log file right away */
    /* even if logging is enabled */
    s_log_init ("gnetlist");

    s_log_message("gEDA/gnetlist version %s%s.%s\n", PREPEND_VERSION_STRING,
                  PACKAGE_DOTTED_VERSION, PACKAGE_DATE_VERSION);
    s_log_message
        ("gEDA/gnetlist comes with ABSOLUTELY NO WARRANTY; see COPYING for more details.\n");
    s_log_message
        ("This is free software, and you are welcome to redistribute it under certain\n");
    s_log_message
        ("conditions; please see the COPYING file for more details.\n\n");

#if defined(__MINGW32__) && defined(DEBUG)
    fprintf(stderr, "This is the MINGW32 port.\n\n");
#endif

    /* register guile (scheme) functions */
    g_register_funcs();

    pr_current = s_toplevel_new ();

    /* Evaluate Scheme expressions that need to be run before rc files
     * are loaded. */
    scm_eval (pre_rc_list, scm_current_module ());

    g_rc_parse (pr_current, argv[0], "gnetlistrc", rc_filename);
    /* immediately setup user params */
    i_vars_set (pr_current);

    s_rename_init();

    if(list_backends) {
      gnetlist_backends(pr_current);
      exit (0);
    }

    /* Evaluate the first set of Scheme expressions before we load any
     * schematic files */
    scm_eval (pre_backend_list, scm_current_module ());

    i = argv_index;
    while (argv[i] != NULL) {
      GError *err = NULL;

      if (g_path_is_absolute(argv[i])) {
        /* Path is already absolute so no need to do any concat of cwd */
        filename = g_strdup (argv[i]);
      } else {
        filename = g_build_filename (cwd, argv[i], NULL);
      }

      if (!quiet_mode) {
        s_log_message ("Loading schematic [%s]\n", filename);
        printf ("Loading schematic [%s]\n", filename);
      }

      s_page_goto (pr_current, s_page_new (pr_current, filename));

      if (!f_open (pr_current, pr_current->page_current, filename, &err)) {
        g_warning ("%s\n", err->message);
        fprintf (stderr, "%s\n", err->message);
        g_error_free (err);
      }

      /* collect input filenames for backend use */
      input_files = g_slist_append(input_files, argv[i]);

      i++;
      g_free (filename);
    }

    /* Change back to the directory where we started.  This is done */
    /* since gnetlist is a command line utility and will deposit its output */
    /* in the current directory.  Having the output go to a different */
    /* directory will confuse the user (confused me, at first). */
    if (chdir (cwd)) {
      /* Error occured with chdir */
#warning FIME: What do we do?
    }
    /* free(cwd); - Defered; see below */

    if (argv[argv_index] == NULL) {
        fprintf (stderr, "ERROR: No schematics files specified for processing.\n");
        fprintf (stderr, "\nRun `%s --help' for more information.\n", argv[0]);
        exit (1);
    }

    g_set_project_current(pr_current);
#if DEBUG
    s_page_print_all(pr_current);
#endif

    /* Load basic gnetlist functions */
    scm_primitive_load_path (scm_from_utf8_string ("gnetlist.scm"));

    if (guile_proc) {
      SCM s_backend_path;

      /* Search for backend scm file in load path */
      str = g_strdup_printf("gnet-%s.scm", guile_proc);
      s_backend_path = scm_sys_search_load_path (scm_from_locale_string (str));
      g_free (str);

      /* If it couldn't be found, fail. */
      if (scm_is_false (s_backend_path)) {
        fprintf (stderr, "ERROR: Could not find backend `%s' in load path.\n",
                 guile_proc);
        fprintf (stderr,
                 "\nRun `%s --list-backends' for a full list of available backends.\n",
                 argv[0]);
        exit (1);
      }

      /* Load backend code. */
      scm_primitive_load (s_backend_path);

      /* Evaluate second set of Scheme expressions. */
      scm_eval (post_backend_list, scm_current_module ());
    }

    s_traverse_init();
    s_traverse_start(pr_current);

    /* Change back to the directory where we started AGAIN.  This is done */
    /* because the s_traverse functions can change the Current Working Directory. */
    if (chdir (cwd)) {
      /* Error occured with chdir */
#warning FIXME: What do we do?
    }
    g_free(cwd);

    /* Run post-traverse code. */
    scm_primitive_load_path (scm_from_utf8_string ("gnetlist-post.scm"));

    if (guile_proc) {
        /* check size here hack */
        str = g_strdup_printf ("(%s \"%s\")", guile_proc, output_filename);
        scm_c_eval_string (str);
        g_free (str);
        /* gh_eval_str_with_stack_saving_handler (input_str); */
    } else if (interactive_mode) {
        scm_c_eval_string ("(set-repl-prompt! \"gnetlist> \")");
        scm_shell (0, NULL);
    } else {
        fprintf(stderr,
                "You gave neither backend to execute nor interactive mode!\n");
    }

    gnetlist_quit();
}
Ejemplo n.º 22
0
gboolean
download_cb(WebKitWebView *web_view, WebKitDownload *download, gpointer user_data) {
    (void) web_view; (void) user_data;

    /* get the URI being downloaded */
    const gchar *uri = webkit_download_get_uri(download);

    if (uzbl.state.verbose)
        printf("Download requested -> %s\n", uri);

    if (!uzbl.behave.download_handler) {
        webkit_download_cancel(download);
        return FALSE; /* reject downloads when there's no download handler */
    }

    /* get a reasonable suggestion for a filename */
    const gchar *suggested_filename;
    g_object_get(download, "suggested-filename", &suggested_filename, NULL);

    /* get the mimetype of the download */
    const gchar *content_type = NULL;
    WebKitNetworkResponse *r  = webkit_download_get_network_response(download);
    /* downloads can be initiated from the context menu, in that case there is
       no network response yet and trying to get one would crash. */
    if(WEBKIT_IS_NETWORK_RESPONSE(r)) {
        SoupMessage        *m = webkit_network_response_get_message(r);
        SoupMessageHeaders *h = NULL;
        g_object_get(m, "response-headers", &h, NULL);
        if(h) /* some versions of libsoup don't have "response-headers" here */
            content_type = soup_message_headers_get_one(h, "Content-Type");
    }

    if(!content_type)
        content_type = "application/octet-stream";

    /* get the filesize of the download, as given by the server.
       (this may be inaccurate, there's nothing we can do about that.)  */
    unsigned int total_size = webkit_download_get_total_size(download);

    GArray *a = g_array_new (TRUE, FALSE, sizeof(gchar*));
    const CommandInfo *c = parse_command_parts(uzbl.behave.download_handler, a);
    if(!c) {
        webkit_download_cancel(download);
        g_array_free(a, TRUE);
        return FALSE;
    }

    g_array_append_val(a, uri);
    g_array_append_val(a, suggested_filename);
    g_array_append_val(a, content_type);
    gchar *total_size_s = g_strdup_printf("%d", total_size);
    g_array_append_val(a, total_size_s);

    GString *result = g_string_new ("");
    run_parsed_command(c, a, result);

    g_free(total_size_s);
    g_array_free(a, TRUE);

    /* no response, cancel the download */
    if(result->len == 0) {
        webkit_download_cancel(download);
        return FALSE;
    }

    /* we got a response, it's the path we should download the file to */
    gchar *destination_path = result->str;
    g_string_free(result, FALSE);

    /* presumably people don't need newlines in their filenames. */
    char *p = strchr(destination_path, '\n');
    if ( p != NULL ) *p = '\0';

    /* set up progress callbacks */
    g_signal_connect(download, "notify::status",   G_CALLBACK(download_status_cb),   NULL);
    g_signal_connect(download, "notify::progress", G_CALLBACK(download_progress_cb), NULL);

    /* convert relative path to absolute path */
    if(destination_path[0] != '/') {
        gchar *rel_path = destination_path;
        gchar *cwd = g_get_current_dir();
        destination_path = g_strconcat(cwd, "/", destination_path, NULL);
        g_free(cwd);
        g_free(rel_path);
    }

    send_event(DOWNLOAD_STARTED, NULL, TYPE_STR, destination_path, NULL);

    /* convert absolute path to file:// URI */
    gchar *destination_uri = g_strconcat("file://", destination_path, NULL);
    g_free(destination_path);

    webkit_download_set_destination_uri(download, destination_uri);
    g_free(destination_uri);

    return TRUE;
}
Ejemplo n.º 23
0
void 
main_prog(void *closure, int argc, char *argv[])
{
  int i;
  int argv_index;
  char *cwd;
  
  TOPLEVEL *pr_current;

  argv_index = parse_commandline(argc, argv);
  cwd = g_get_current_dir();

  libgeda_init();

  /* create log file right away */
  /* even if logging is enabled */
  s_log_init ("gschlas");
	
  logging_dest=STDOUT_TTY;

#if defined(__MINGW32__) && defined(DEBUG)
  fprintf(stderr, "This is the MINGW32 port.\n");
#endif  

  logging_dest=-1; /* don't output to the screen for now */
  
  /* register guile (scheme) functions */
  g_register_funcs();

  pr_current = s_toplevel_new ();
  g_rc_parse (pr_current, argv[0], "gschlasrc", rc_filename);
  i_vars_set(pr_current);
  
  i = argv_index;
  while (argv[i] != NULL) {

    gchar *filename;
    GError *err = NULL;

    if (g_path_is_absolute(argv[i]))
    {
      /* Path is already absolute so no need to do any concat of cwd */
      filename = g_strdup (argv[i]);
    } else {
      filename = g_build_filename (cwd, argv[i], NULL);
    }

    s_page_goto (pr_current, s_page_new (pr_current, filename));

    if (!f_open (pr_current, pr_current->page_current,
                 pr_current->page_current->page_filename, &err)) {
      /* Not being able to load a file is apparently a fatal error */
      logging_dest = STDOUT_TTY;
      g_warning ("%s\n", err->message);
      g_error_free (err);
      exit(2);
    } else {
      g_message ("Loaded file [%s]\n", filename);
    }

    i++;
    g_free (filename);
  }

  if (argv[argv_index] == NULL) {
    fprintf(stderr, "\nERROR! You must specify at least one filename\n\n");
    usage(argv[0]);
  }

  g_free(cwd);

  logging_dest=STDOUT_TTY;

#if DEBUG 
  s_page_print_all(pr_current);
#endif
  
  if (!quiet_mode) s_log_message("\n");

  if (embed_mode) {
    s_util_embed(pr_current, TRUE);
  }

  if (unembed_mode) {
    s_util_embed(pr_current, FALSE);
  }	

  /* save all the opened files */
  s_page_save_all(pr_current);

  s_page_delete_list (pr_current);
  gschlas_quit();

  exit(0);
}
Ejemplo n.º 24
0
int
main (int argc, char *argv[])
{
        char           *file;
        char           *uri;
        GdkPixbuf      *pixbuf;

        gtk_init (&argc, &argv);

        if (!notify_init ("Images Test"))
                exit (1);

        /* Stock icon */
        n = notify_notification_new ("Icon Test",
                                     "Testing stock icon",
                                     "appointment-new");

        if (!notify_notification_show (n, NULL)) {
                fprintf (stderr, "failed to send notification\n");
                return 1;
        }

        g_object_unref (G_OBJECT (n));

        file = g_get_current_dir ();
        uri = g_strdup_printf ("file://%s/%s",
                               file,
                               "dewdop_leaf.jpg");

        g_free (file);
        printf ("sending %s\n", uri);

        /* URIs */
        n = notify_notification_new ("Alert!",
                                     "Testing URI icons",
                                     uri);

        if (!notify_notification_show (n, NULL)) {
                fprintf (stderr, "failed to send notification\n");
                return 1;
        }

        g_object_unref (G_OBJECT (n));

        /* Raw image */
        n = notify_notification_new ("Raw image test",
                                     "Testing sending raw pixbufs",
                                     NULL);
        pixbuf = gtk_icon_theme_load_icon (gtk_icon_theme_get_for_screen (gdk_screen_get_default ()),
                                           "folder-open",
                                           48,
                                           GTK_ICON_LOOKUP_USE_BUILTIN,
                                           NULL);
        if (pixbuf == NULL) {
                fprintf (stderr, "failed to render pixbuf\n");
                return 1;
        }

        notify_notification_set_image_from_pixbuf (n, pixbuf);
        g_object_unref (pixbuf);

        if (!notify_notification_show (n, NULL)) {
                fprintf (stderr, "failed to send notification\n");
                return 1;
        }

        return 0;
}