예제 #1
0
static void
panel_place_menu_item_append_gtk_bookmarks (GtkWidget *menu, guint max_items_or_submenu)
{
	typedef struct {
		char *full_uri;
		char *label;
	} PanelBookmark;

	GtkWidget   *add_menu;
	char        *filename;
	GIOChannel  *io_channel;
	GHashTable  *table;
	int          i;
	GSList      *lines = NULL;
	GSList      *add_bookmarks, *l;
	PanelBookmark *bookmark;

	filename = g_build_filename (g_get_home_dir (),
				     BOOKMARKS_FILENAME, NULL);

	io_channel = g_io_channel_new_file (filename, "r", NULL);
	g_free (filename);

	if (!io_channel)
		return;

	/* We use a hard limit to avoid having users shooting their
	 * own feet, and to avoid crashing the system if a misbehaving
	 * application creates a big bookmarks file.
	 */
	for (i = 0; i < MAX_BOOKMARK_ITEMS; i++) {
		char      *contents;
		gsize      length;
		gsize      terminator_pos;
		GIOStatus  status;

		status = g_io_channel_read_line (io_channel, &contents, &length, &terminator_pos, NULL);

		if (status != G_IO_STATUS_NORMAL)
			break;

		if (length == 0)
			break;

		/* Clear the line terminator (\n), if any */
		if (terminator_pos > 0)
			contents[terminator_pos] = '\0';

		lines = g_slist_prepend (lines, contents);
	}

	g_io_channel_shutdown (io_channel, FALSE, NULL);
	g_io_channel_unref (io_channel);

	if (!lines)
		return;

	lines = g_slist_reverse (lines);

	table = g_hash_table_new (g_str_hash, g_str_equal);
	add_bookmarks = NULL;

	for (l = lines; l; l = l->next) {
		char *line = (char*) l->data;

		if (line[0] && !g_hash_table_lookup (table, line)) {
			GFile    *file;
			char     *space;
			char     *label;
			gboolean  keep;

			g_hash_table_insert (table, line, line);

			space = strchr (line, ' ');
			if (space) {
				*space = '\0';
				label = g_strdup (space + 1);
			} else {
				label = NULL;
			}

			keep = FALSE;

			if (g_str_has_prefix (line, "x-caja-search:"))
				keep = TRUE;

			if (!keep) {
				file = g_file_new_for_uri (line);
				keep = !g_file_is_native (file) ||
				       g_file_query_exists (file, NULL);
				g_object_unref (file);
			}

			if (!keep) {
				if (label)
					g_free (label);
				continue;
			}

			bookmark = g_malloc (sizeof (PanelBookmark));
			bookmark->full_uri = g_strdup (line);
			bookmark->label = label;
			add_bookmarks = g_slist_prepend (add_bookmarks, bookmark);
		}
	}

	g_hash_table_destroy (table);
	g_slist_foreach (lines, (GFunc) g_free, NULL);
	g_slist_free (lines);

	add_bookmarks = g_slist_reverse (add_bookmarks);

	if (g_slist_length (add_bookmarks) <= max_items_or_submenu) {
		add_menu = menu;
	} else {
		GtkWidget *item;

		item = gtk_image_menu_item_new ();
		setup_menuitem_with_icon (item, panel_menu_icon_get_size (),
					  NULL, PANEL_ICON_BOOKMARKS,
					  _("Bookmarks"));

		gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
		gtk_widget_show (item);

		add_menu = create_empty_menu ();
		gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), add_menu);
	}

	for (l = add_bookmarks; l; l = l->next) {
		char *display_name;
		char *tooltip;
		char *label;
		char *icon;
		GFile *file;
		GIcon *gicon;

		bookmark = l->data;

		file = g_file_new_for_uri (bookmark->full_uri);
		display_name = g_file_get_parse_name (file);
		g_object_unref (file);
		/* Translators: %s is a URI */
		tooltip = g_strdup_printf (_("Open '%s'"), display_name);
		g_free (display_name);

		label = NULL;
		if (bookmark->label) {
			label = g_strdup (g_strstrip (bookmark->label));
			if (!label [0]) {
				g_free (label);
				label = NULL;
			}
		}

		if (!label) {
			label = panel_util_get_label_for_uri (bookmark->full_uri);

			if (!label) {
				g_free (tooltip);
				g_free (bookmark->full_uri);
				if (bookmark->label)
					g_free (bookmark->label);
				g_free (bookmark);
				continue;
			}
		}

		icon = panel_util_get_icon_for_uri (bookmark->full_uri);
		/*FIXME: we should probably get a GIcon if possible, so that we
		 * have customized icons for cd-rom, eg */
		if (!icon)
			icon = g_strdup (PANEL_ICON_FOLDER);

		gicon = g_themed_icon_new_with_default_fallbacks (icon);

		//FIXME: drag and drop will be broken for x-caja-search uris
		panel_menu_items_append_place_item (icon, gicon,
						    label,
						    tooltip,
						    add_menu,
						    G_CALLBACK (activate_uri),
						    bookmark->full_uri);

		g_free (icon);
		g_object_unref (gicon);
		g_free (tooltip);
		g_free (label);
		g_free (bookmark->full_uri);
		if (bookmark->label)
			g_free (bookmark->label);
		g_free (bookmark);
	}

	g_slist_free (add_bookmarks);
}
예제 #2
0
static void
tp_roomlist_got_rooms_cb (TpChannel       *channel,
			  const GPtrArray *rooms,
			  gpointer         user_data,
			  GObject         *list)
{
	EmpathyTpRoomlistPriv *priv = GET_PRIV (list);
	EmpathyChatroom       *chatroom;
	guint                  i;
	GArray                *handles = NULL;
	GSList                *chatrooms = NULL;

	for (i = 0; i < rooms->len; i++) {
		const GValue *room_name_value;
		const GValue *handle_name_value;
		GValueArray  *room_struct;
		guint         handle;
		const gchar  *channel_type;
		GHashTable   *info;

		/* Get information */
		room_struct = g_ptr_array_index (rooms, i);
		handle = g_value_get_uint (g_value_array_get_nth (room_struct, 0));
		channel_type = g_value_get_string (g_value_array_get_nth (room_struct, 1));
		info = g_value_get_boxed (g_value_array_get_nth (room_struct, 2));
		room_name_value = g_hash_table_lookup (info, "name");
		handle_name_value = g_hash_table_lookup (info, "handle-name");

		if (tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TEXT)) {
			continue;
		}

		chatroom = empathy_chatroom_new (priv->account);

		if (room_name_value != NULL) {
			empathy_chatroom_set_name (chatroom,
						   g_value_get_string (room_name_value));
		}

		if (handle_name_value != NULL) {
			empathy_chatroom_set_room (chatroom,
						   g_value_get_string (handle_name_value));

			/* We have the room ID, we can directly emit it */
			g_signal_emit (list, signals[NEW_ROOM], 0, chatroom);
			g_object_unref (chatroom);
		} else {
			/* We don't have the room ID, we'll inspect all handles
			 * at once and then emit rooms */
			if (handles == NULL) {
				handles = g_array_new (FALSE, FALSE, sizeof (guint));
			}

			g_array_append_val (handles, handle);
			chatrooms = g_slist_prepend (chatrooms, chatroom);
		}
	}

	if (handles != NULL) {
		chatrooms = g_slist_reverse (chatrooms);
		tp_cli_connection_call_inspect_handles (priv->connection, -1,
						       TP_HANDLE_TYPE_ROOM,
						       handles,
						       tp_roomlist_inspect_handles_cb,
						       chatrooms,
						       tp_roomlist_chatrooms_free,
						       list);
		g_array_free (handles, TRUE);
	}
}
예제 #3
0
GSList *get_facet_equiv(struct model_pak *data, gint *f1)
{
gint i, flag, *f2, index[3];
gdouble d1, d2, vec[3];
GSList *flist=NULL, *list=NULL;

g_return_val_if_fail(data != NULL, NULL);
g_return_val_if_fail(f1 != NULL, NULL);

/* NEW */
ARR3SET(vec, f1);
vecmat(data->rlatmat, vec);
d1 = 1.0/VEC3MAG(vec);

#if DEBUG_GET_FACET_EQUIV
printf("search for equiv faces to (%d %d %d) (Dhkl = %f)\n",
        f1[0], f1[1], f1[2], d1);
#endif

/* add the supplied face to the list (needed to eliminate repetitions) */
f2 = g_malloc(3*sizeof(gint));
ARR3SET(f2, f1);
flist = g_slist_prepend(flist, (gpointer) f2);

if (data->sginfo.spacenum)
  {
/* skip 1st (trivial) op */
  for (i=1 ; i<data->sginfo.order ; i++)
    {
/* generate new symmetry related hkl */
    ARR3SET(vec, f1);
    vecmat(*(data->sginfo.matrix+i), vec);
    ARR3SET(index, vec);

/* NEW - weed out symop generated faces with different Dhkl values */
/* FIXME - why does this happen??? */
vecmat(data->rlatmat, vec);
d2 = 1.0/VEC3MAG(vec);

#if DEBUG_GET_FACET_EQUIV
printf("candidate: (%3d %3d %3d) : (Dhkl=%7.4f)", index[0], index[1], index[2], d2);
#endif

if (fabs(d2-d1) > FRACTION_TOLERANCE)
  {
#if DEBUG_GET_FACET_EQUIV
printf("[NO : dhkl mis-match]\n");
#endif
  continue;
  }

/* add new hkl if not found in the list */
    flag = 0;
    list = flist;
    while (list != NULL)
      {
      f2 = (gint *) list->data;
      if (index[0] == f2[0] && index[1] == f2[1] && index[2] == f2[2])
        {
        flag++;
        break;
        }
      list = g_slist_next(list);
      }
    if (!flag)
      {
      f2 = g_malloc(3*sizeof(gint));
      ARR3SET(f2, index);
      flist = g_slist_prepend(flist, f2);

#if DEBUG_GET_FACET_EQUIV
printf("[YES : symop %d]\n", i);
#endif
      }
#if DEBUG_GET_FACET_EQUIV
    else
      {
printf("[NO : already exists]\n");
      }
#endif
    }
  }
else
  printf("No space group information.\n");

flist = g_slist_reverse(flist);
return(flist);
}
예제 #4
0
int
main (int   argc,
      char *argv[])
{
  const gchar *gobject_marshallers[] = {
#include	"gmarshal.strings"
  };
  GScanner *scanner;
  GSList *slist, *files = NULL;
  gint i;
  gint result = 0;

  /* parse args and do fast exits */
  parse_args (&argc, &argv);

  /* list input files */
  for (i = 1; i < argc; i++)
    files = g_slist_prepend (files, argv[i]);
  if (files)
    files = g_slist_reverse (files);
  else
    files = g_slist_prepend (files, "/dev/stdin");

  /* setup auxillary structs */
  scanner = g_scanner_new (&scanner_config_template);
  fout = stdout;
  marshallers = g_hash_table_new (g_str_hash, g_str_equal);

  /* add standard marshallers of the GObject library */
  if (std_includes)
    for (i = 0; i < G_N_ELEMENTS (gobject_marshallers); i++)
      {
	gchar *tmp = g_strdup (gobject_marshallers[i]);
	
	g_hash_table_insert (marshallers, tmp, tmp);
      }

  /* put out initial heading */
  g_fprintf (fout, "\n");

  if (gen_cheader && std_includes)
    {
      g_fprintf (fout, "#ifndef __%s_MARSHAL_H__\n", marshaller_prefix);
      g_fprintf (fout, "#define __%s_MARSHAL_H__\n\n", marshaller_prefix);
    }

  if ((gen_cheader || gen_cbody) && std_includes)
    g_fprintf (fout, "#include\t<glib-object.h>\n\n");

  if (gen_cheader)
    g_fprintf (fout, "G_BEGIN_DECLS\n");

  /* generate necessary preprocessor directives */
  if (gen_cbody)
    put_marshal_value_getters ();

  /* process input files */
  for (slist = files; slist; slist = slist->next)
    {
      gchar *file = slist->data;
      gint fd = open (file, O_RDONLY);

      if (fd < 0)
	{
	  g_warning ("failed to open \"%s\": %s", file, g_strerror (errno));
	  result = 1;
	  continue;
	}

      /* set file name for error reports */
      scanner->input_name = file;

      /* parse & process file */
      g_scanner_input_file (scanner, fd);
      
      /* scanning loop, we parse the input untill it's end is reached,
       * or our sub routine came across invalid syntax
       */
      do
	{
	  guint expected_token = G_TOKEN_NONE;

	  switch (g_scanner_peek_next_token (scanner))
	    {
	    case '\n':
	      /* eat newline and restart */
	      g_scanner_get_next_token (scanner);
	      continue;
	    case G_TOKEN_EOF:
	      /* done */
	      break;
	    default:
	      /* parse and process signatures */
	      {
		Signature signature = { NULL, NULL, NULL };
		GList *node;

		expected_token = parse_line (scanner, &signature);
		
		/* once we got a valid signature, process it */
		if (expected_token == G_TOKEN_NONE)
		  process_signature (&signature);
		
		/* clean up signature contents */
		g_free (signature.ploc);
		if (signature.rarg)
		  g_free (signature.rarg->keyword);
		g_free (signature.rarg);
		for (node = signature.args; node; node = node->next)
		  {
		    InArgument *iarg = node->data;
		    
		    g_free (iarg->keyword);
		    g_free (iarg);
		  }
		g_list_free (signature.args);
	      }
	      break;
	    }

	  /* bail out on errors */
	  if (expected_token != G_TOKEN_NONE)
	    {
	      g_scanner_unexp_token (scanner, expected_token, "type name", NULL, NULL, NULL, TRUE);
	      result = 1;
	      break;
	    }

	  g_scanner_peek_next_token (scanner);
	}
      while (scanner->next_token != G_TOKEN_EOF);

      close (fd);
    }

  /* put out trailer */
  if (gen_cheader)
    {
      g_fprintf (fout, "\nG_END_DECLS\n");

      if (std_includes)
	g_fprintf (fout, "\n#endif /* __%s_MARSHAL_H__ */\n", marshaller_prefix);
    }
  g_fprintf (fout, "\n");

  /* clean up */
  g_slist_free (files);
  g_scanner_destroy (scanner);
  g_hash_table_foreach_remove (marshallers, string_key_destroy, NULL);
  g_hash_table_destroy (marshallers);

  return result;
}
예제 #5
0
/** \brief Create polylines. */
static void
create_polylines (GtkSatMap *satmap, sat_t *sat, qth_t *qth, sat_map_obj_t *obj)
{
     ssp_t              *ssp,*buff;     /* map coordinates */
     double             lastx,lasty;
     GSList             *points = NULL;
     GooCanvasItemModel *root;
     GooCanvasItemModel *line;
     GooCanvasPoints    *gpoints;
     guint              start;
     guint              i,j,n,num_points;
     guint32            col;

     (void) sat; /* prevent unused parameter compiler warning */
     (void) qth; /* prevent unused parameter compiler warning */

     /* initialise parameters */
     lastx = -50.0;
     lasty = -50.0;
     start = 0;
     num_points = 0;
     n = g_slist_length (obj->track_data.latlon);
     col = mod_cfg_get_int (satmap->cfgdata,
                                 MOD_CFG_MAP_SECTION,
                                 MOD_CFG_MAP_TRACK_COL,
                                 SAT_CFG_INT_MAP_TRACK_COL);

     /* loop over each SSP */
     for (i = 0; i < n; i++) {

          buff = (ssp_t *) g_slist_nth_data (obj->track_data.latlon, i);
          ssp = g_try_new (ssp_t, 1);
          gtk_sat_map_lonlat_to_xy (satmap, buff->lon, buff->lat, &ssp->lon, &ssp->lat);

          /* if this is the first point, just add it to the list */
          if (i == start) {
               points = g_slist_prepend (points, ssp);
               lastx = ssp->lon;
               lasty = ssp->lat;
          }

          else {

               /* if SSP is on the other side of the map */
               if (ssp_wrap_detected (satmap, lastx, ssp->lon)) {

                    points = g_slist_reverse (points);
                    num_points = g_slist_length (points);

                    /* we need at least 2 points to draw a line */
                    if (num_points > 1) {

                         /* convert SSPs to GooCanvasPoints */
                         gpoints = goo_canvas_points_new (num_points);
                         for (j = 0; j < num_points; j++) {
                              buff = (ssp_t *) g_slist_nth_data (points, j);
                              gpoints->coords[2*j] = buff->lon;
                              gpoints->coords[2*j+1] = buff->lat;
                         }

                         /* create a new polyline using the current set of points */
                         root = goo_canvas_get_root_item_model (GOO_CANVAS (satmap->canvas));

                         line = goo_canvas_polyline_model_new (root, FALSE, 0,
                                                                        "points", gpoints,
                                                                        "line-width", 1.0,
                                                                        "stroke-color-rgba", col,
                                                                        "line-cap", CAIRO_LINE_CAP_SQUARE,
                                                                        "line-join", CAIRO_LINE_JOIN_MITER,
                                                                        NULL);
                         goo_canvas_points_unref (gpoints);
                         goo_canvas_item_model_lower (line, obj->marker);
                         
                         /* store line in sat object */
                         obj->track_data.lines = g_slist_append (obj->track_data.lines, line);

                    }

                    /* reset parameters and continue with a new set */
                    g_slist_foreach (points, free_ssp, NULL);
                    g_slist_free (points);
                    points = NULL;
                    start = i;
                    lastx = ssp->lon;
                    lasty = ssp->lat;
                    num_points = 0;

                    /* Add current SSP to the new list */
                    points = g_slist_prepend (points, ssp);
                    lastx = ssp->lon;
                    lasty = ssp->lat;

               }

               /* else if this SSP is separable from the previous */
               else if ((fabs (lastx - ssp->lon) > 1.0 ) || (fabs(lasty - ssp->lat)>1.0)){

                    /* add SSP to list */
                    points = g_slist_prepend (points, ssp);
                    lastx = ssp->lon;
                    lasty = ssp->lon;

               }

               /* else if  do nothing */

          }
     }

     /* create (last) line if we have at least two points */
     points = g_slist_reverse (points);
     num_points = g_slist_length (points);

     if (num_points > 1) {

          /* convert SSPs to GooCanvasPoints */
          gpoints = goo_canvas_points_new (num_points);
          for (j = 0; j < num_points; j++) {
               buff = (ssp_t *) g_slist_nth_data (points, j);
               gpoints->coords[2*j] = buff->lon;
               gpoints->coords[2*j+1] = buff->lat;
          }

          /* create a new polyline using the current set of points */
          root = goo_canvas_get_root_item_model (GOO_CANVAS (satmap->canvas));

          line = goo_canvas_polyline_model_new (root, FALSE, 0,
                                                         "points", gpoints,
                                                         "line-width", 1.0,
                                                         "stroke-color-rgba", col,
                                                         "line-cap", CAIRO_LINE_CAP_SQUARE,
                                                         "line-join", CAIRO_LINE_JOIN_MITER,
                                                         NULL);
          goo_canvas_points_unref (gpoints);
          goo_canvas_item_model_lower (line, obj->marker);

          /* store line in sat object */
          obj->track_data.lines = g_slist_append (obj->track_data.lines, line);

          /* reset parameters and continue with a new set */
          g_slist_foreach (points, free_ssp, NULL);
          g_slist_free (points);

     }
}
예제 #6
0
static void plugin_init(PurplePlugin *plugin) {
    PurpleAccountUserSplit *split;
    PurpleAccountOption *option;
    
    split = purple_account_user_split_new("Character", "", ':');
    prpl_info.user_splits = g_list_append(prpl_info.user_splits, split);

/*    option = purple_account_option_bool_new("Sync Status", "sync_status", TRUE);
    prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);

    option = purple_account_option_bool_new("Sync Status Message", "sync_status_message", TRUE);
    prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);*/
    
    option = purple_account_option_string_new("Server Address", "server_address", "chat.f-list.net");
    prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);

    option = purple_account_option_int_new("Server Port", "server_port", FLIST_PORT);
    prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);
    
    option = purple_account_option_bool_new("Download Friends List", "sync_friends", TRUE);
    prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);

    option = purple_account_option_bool_new("Download Bookmarks", "sync_bookmarks", FALSE);
    prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);
    
    option = purple_account_option_bool_new("Debug Mode", "debug_mode", FALSE);
    prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);

    gender_list = NULL;
    gender_list = g_slist_prepend(gender_list, "Male");
    gender_list = g_slist_prepend(gender_list, "Female");
    gender_list = g_slist_prepend(gender_list, "Transgender");
    gender_list = g_slist_prepend(gender_list, "Herm");
    gender_list = g_slist_prepend(gender_list, "Shemale");
    gender_list = g_slist_prepend(gender_list, "Male-Herm");
    gender_list = g_slist_prepend(gender_list, "C**t-boy");
    gender_list = g_slist_prepend(gender_list, "None");
    gender_list = g_slist_reverse(gender_list);
    
    str_to_channel_mode = g_hash_table_new(g_str_hash, g_str_equal);
    g_hash_table_insert(str_to_channel_mode, "both", GINT_TO_POINTER(CHANNEL_MODE_BOTH));
    g_hash_table_insert(str_to_channel_mode, "ads", GINT_TO_POINTER(CHANNEL_MODE_ADS_ONLY));
    g_hash_table_insert(str_to_channel_mode, "chat", GINT_TO_POINTER(CHANNEL_MODE_CHAT_ONLY));
    
    str_to_gender = g_hash_table_new(g_str_hash, g_str_equal);
    g_hash_table_insert(str_to_gender, "Male", GINT_TO_POINTER(FLIST_GENDER_MALE));
    g_hash_table_insert(str_to_gender, "Female", GINT_TO_POINTER(FLIST_GENDER_FEMALE));
    g_hash_table_insert(str_to_gender, "Transgender", GINT_TO_POINTER(FLIST_GENDER_TRANSGENDER));
    g_hash_table_insert(str_to_gender, "Herm", GINT_TO_POINTER(FLIST_GENDER_HERM));
    g_hash_table_insert(str_to_gender, "Shemale", GINT_TO_POINTER(FLIST_GENDER_SHEMALE));
    g_hash_table_insert(str_to_gender, "Male-Herm", GINT_TO_POINTER(FLIST_GENDER_MALEHERM));
    g_hash_table_insert(str_to_gender, "C**t-boy", GINT_TO_POINTER(FLIST_GENDER_CUNTBOY));
    g_hash_table_insert(str_to_gender, "None", GINT_TO_POINTER(FLIST_GENDER_NONE));

    gender_to_proper_str = g_hash_table_new(g_direct_hash, NULL);
    g_hash_table_insert(gender_to_proper_str, GINT_TO_POINTER(FLIST_GENDER_MALE), "Male");
    g_hash_table_insert(gender_to_proper_str, GINT_TO_POINTER(FLIST_GENDER_FEMALE), "Female");
    g_hash_table_insert(gender_to_proper_str, GINT_TO_POINTER(FLIST_GENDER_TRANSGENDER), "Transgender");
    g_hash_table_insert(gender_to_proper_str, GINT_TO_POINTER(FLIST_GENDER_HERM), "Herm");
    g_hash_table_insert(gender_to_proper_str, GINT_TO_POINTER(FLIST_GENDER_SHEMALE), "Shemale");
    g_hash_table_insert(gender_to_proper_str, GINT_TO_POINTER(FLIST_GENDER_MALEHERM), "Male-Herm");
    g_hash_table_insert(gender_to_proper_str, GINT_TO_POINTER(FLIST_GENDER_CUNTBOY), "C**t-boy");
    g_hash_table_insert(gender_to_proper_str, GINT_TO_POINTER(FLIST_GENDER_NONE), "None");
    
    status_list = NULL;
    status_list = g_slist_prepend(status_list, "online");
    status_list = g_slist_prepend(status_list, "looking");
    status_list = g_slist_prepend(status_list, "away");
    status_list = g_slist_prepend(status_list, "busy");
    status_list = g_slist_prepend(status_list, "dnd");
    status_list = g_slist_reverse(status_list);

    str_to_status = g_hash_table_new(g_str_hash, g_str_equal);
    g_hash_table_insert(str_to_status, "online", GINT_TO_POINTER(FLIST_STATUS_AVAILABLE));
    g_hash_table_insert(str_to_status, "looking", GINT_TO_POINTER(FLIST_STATUS_LOOKING));
    g_hash_table_insert(str_to_status, "busy", GINT_TO_POINTER(FLIST_STATUS_BUSY));
    g_hash_table_insert(str_to_status, "dnd", GINT_TO_POINTER(FLIST_STATUS_DND));
    g_hash_table_insert(str_to_status, "crown", GINT_TO_POINTER(FLIST_STATUS_CROWN));
    g_hash_table_insert(str_to_status, "idle", GINT_TO_POINTER(FLIST_STATUS_IDLE));
    g_hash_table_insert(str_to_status, "away", GINT_TO_POINTER(FLIST_STATUS_AWAY));
    g_hash_table_insert(str_to_status, "unknown", GINT_TO_POINTER(FLIST_STATUS_UNKNOWN));

    status_to_str = g_hash_table_new(g_direct_hash, NULL);
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_AVAILABLE), "online");
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_LOOKING), "looking");
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_BUSY), "busy");
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_DND), "dnd");
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_CROWN), "crown");
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_AWAY), "away");
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_IDLE), "idle");
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_OFFLINE), "offline");
    g_hash_table_insert(status_to_str, GINT_TO_POINTER(FLIST_STATUS_UNKNOWN), "unknown");

    status_to_proper_str = g_hash_table_new(g_direct_hash, NULL);
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_AVAILABLE), "Available");
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_LOOKING), "Looking");
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_BUSY), "Busy");
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_DND), "Do Not Disturb");
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_CROWN), "Crown");
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_AWAY), "Away");
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_IDLE), "Idle");
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_OFFLINE), "Offline");
    g_hash_table_insert(status_to_proper_str, GINT_TO_POINTER(FLIST_STATUS_UNKNOWN), "Unknown");

    friend_status_to_proper_str = g_hash_table_new(g_direct_hash, NULL);
    g_hash_table_insert(friend_status_to_proper_str, GINT_TO_POINTER(FLIST_NOT_FRIEND), "No");
    g_hash_table_insert(friend_status_to_proper_str, GINT_TO_POINTER(FLIST_MUTUAL_FRIEND), "Mutual");
    g_hash_table_insert(friend_status_to_proper_str, GINT_TO_POINTER(FLIST_PENDING_IN_FRIEND), "Pending (You)");
    g_hash_table_insert(friend_status_to_proper_str, GINT_TO_POINTER(FLIST_PENDING_OUT_FRIEND), "Pending (Buddy)");

    string_to_account = g_hash_table_new((GHashFunc) flist_str_hash, (GEqualFunc) flist_str_equal);
    account_to_string = g_hash_table_new((GHashFunc) flist_str_hash, (GEqualFunc) flist_str_equal);

    flist_callback_init();
    flist_init_commands();
    flist_bbcode_init();
    flist_web_requests_init();
    flist_ticket_init();
}
예제 #7
0
static gpointer
brasero_burn_uri_thread (gpointer data)
{
	BraseroBurnURI *self = BRASERO_BURN_URI (data);
	BraseroTrack *current = NULL;
	BraseroBurnURIPrivate *priv;
	BraseroTrackData *track;
	GSList *excluded = NULL;
	GSList *grafts = NULL;
	guint64 num = 0;
	GSList *src;

	priv = BRASERO_BURN_URI_PRIVATE (self);
	brasero_job_set_current_action (BRASERO_JOB (self),
					BRASERO_BURN_ACTION_FILE_COPY,
					_("Copying files locally"),
					TRUE);

	brasero_job_get_current_track (BRASERO_JOB (self), &current);

	/* This is for IMAGE tracks */
	if (BRASERO_IS_TRACK_IMAGE (current)) {
		gchar *uri;
		gchar *path_toc;
		gchar *path_image;
		goffset blocks = 0;
		BraseroTrackImage *image;

		path_image = NULL;
		uri = brasero_track_image_get_source (BRASERO_TRACK_IMAGE (current), TRUE);
		if (!brasero_burn_uri_retrieve_path (self, uri, &path_image)) {
			g_free (uri);
			goto end;
		}
		g_free (uri);

		path_toc = NULL;
		uri = brasero_track_image_get_toc_source (BRASERO_TRACK_IMAGE (current), TRUE);
		if (uri) {
			/* NOTE: if it's a .bin image there is not .toc file */
			if (!brasero_burn_uri_retrieve_path (self, uri, &path_toc)) {
				g_free (path_image);
				g_free (uri);
				goto end;
			}
			g_free (uri);
		}

		brasero_track_get_size (current, &blocks, NULL);

		image = brasero_track_image_new ();
		brasero_track_tag_copy_missing (BRASERO_TRACK (image), current);
		brasero_track_image_set_source (image,
						path_image,
						path_toc,
						brasero_track_image_get_format (BRASERO_TRACK_IMAGE (current)));
		brasero_track_image_set_block_num (image, blocks);

		priv->track = BRASERO_TRACK (image);

		g_free (path_toc);
		g_free (path_image);
		goto end;
	}

	/* This is for DATA tracks */
	for (src = brasero_track_data_get_grafts (BRASERO_TRACK_DATA (current)); src; src = src->next) {
		GFile *file;
		GFileInfo *info;
		BraseroGraftPt *graft;

		graft = src->data;

		if (!graft->uri) {
			grafts = g_slist_prepend (grafts, brasero_graft_point_copy (graft));
			continue;
		}

		if (!g_str_has_prefix (graft->uri, "burn://")) {
			grafts = g_slist_prepend (grafts, brasero_graft_point_copy (graft));
			continue;
		}

		BRASERO_JOB_LOG (self, "Information retrieval for %s", graft->uri);

		file = g_file_new_for_uri (graft->uri);
		info = g_file_query_info (file,
					  G_FILE_ATTRIBUTE_STANDARD_NAME ","
					  G_FILE_ATTRIBUTE_STANDARD_TYPE ","
					  "burn::backing-file",
					  G_FILE_QUERY_INFO_NONE,
					  priv->cancel,
					  &priv->error);

		if (priv->error) {
			g_object_unref (file);
			goto end;
		}

		if (g_cancellable_is_cancelled (priv->cancel)) {
			g_object_unref (file);
			goto end;
		}

		if (!info) {
			/* Error */
			g_object_unref (file);
			g_object_unref (info);
			goto end;
		}

		/* See if we were passed the burn:/// uri itself (the root).
		 * Then skip graft point addition */
		if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY) {
			if (g_file_info_get_name (info)
			&&  strcmp (g_file_info_get_name (info), "/")) {
				BraseroGraftPt *newgraft;

				/* we need a dummy directory */
				newgraft = g_new0 (BraseroGraftPt, 1);
				newgraft->uri = NULL;
				newgraft->path = g_strdup (graft->path);
				grafts = g_slist_prepend (grafts, newgraft);

				BRASERO_JOB_LOG (self,
						 "Adding directory %s at %s",
						 newgraft->uri,
						 newgraft->path);
				grafts = brasero_burn_uri_explore_directory (self,
									     grafts,
									     file,
									     newgraft->path,
									     priv->cancel,
									     &priv->error);
			}
			else {
				BRASERO_JOB_LOG (self, "Directory is root");
				grafts = brasero_burn_uri_explore_directory (self,
									     grafts,
									     file,
									     "/",
									     priv->cancel,
									     &priv->error);
			}

			if (!grafts) {
				g_object_unref (info);
				g_object_unref (file);
				goto end;
			}
		}
		else if (g_file_info_get_file_type (info) == G_FILE_TYPE_REGULAR
		     /* NOTE: burn:// URI allows symlink */
		     ||  g_file_info_get_file_type (info) == G_FILE_TYPE_SYMBOLIC_LINK) {
			const gchar *real_path;
			BraseroGraftPt *newgraft;

			real_path = g_file_info_get_attribute_byte_string (info, "burn::backing-file");
			if (!real_path) {
				priv->error = g_error_new (BRASERO_BURN_ERROR,
							   BRASERO_BURN_ERROR_GENERAL,
							   _("Impossible to retrieve local file path"));

				g_slist_foreach (grafts, (GFunc) brasero_graft_point_free, NULL);
				g_slist_free (grafts);
				g_object_unref (info);
				g_object_unref (file);
				goto end;
			}

			newgraft = brasero_graft_point_copy (graft);
			g_free (newgraft->uri);

			newgraft->uri = g_strdup (real_path);
			/* FIXME: maybe one day, graft->uri will always be an URI */
			/* newgraft->uri = g_filename_to_uri (real_path, NULL, NULL); */

			BRASERO_JOB_LOG (self,
					 "Added file %s at %s",
					 newgraft->uri,
					 newgraft->path);
			grafts = g_slist_prepend (grafts, newgraft);
		}

		g_object_unref (info);
		g_object_unref (file);
	}
	grafts = g_slist_reverse (grafts);

	/* remove all excluded starting by burn:// from the list */
	for (src = brasero_track_data_get_excluded_list (BRASERO_TRACK_DATA (current)); src; src = src->next) {
		gchar *uri;

		uri = src->data;

		if (uri && g_str_has_prefix (uri, "burn://"))
			continue;

		uri = g_strdup (uri);
		excluded = g_slist_prepend (excluded, uri);

		BRASERO_JOB_LOG (self, "Added excluded file %s", uri);
	}
	excluded = g_slist_reverse (excluded);

	track = brasero_track_data_new ();
	brasero_track_tag_copy_missing (BRASERO_TRACK (track), current);
	
	brasero_track_data_add_fs (track, brasero_track_data_get_fs (BRASERO_TRACK_DATA (current)));

	brasero_track_data_get_file_num (BRASERO_TRACK_DATA (current), &num);
	brasero_track_data_set_file_num (track, num);

	brasero_track_data_set_source (track,
				       grafts,
				       excluded);
	priv->track = BRASERO_TRACK (track);

end:

	if (!g_cancellable_is_cancelled (priv->cancel))
		priv->thread_id = g_idle_add ((GSourceFunc) brasero_burn_uri_thread_finished, self);

	/* End thread */
	g_mutex_lock (priv->mutex);
	g_atomic_pointer_set (&priv->thread, NULL);
	g_cond_signal (priv->cond);
	g_mutex_unlock (priv->mutex);

	g_thread_exit (NULL);

	return NULL;
}
예제 #8
0
파일: file_diff.c 프로젝트: Bhattiasif/gdis
gint read_diffax(gchar *filename, struct model_pak *model)
{
gint num_tokens, num_layer, tot_layer;
gdouble offset;
gchar **buff;
GSList *list1, *list2;
struct core_pak *core;
struct layer_pak *layer;
FILE *fp;

/* checks */
g_return_val_if_fail(model != NULL, 1);
g_return_val_if_fail(filename != NULL, 2);
fp = fopen(filename, "rt");
if (!fp)
  return(3);

/* setup */
model->id = DIFFAX_INP;
model->fractional = TRUE;
model->periodic = 3;
model->colour_scheme = REGION;

strcpy(model->filename, filename);
g_free(model->basename);
model->basename = parse_strip(filename);

/* scan the file */
while ((buff = get_tokenized_line(fp, &num_tokens)))
  {
  diffax_keyword_search:;

/* restricted unit cell */
  if (g_ascii_strncasecmp("structural", *buff, 10) == 0)
    {
    g_strfreev(buff);
    buff = get_tokenized_line(fp, &num_tokens);
    if (num_tokens > 3)
      {
      model->pbc[0] = str_to_float(*(buff+0));
      model->pbc[1] = str_to_float(*(buff+1));
      model->pbc[2] = str_to_float(*(buff+2));
      model->pbc[3] = PI/2.0;
      model->pbc[4] = PI/2.0;
      model->pbc[5] = D2R*str_to_float(*(buff+3));
      }
    }

/* layer testing */
  if (g_ascii_strncasecmp("layer", *buff, 5) == 0)
    {
    layer = g_malloc(sizeof(struct model_pak));
    layer->width = 1.0;
    VEC3SET(layer->centroid, 0.5, 0.5, 0.5);
    layer->cores = NULL;
    model->layer_list = g_slist_prepend(model->layer_list, layer);

    g_strfreev(buff);
    buff = get_tokenized_line(fp, &num_tokens);
    if (buff)
      {
/* TODO - if centrosymmetric : add a -1 operation */
      }

/* get layer data */
    g_strfreev(buff);
    buff = get_tokenized_line(fp, &num_tokens);
    while (buff)
      {
      if (elem_symbol_test(*buff))
        {
        if (num_tokens > 6)
          {
/*
printf("[%s] [%s  %s  %s]\n", *buff, *(buff+2), *(buff+3), *(buff+4));
*/
          core = new_core(*buff, model);
          model->cores = g_slist_prepend(model->cores, core);
          layer->cores = g_slist_prepend(layer->cores, core);

          core->x[0] = str_to_float(*(buff+2));
          core->x[1] = str_to_float(*(buff+3));
          core->x[2] = str_to_float(*(buff+4));

          core->sof = str_to_float(*(buff+5));
          }
        }
      else
        goto diffax_keyword_search;

/* get next line of tokens */
      g_strfreev(buff);
      buff = get_tokenized_line(fp, &num_tokens);
      }
    }

  g_strfreev(buff);
  }

/* TODO - enumerate layers and scale, so they are stacked 1..n in a single cell */
/* also label the layers as different region types */
model->layer_list = g_slist_reverse(model->layer_list);
num_layer = 0;
tot_layer = g_slist_length(model->layer_list);

model->pbc[2] *= tot_layer;

#if DEBUG_READ_DIFFAX
printf("Read in %d layers.\n", tot_layer);
#endif

for (list1=model->layer_list ; list1 ; list1=g_slist_next(list1))
  {
  layer = (struct layer_pak *) list1->data;
  layer->width = 1.0 / (gdouble) tot_layer;

  offset = (gdouble) num_layer * layer->width;

  VEC3SET(layer->centroid, 0.0, 0.0, offset);

  for (list2=layer->cores ; list2 ; list2=g_slist_next(list2))
    {
    core = (struct core_pak *) list2->data;

/* scale to within the big cell (encloses all DIFFAX layers) */
    core->x[2] *= layer->width;

/* offset each particular layer */
    core->x[2] += offset;

    core->region = num_layer;
    }
  num_layer++;
  }

/* end of read */
fclose(fp);

/* post read setup */
model->cores = g_slist_reverse(model->cores);
model_prep(model);

return(0);
}
예제 #9
0
파일: session.c 프로젝트: igaw/connman
static void session_activate(struct connman_session *session)
{
	GHashTableIter iter;
	gpointer key, value;

	if (!service_hash)
		return;

	if (policy && policy->get_service_for_session) {
		struct connman_service *service;
		struct connman_service_info *info;
		GSList *service_list = NULL;
		enum connman_service_state state = CONNMAN_SESSION_STATE_DISCONNECTED;

		g_hash_table_iter_init(&iter, service_hash);

		while (g_hash_table_iter_next(&iter, &key, &value)) {
			struct connman_service_info *info = value;
			state = connman_service_get_state(info->service);

			if (is_session_connected(session, state))
				service_list = g_slist_prepend(service_list,
							       info->service);
		}

		service_list = g_slist_reverse(service_list);
		service = policy->get_service_for_session(session, service_list);

		if (service) {
			info = g_hash_table_lookup(service_hash, service);
			DBG("session %p add service %p", session, info->service);

			info->sessions = g_slist_prepend(info->sessions,
							session);
			session->service = info->service;
			update_session_state(session);
		}

		g_slist_free(service_list);
		return;
	}

	g_hash_table_iter_init(&iter, service_hash);
	while (g_hash_table_iter_next(&iter, &key, &value)) {
		struct connman_service_info *info = value;
		enum connman_service_state state;

		state = connman_service_get_state(info->service);

		if (is_session_connected(session, state) &&
				session_match_service(session, info->service)) {
			DBG("session %p add service %p", session, info->service);

			info->sessions = g_slist_prepend(info->sessions,
							session);
			session->service = info->service;
			update_session_state(session);

			return;
		}
	}

	session_notify(session);
}
예제 #10
0
GtkWidget *
gr_vector_list (SPDesktop *desktop, bool selection_empty, SPGradient *gr_selected, bool gr_multi)
{
    SPDocument *document = sp_desktop_document (desktop);

    GtkWidget *om = gtk_option_menu_new ();
    GtkWidget *m = gtk_menu_new ();

    GSList *gl = NULL;
    const GSList *gradients = sp_document_get_resource_list (document, "gradient");
    for (const GSList *i = gradients; i != NULL; i = i->next) {
        if (SP_GRADIENT_HAS_STOPS (i->data)) {
            gl = g_slist_prepend (gl, i->data);
        }
    }
    gl = g_slist_reverse (gl);

    guint pos = 0;
    guint idx = 0;

    if (!gl) {
        GtkWidget *l = gtk_label_new("");
        gtk_label_set_markup (GTK_LABEL(l), _("<small>No gradients</small>"));
        GtkWidget *i = gtk_menu_item_new ();
        gtk_container_add (GTK_CONTAINER (i), l);

        gtk_widget_show (i);
        gtk_menu_append (GTK_MENU (m), i);
        gtk_widget_set_sensitive (om, FALSE);
    } else if (selection_empty) {
        GtkWidget *l = gtk_label_new("");
        gtk_label_set_markup (GTK_LABEL(l), _("<small>Nothing selected</small>"));
        GtkWidget *i = gtk_menu_item_new ();
        gtk_container_add (GTK_CONTAINER (i), l);

        gtk_widget_show (i);
        gtk_menu_append (GTK_MENU (m), i);
        gtk_widget_set_sensitive (om, FALSE);
    } else {

        if (gr_selected == NULL) {
            GtkWidget *l = gtk_label_new("");
            gtk_label_set_markup (GTK_LABEL(l), _("<small>No gradients in selection</small>"));
            GtkWidget *i = gtk_menu_item_new ();
            gtk_container_add (GTK_CONTAINER (i), l);

            gtk_widget_show (i);
            gtk_menu_append (GTK_MENU (m), i);
        }

        if (gr_multi) {
            GtkWidget *l = gtk_label_new("");
            gtk_label_set_markup (GTK_LABEL(l), _("<small>Multiple gradients</small>"));
            GtkWidget *i = gtk_menu_item_new ();
            gtk_container_add (GTK_CONTAINER (i), l);

            gtk_widget_show (i);
            gtk_menu_append (GTK_MENU (m), i);
        }

        while (gl) {
            SPGradient *gradient = SP_GRADIENT (gl->data);
            gl = g_slist_remove (gl, gradient);

            GtkWidget *i = gtk_menu_item_new ();
            g_object_set_data (G_OBJECT (i), "gradient", gradient);
            g_signal_connect (G_OBJECT (i), "activate", G_CALLBACK (gr_item_activate), desktop);

            GtkWidget *image = sp_gradient_image_new (gradient);

            GtkWidget *hb = gtk_hbox_new (FALSE, 4);
            GtkWidget *l = gtk_label_new ("");
            gchar *label = gr_prepare_label (SP_OBJECT(gradient));
            gtk_label_set_markup (GTK_LABEL(l), label);
            g_free (label);
            gtk_misc_set_alignment (GTK_MISC (l), 1.0, 0.5);
            gtk_box_pack_start (GTK_BOX (hb), l, TRUE, TRUE, 0);
            gtk_box_pack_start (GTK_BOX (hb), image, FALSE, FALSE, 0);

            gtk_widget_show_all (i);

            gtk_container_add (GTK_CONTAINER (i), hb);

            gtk_menu_append (GTK_MENU (m), i);

            if (gradient == gr_selected) {
                pos = idx;
            }
            idx ++;
        }
        gtk_widget_set_sensitive (om, TRUE);
    }

    gtk_option_menu_set_menu (GTK_OPTION_MENU (om), m);
    /* Select the current gradient, or the Multi/Nothing line */
    if (gr_multi || gr_selected == NULL)
        gtk_option_menu_set_history (GTK_OPTION_MENU (om), 0);
    else
        gtk_option_menu_set_history (GTK_OPTION_MENU (om), pos);

    return om;
}
static void
read_one_setting_value (NMSetting *setting,
                        const char *key,
                        const GValue *value,
                        GParamFlags flags,
                        gpointer user_data)
{
	GKeyFile *file = user_data;
	const char *setting_name;
	GType type;
	GError *err = NULL;
	gboolean check_for_key = TRUE;
	KeyParser *parser = &key_parsers[0];

	/* Property is not writable */
	if (!(flags & G_PARAM_WRITABLE))
		return;

	/* Setting name gets picked up from the keyfile's section name instead */
	if (!strcmp (key, NM_SETTING_NAME))
		return;

	/* Don't read the NMSettingConnection object's 'read-only' property */
	if (   NM_IS_SETTING_CONNECTION (setting)
	    && !strcmp (key, NM_SETTING_CONNECTION_READ_ONLY))
		return;

	setting_name = nm_setting_get_name (setting);

	/* Look through the list of handlers for non-standard format key values */
	while (parser->setting_name) {
		if (!strcmp (parser->setting_name, setting_name) && !strcmp (parser->key, key)) {
			check_for_key = parser->check_for_key;
			break;
		}
		parser++;
	}

	/* VPN properties don't have the exact key name */
	if (NM_IS_SETTING_VPN (setting))
		check_for_key = FALSE;

	/* Check for the exact key in the GKeyFile if required.  Most setting
	 * properties map 1:1 to a key in the GKeyFile, but for those properties
	 * like IP addresses and routes where more than one value is actually
	 * encoded by the setting property, this won't be true.
	 */
	if (check_for_key && !g_key_file_has_key (file, setting_name, key, &err)) {
		/* Key doesn't exist or an error ocurred, thus nothing to do. */
		if (err) {
			g_warning ("Error loading setting '%s' value: %s", setting_name, err->message);
			g_error_free (err);
		}
		return;
	}

	/* If there's a custom parser for this key, handle that before the generic
	 * parsers below.
	 */
	if (parser && parser->setting_name) {
		(*parser->parser) (setting, key, file);
		return;
	}

	type = G_VALUE_TYPE (value);

	if (type == G_TYPE_STRING) {
		char *str_val;

		str_val = g_key_file_get_string (file, setting_name, key, NULL);
		g_object_set (setting, key, str_val, NULL);
		g_free (str_val);
	} else if (type == G_TYPE_UINT) {
		int int_val;

		int_val = g_key_file_get_integer (file, setting_name, key, NULL);
		if (int_val < 0)
			g_warning ("Casting negative value (%i) to uint", int_val);
		g_object_set (setting, key, int_val, NULL);
	} else if (type == G_TYPE_INT) {
		int int_val;

		int_val = g_key_file_get_integer (file, setting_name, key, NULL);
		g_object_set (setting, key, int_val, NULL);
	} else if (type == G_TYPE_BOOLEAN) {
		gboolean bool_val;

		bool_val = g_key_file_get_boolean (file, setting_name, key, NULL);
		g_object_set (setting, key, bool_val, NULL);
	} else if (type == G_TYPE_CHAR) {
		int int_val;

		int_val = g_key_file_get_integer (file, setting_name, key, NULL);
		if (int_val < G_MININT8 || int_val > G_MAXINT8)
			g_warning ("Casting value (%i) to char", int_val);

		g_object_set (setting, key, int_val, NULL);
	} else if (type == G_TYPE_UINT64) {
		char *tmp_str;
		guint64 uint_val;

		tmp_str = g_key_file_get_value (file, setting_name, key, NULL);
		uint_val = g_ascii_strtoull (tmp_str, NULL, 10);
		g_free (tmp_str);
		g_object_set (setting, key, uint_val, NULL);
 	} else if (type == DBUS_TYPE_G_UCHAR_ARRAY) {
		gint *tmp;
		GByteArray *array;
		gsize length;
		int i;

		tmp = g_key_file_get_integer_list (file, setting_name, key, &length, NULL);

		array = g_byte_array_sized_new (length);
		for (i = 0; i < length; i++) {
			int val = tmp[i];
			unsigned char v = (unsigned char) (val & 0xFF);

			if (val < 0 || val > 255) {
				g_warning ("%s: %s / %s ignoring invalid byte element '%d' (not "
				           " between 0 and 255 inclusive)", __func__, setting_name,
				           key, val);
			} else
				g_byte_array_append (array, (const unsigned char *) &v, sizeof (v));
		}

		g_object_set (setting, key, array, NULL);
		g_byte_array_free (array, TRUE);
		g_free (tmp);
 	} else if (type == DBUS_TYPE_G_LIST_OF_STRING) {
		gchar **sa;
		gsize length;
		int i;
		GSList *list = NULL;

		sa = g_key_file_get_string_list (file, setting_name, key, &length, NULL);
		for (i = 0; i < length; i++)
			list = g_slist_prepend (list, sa[i]);

		list = g_slist_reverse (list);
		g_object_set (setting, key, list, NULL);

		g_slist_free (list);
		g_strfreev (sa);
	} else if (type == DBUS_TYPE_G_MAP_OF_STRING) {
		read_hash_of_string (file, setting, key);
	} else if (type == DBUS_TYPE_G_UINT_ARRAY) {
		if (!read_array_of_uint (file, setting, key)) {
			g_warning ("Unhandled setting property type (read): '%s/%s' : '%s'",
					 setting_name, key, G_VALUE_TYPE_NAME (value));
		}
	} else {
		g_warning ("Unhandled setting property type (read): '%s/%s' : '%s'",
				 setting_name, key, G_VALUE_TYPE_NAME (value));
	}
}
예제 #12
0
GSList *
empathy_smiley_manager_parse (EmpathySmileyManager *manager,
			      const gchar          *text)
{
	EmpathySmileyManagerPriv *priv = GET_PRIV (manager);
	EmpathySmiley            *smiley;
	SmileyManagerTree        *cur_tree = priv->tree;
	const gchar              *t;
	const gchar              *cur_str = text;
	GSList                   *smileys = NULL;

	g_return_val_if_fail (EMPATHY_IS_SMILEY_MANAGER (manager), NULL);
	g_return_val_if_fail (text != NULL, NULL);

	for (t = text; *t; t = g_utf8_next_char (t)) {
		SmileyManagerTree *child;
		gunichar           c;

		c = g_utf8_get_char (t);
		child = smiley_manager_tree_find_child (cur_tree, c);

		if (cur_tree == priv->tree) {
			if (child) {
				if (t > cur_str) {
					smiley = smiley_new (NULL,
							     g_strndup (cur_str, t - cur_str),
							     NULL);
					smileys = g_slist_prepend (smileys, smiley);
				}
				cur_str = t;
				cur_tree = child;
			}

			continue;
		}

		if (child) {
			cur_tree = child;
			continue;
		}

		smiley = smiley_new (cur_tree->pixbuf,
				     g_strndup (cur_str, t - cur_str),
				     cur_tree->path);
		smileys = g_slist_prepend (smileys, smiley);
		if (cur_tree->pixbuf) {
			cur_str = t;
			cur_tree = smiley_manager_tree_find_child (priv->tree, c);

			if (!cur_tree) {
				cur_tree = priv->tree;
			}
		} else {
			cur_str = t;
			cur_tree = priv->tree;
		}
	}

	smiley = smiley_new (cur_tree->pixbuf,
			     g_strndup (cur_str, t - cur_str),
			     cur_tree->path);
	smileys = g_slist_prepend (smileys, smiley);

	return g_slist_reverse (smileys);
}
예제 #13
0
/* this is loosely based on update_places() from caja-places-sidebar.c */
static void
panel_place_menu_item_append_remote_gio (PanelPlaceMenuItem *place_item,
					 GtkWidget          *menu)
{
	GtkWidget *add_menu;
	GList     *mounts, *l;
	GMount    *mount;
	GSList    *add_mounts, *sl;

	/* add mounts that has no volume (/etc/mtab mounts, ftp, sftp,...) */
	mounts = g_volume_monitor_get_mounts (place_item->priv->volume_monitor);
	add_mounts = NULL;

	for (l = mounts; l; l = l->next) {
		GVolume *volume;
		GFile   *root;

		mount = l->data;

		if (g_mount_is_shadowed (mount)) {
			g_object_unref (mount);
			continue;
		}

		volume = g_mount_get_volume (mount);
		if (volume != NULL) {
			g_object_unref (volume);
			g_object_unref (mount);
			continue;
		}

		root = g_mount_get_root (mount);
		if (g_file_is_native (root)) {
			g_object_unref (root);
			g_object_unref (mount);
			continue;
		}
		g_object_unref (root);


		add_mounts = g_slist_prepend (add_mounts, mount);
	}
	add_mounts = g_slist_reverse (add_mounts);

	if (g_slist_length (add_mounts) <= g_settings_get_uint (place_item->priv->menubar_settings, PANEL_MENU_BAR_MAX_ITEMS_OR_SUBMENU)) {
		add_menu = menu;
	} else {
		GtkWidget  *item;

		item = panel_image_menu_item_new ();
		setup_menuitem_with_icon (item, panel_menu_icon_get_size (),
					  NULL,
					  PANEL_ICON_NETWORK_SERVER,
					  _("Network Places"));

		gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
		gtk_widget_show (item);

		add_menu = create_empty_menu ();
		gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), add_menu);
	}

	for (sl = add_mounts; sl; sl = sl->next) {
		mount = sl->data;
		panel_menu_item_append_mount (add_menu, mount);
		g_object_unref (mount);
	}

	g_slist_free (add_mounts);
	g_list_free (mounts);
}
예제 #14
0
/* this is loosely based on update_places() from caja-places-sidebar.c */
static void
panel_place_menu_item_append_local_gio (PanelPlaceMenuItem *place_item,
					GtkWidget          *menu)
{
	GList   *l;
	GList   *ll;
	GList   *drives;
	GDrive  *drive;
	GList   *volumes;
	GVolume *volume;
	GList   *mounts;
	GMount  *mount;
	GSList       *items;
	GSList       *sl;
	PanelGioItem *item;
	GtkWidget *add_menu;

	items = NULL;

	/* first go through all connected drives */
	drives = g_volume_monitor_get_connected_drives (place_item->priv->volume_monitor);
	for (l = drives; l != NULL; l = l->next) {
		drive = l->data;

		volumes = g_drive_get_volumes (drive);
		if (volumes != NULL) {
			for (ll = volumes; ll != NULL; ll = ll->next) {
				volume = ll->data;
				mount = g_volume_get_mount (volume);
				item = g_slice_new (PanelGioItem);
				if (mount != NULL) {
					item->type = PANEL_GIO_MOUNT;
					item->u.mount = mount;
				} else {
					/* Do show the unmounted volumes; this
					 * is so the user can mount it (in case
					 * automounting is off).
					 *
					 * Also, even if automounting is
					 * enabled, this gives a visual cue
					 * that the user should remember to
					 * yank out the media if he just
					 * unmounted it.
					 */
					item->type = PANEL_GIO_VOLUME;
					item->u.volume = g_object_ref (volume);
				}
				items = g_slist_prepend (items, item);
				g_object_unref (volume);
			}
			g_list_free (volumes);
		} else {
			if (g_drive_is_media_removable (drive) &&
			    !g_drive_is_media_check_automatic (drive)) {
				/* If the drive has no mountable volumes and we
				 * cannot detect media change.. we display the
				 * drive so the user can manually poll the
				 * drive by clicking on it..."
				 *
				 * This is mainly for drives like floppies
				 * where media detection doesn't work.. but
				 * it's also for human beings who like to turn
				 * off media detection in the OS to save
				 * battery juice.
				 */
				item = g_slice_new (PanelGioItem);
				item->type = PANEL_GIO_DRIVE;
				item->u.drive = g_object_ref (drive);
				items = g_slist_prepend (items, item);
			}
		}
		g_object_unref (drive);
	}
	g_list_free (drives);

	/* add all volumes that is not associated with a drive */
	volumes = g_volume_monitor_get_volumes (place_item->priv->volume_monitor);
	for (l = volumes; l != NULL; l = l->next) {
		volume = l->data;
		drive = g_volume_get_drive (volume);
		if (drive != NULL) {
		    	g_object_unref (volume);
			g_object_unref (drive);
			continue;
		}
		mount = g_volume_get_mount (volume);
		item = g_slice_new (PanelGioItem);
		if (mount != NULL) {
			item->type = PANEL_GIO_MOUNT;
			item->u.mount = mount;
		} else {
			/* see comment above in why we add an icon for an
			 * unmounted mountable volume */
			item->type = PANEL_GIO_VOLUME;
			item->u.volume = g_object_ref (volume);
		}
		items = g_slist_prepend (items, item);
		g_object_unref (volume);
	}
	g_list_free (volumes);

	/* add mounts that has no volume (/etc/mtab mounts, ftp, sftp,...) */
	mounts = g_volume_monitor_get_mounts (place_item->priv->volume_monitor);
	for (l = mounts; l != NULL; l = l->next) {
		GFile *root;

		mount = l->data;

		if (g_mount_is_shadowed (mount)) {
			g_object_unref (mount);
			continue;
		}

		volume = g_mount_get_volume (mount);
		if (volume != NULL) {
			g_object_unref (volume);
			g_object_unref (mount);
			continue;
		}

		root = g_mount_get_root (mount);
		if (!g_file_is_native (root)) {
			g_object_unref (root);
			g_object_unref (mount);
			continue;
		}
		g_object_unref (root);

		item = g_slice_new (PanelGioItem);
		item->type = PANEL_GIO_MOUNT;
		item->u.mount = mount;
		items = g_slist_prepend (items, item);
	}
	g_list_free (mounts);

	/* now that we have everything, add the items inline or in a submenu */
	items = g_slist_reverse (items);

	if (g_slist_length (items) <= g_settings_get_uint (place_item->priv->menubar_settings, PANEL_MENU_BAR_MAX_ITEMS_OR_SUBMENU)) {
		add_menu = menu;
	} else {
		GtkWidget  *item;

		item = gtk_image_menu_item_new ();
		setup_menuitem_with_icon (item, panel_menu_icon_get_size (),
					  NULL,
					  PANEL_ICON_REMOVABLE_MEDIA,
					   _("Removable Media"));

		gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
		gtk_widget_show (item);

		add_menu = create_empty_menu ();
		gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), add_menu);
	}

	for (sl = items; sl; sl = sl->next) {
		item = sl->data;
		switch (item->type) {
		case PANEL_GIO_DRIVE:
			panel_menu_item_append_drive (add_menu, item->u.drive);
			g_object_unref (item->u.drive);
			break;
		case PANEL_GIO_VOLUME:
			panel_menu_item_append_volume (add_menu, item->u.volume);
			g_object_unref (item->u.volume);
			break;
		case PANEL_GIO_MOUNT:
			panel_menu_item_append_mount (add_menu, item->u.mount);
			g_object_unref (item->u.mount);
			break;
		default:
			g_assert_not_reached ();
		}
		g_slice_free (PanelGioItem, item);
	}

	g_slist_free (items);
}
GSList*
mono_w32process_get_modules (pid_t pid)
{
    GSList *ret = NULL;
    FILE *fp;
    MonoW32ProcessModule *mod;
    gchar buf[MAXPATHLEN + 1], *p, *endp;
    gchar *start_start, *end_start, *prot_start, *offset_start;
    gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
    gpointer address_start, address_end, address_offset;
    guint32 maj_dev, min_dev;
    guint64 inode;
    guint64 device;

    fp = open_process_map (pid, "r");
    if (!fp)
        return NULL;

    while (fgets (buf, sizeof(buf), fp)) {
        p = buf;
        while (g_ascii_isspace (*p)) ++p;
        start_start = p;
        if (!g_ascii_isxdigit (*start_start)) {
            continue;
        }
        address_start = (gpointer)strtoul (start_start, &endp, 16);
        p = endp;
        if (*p != '-') {
            continue;
        }

        ++p;
        end_start = p;
        if (!g_ascii_isxdigit (*end_start)) {
            continue;
        }
        address_end = (gpointer)strtoul (end_start, &endp, 16);
        p = endp;
        if (!g_ascii_isspace (*p)) {
            continue;
        }

        while (g_ascii_isspace (*p)) ++p;
        prot_start = p;
        if (*prot_start != 'r' && *prot_start != '-') {
            continue;
        }
        memcpy (prot_buf, prot_start, 4);
        prot_buf[4] = '\0';
        while (!g_ascii_isspace (*p)) ++p;

        while (g_ascii_isspace (*p)) ++p;
        offset_start = p;
        if (!g_ascii_isxdigit (*offset_start)) {
            continue;
        }
        address_offset = (gpointer)strtoul (offset_start, &endp, 16);
        p = endp;
        if (!g_ascii_isspace (*p)) {
            continue;
        }

        while(g_ascii_isspace (*p)) ++p;
        maj_dev_start = p;
        if (!g_ascii_isxdigit (*maj_dev_start)) {
            continue;
        }
        maj_dev = strtoul (maj_dev_start, &endp, 16);
        p = endp;
        if (*p != ':') {
            continue;
        }

        ++p;
        min_dev_start = p;
        if (!g_ascii_isxdigit (*min_dev_start)) {
            continue;
        }
        min_dev = strtoul (min_dev_start, &endp, 16);
        p = endp;
        if (!g_ascii_isspace (*p)) {
            continue;
        }

        while (g_ascii_isspace (*p)) ++p;
        inode_start = p;
        if (!g_ascii_isxdigit (*inode_start)) {
            continue;
        }
        inode = (guint64)strtol (inode_start, &endp, 10);
        p = endp;
        if (!g_ascii_isspace (*p)) {
            continue;
        }

        device = makedev ((int)maj_dev, (int)min_dev);
        if ((device == 0) && (inode == 0)) {
            continue;
        }

        while(g_ascii_isspace (*p)) ++p;
        /* p now points to the filename */

        mod = g_new0 (MonoW32ProcessModule, 1);
        mod->address_start = address_start;
        mod->address_end = address_end;
        mod->perms = g_strdup (prot_buf);
        mod->address_offset = address_offset;
        mod->device = device;
        mod->inode = inode;
        mod->filename = g_strdup (g_strstrip (p));

        if (g_slist_find_custom (ret, mod, mono_w32process_module_equals) == NULL) {
            ret = g_slist_prepend (ret, mod);
        } else {
            mono_w32process_module_free (mod);
        }
    }

    ret = g_slist_reverse (ret);

    fclose (fp);

    return(ret);
}
/*
 * the @ps struct is modified and transferred to the new data model created in
 * this function
 */
GdaDataModel *
_gda_sqlite_recordset_new (GdaConnection *cnc, GdaSqlitePStmt *ps, GdaSet *exec_params,
			   GdaDataModelAccessFlags flags, GType *col_types, gboolean force_empty)
{
	GdaSqliteRecordset *model;
        SqliteConnectionData *cdata;
        gint i;
	GdaDataModelAccessFlags rflags;
	gboolean is_virt;
        g_return_val_if_fail (GDA_IS_CONNECTION (cnc), NULL);
        g_return_val_if_fail (ps != NULL, NULL);

	cdata = (SqliteConnectionData*) gda_connection_internal_get_provider_data (cnc);
	if (!cdata)
		return NULL;

        if (!cdata->types_hash)
                _gda_sqlite_compute_types_hash (cdata);

        /* make sure @ps reports the correct number of columns */
	if (_GDA_PSTMT (ps)->ncols < 0)
		_GDA_PSTMT (ps)->ncols = SQLITE3_CALL (sqlite3_column_count) (ps->sqlite_stmt) -
			ps->nb_rowid_columns;

        /* completing ps */
	g_assert (! ps->stmt_used);
        ps->stmt_used = TRUE;
        if (!_GDA_PSTMT (ps)->types && (_GDA_PSTMT (ps)->ncols > 0)) {
		/* create prepared statement's columns */
		GSList *list;
		for (i = 0; i < _GDA_PSTMT (ps)->ncols; i++)
			_GDA_PSTMT (ps)->tmpl_columns = g_slist_prepend (_GDA_PSTMT (ps)->tmpl_columns, 
									 gda_column_new ());
		_GDA_PSTMT (ps)->tmpl_columns = g_slist_reverse (_GDA_PSTMT (ps)->tmpl_columns);

		/* create prepared statement's types, all types are initialized to GDA_TYPE_NULL */
		_GDA_PSTMT (ps)->types = g_new (GType, _GDA_PSTMT (ps)->ncols);
		for (i = 0; i < _GDA_PSTMT (ps)->ncols; i++)
			_GDA_PSTMT (ps)->types [i] = GDA_TYPE_NULL;

		if (col_types) {
			for (i = 0; ; i++) {
				if (col_types [i] > 0) {
					if (col_types [i] == G_TYPE_NONE)
						break;
					if (i >= _GDA_PSTMT (ps)->ncols)
						g_warning (_("Column %d out of range (0-%d), ignoring its specified type"), i,
							   _GDA_PSTMT (ps)->ncols - 1);
					else 
						_GDA_PSTMT (ps)->types [i] = col_types [i];
				}
			}
		}
		
		/* fill GdaColumn's data */
		for (i=0, list = _GDA_PSTMT (ps)->tmpl_columns; 
		     i < GDA_PSTMT (ps)->ncols; 
		     i++, list = list->next) {
			GdaColumn *column;
			gint real_col = i + ps->nb_rowid_columns;
			
			column = GDA_COLUMN (list->data);
			gda_column_set_description (column, SQLITE3_CALL (sqlite3_column_name) (ps->sqlite_stmt, real_col));
			gda_column_set_name (column, SQLITE3_CALL (sqlite3_column_name) (ps->sqlite_stmt, real_col));
			gda_column_set_dbms_type (column, SQLITE3_CALL (sqlite3_column_decltype) (ps->sqlite_stmt, real_col));
			if (_GDA_PSTMT (ps)->types [i] != GDA_TYPE_NULL)
				gda_column_set_g_type (column, _GDA_PSTMT (ps)->types [i]);
		}
        }

	/* determine access mode: RANDOM or CURSOR FORWARD are the only supported; if CURSOR BACKWARD
	 * is requested, then we need RANDOM mode */
	if (flags & GDA_DATA_MODEL_ACCESS_RANDOM)
		rflags = GDA_DATA_MODEL_ACCESS_RANDOM;
	else if (flags & GDA_DATA_MODEL_ACCESS_CURSOR_BACKWARD)
		rflags = GDA_DATA_MODEL_ACCESS_RANDOM;
	else
		rflags = GDA_DATA_MODEL_ACCESS_CURSOR_FORWARD;

	/* create data model */
        model = g_object_new (GDA_TYPE_SQLITE_RECORDSET, "connection", cnc, 
			      "prepared-stmt", ps, "model-usage", rflags, 
			      "exec-params", exec_params, 
			      "auto-reset", force_empty, NULL);

	is_virt = GDA_IS_VCONNECTION_DATA_MODEL (cnc) ? TRUE : FALSE;
	if (is_virt) {
		/* steal the lock */
		_gda_vconnection_change_working_obj ((GdaVconnectionDataModel*) cnc, (GObject*) model);
		_gda_vconnection_set_working_obj ((GdaVconnectionDataModel*) cnc, NULL);
	}

        /* fill the data model */
        read_rows_to_init_col_types (model);

        return GDA_DATA_MODEL (model);
}
예제 #17
0
파일: dock.c 프로젝트: Bhattiasif/gdis
void docking_project_create(GtkWidget *w, struct model_pak *model)
{
gint a, b, i, m, n, rx, ry, rz, size, rigid_save;
gint a_max, b_max, rx_max, ry_max, rz_max;
gchar *file, *dump, *dump_save, *rigid_move_save;
gdouble dx, dy, dz, x[3], scale[3], mat[9], dock_centroid[3], q[4];
GString *name, *rigid;
GSList *list, *core_list, *shell_list;
struct dock_pak *dock;
struct core_pak *core, *core2;
struct shel_pak *shell, *shell2;
FILE *fp;

/* checks */
g_assert(model != NULL);
size = g_slist_length(model->selection);
if (!size)
  {
  gui_text_show(WARNING, "Please select the subset you wish to dock.\n");
  return;
  }

/* create new docking project */
dock = g_malloc(sizeof(struct dock_pak));

/* NEW - setup project path */
/*
g_path_get_dirname(model->fullpath);
g_get_current_dir();
*/

/* seek a file name that doesn't exist (avoid background overwriting) */
name = g_string_new(NULL);
i=0;
do
  {
  g_string_sprintf(name, "project_%06d", i);
  i++;
  }
while (g_file_test(name->str, G_FILE_TEST_EXISTS));

dock->path = g_build_path(sysenv.cwd, name->str, NULL);

printf("creating new project: [%s]\n", dock->path);

#if WIN32
if (mkdir(dock->path))
#else
if (mkdir(dock->path, 0700))
#endif
  {
  gui_text_show(ERROR, "Failed to create project directory.\n");
  g_free(dock->path);
  g_free(dock);
  return;
  }

/* project control file */
g_string_sprintf(name, "%s%sproject.pcf", dock->path, DIR_SEP);
fp = fopen(name->str, "wt");

/* save original variables */
dump_save = model->gulp.dump_file;
model->gulp.dump_file = NULL;
rigid_save = model->gulp.rigid;
model->gulp.rigid = dock_rigid_on;
rigid_move_save = model->gulp.rigid_move;
model->gulp.rigid_move = NULL;
if (model->gulp.rigid)
  {
  rigid = g_string_new(NULL);
  if (dock_rigid_x)
    g_string_sprintf(rigid, "x");
  if (dock_rigid_y)
    g_string_sprintfa(rigid, "y");
  if (dock_rigid_z)
    g_string_sprintfa(rigid, "z");
  model->gulp.rigid_move = g_string_free(rigid, FALSE);
  }

/* duplicate selection for docking */
core_list = NULL;
shell_list = NULL;
VEC3SET(dock_centroid, 0.0, 0.0, 0.0);
for (list=model->selection ; list ; list=g_slist_next(list))
  {
  core2 = dup_core(list->data);
  core_list = g_slist_prepend(core_list, core2);
  if (core2->shell)
    shell_list = g_slist_prepend(shell_list, core2->shell);
/* compute centroid */
  ARR3ADD(dock_centroid, core2->x);
  }

/* NB: lists must have the same order as original selection */
core_list = g_slist_reverse(core_list);
shell_list = g_slist_reverse(shell_list);
VEC3MUL(dock_centroid, 1.0/(gdouble) size);

/* fractional translation grid units */
scale[0] = dock_cell[0] / dock_grid[0];
scale[1] = dock_cell[1] / dock_grid[1];

/* rotational increments */
dx = PI/dock_rotate[0];
dy = PI/dock_rotate[1];
dz = PI/dock_rotate[2];

/* translational sampling */
if (dock_grid_on)
  {
  a_max = dock_grid[0];
  b_max = dock_grid[1];
  }
else
  {
  a_max = 1;
  b_max = 1;
  }

/* rotational sampling */
if (dock_rotate_on)
  {
  rx_max = dock_rotate[0];
  ry_max = dock_rotate[1];
  rz_max = dock_rotate[2];
  }
else
  {
  rx_max = 1;
  ry_max = 1;
  rz_max = 1;
  }

/* project header */
fprintf(fp, "%%title solvent mapping project\n");
fprintf(fp, "%%set %d %d %f %f\n", a_max, b_max, dock_cell[0], dock_cell[1]);

/* loop over all grid translations */
m = n = 0;
for (a=0 ; a<a_max ; a++)
  {
  for (b=0 ; b<b_max ; b++)
    {
    VEC3SET(x, a, b, 0.0);
    x[0] *= scale[0];
    x[1] *= scale[1];

/* loop over rotations */
    VEC4SET(q, 1.0, 0.0, 0.0, 0.0);
    for (rx=0 ; rx<rx_max ; rx++)
      {
      if (rx)
        quat_concat_euler(q, PITCH, dx);

    for (ry=0 ; ry<ry_max ; ry++)
      {
      if (ry)
        quat_concat_euler(q, ROLL, dy);

    for (rz=0 ; rz<rz_max ; rz++)
      {
      if (rz)
        quat_concat_euler(q, YAW, dz);

/* build total rotation matrix */
      quat_matrix(mat, q);

/* transform the cores and shells */
      i = 0;
      for (list=model->selection ; list ; list=g_slist_next(list))
        {
        core = list->data;

/* FIXME - should we restore this after? how? */
core->region = 2;

/* get original selection core coordinates */
        core2 = g_slist_nth_data(core_list, i);
        ARR3SET(core->x, core2->x);
/* perform the rotation (NB: must be done about origin in cartesian space) */
        ARR3SUB(core->x, dock_centroid);
        vecmat(model->latmat, core->x);
        vecmat(mat, core->x);
        vecmat(model->ilatmat, core->x);
        ARR3ADD(core->x, dock_centroid);
/* add the current translation offset */
        ARR3ADD(core->x, x);

/* as above, for the associated shell */
        if (core->shell)
          {
          shell = core->shell;
shell->region = 2;
          shell2 = core2->shell;
g_assert(shell2 != NULL);
          ARR3SET(shell->x, shell2->x);
          ARR3SUB(shell->x, dock_centroid);
          vecmat(model->latmat, shell->x);
          vecmat(mat, shell->x);
          vecmat(model->ilatmat, shell->x);
          ARR3ADD(shell->x, dock_centroid);
          ARR3ADD(shell->x, x);
          }
        i++;
        }
/* write docking configuration */
/*
      file = g_strdup_printf("%s_%06d.gin", model->basename, n);
*/

/* m identifies grid points (for later minimum check) */
fprintf(fp, "%s_%06d.gin %f %f %d\n", model->basename, n, x[0], x[1], m);

      file = g_strdup_printf("%s%s%s_%06d.gin", dock->path, DIR_SEP, model->basename, n);
      dump = g_strdup_printf("%s_%06d.res", model->basename, n);

      model->gulp.dump_file = dump;

      write_gulp(file, model);

      g_free(file);
      g_free(dump);
      n++;

      }
      }
      }
    m++;
    }
  }

/* restore original variables */
model->gulp.dump_file = dump_save;
model->gulp.rigid = rigid_save;
g_free(model->gulp.rigid_move);
model->gulp.rigid_move = rigid_move_save;

/* restore original selection (delete, then concat saved list) */
i = 0;
for (list=model->selection ; list ; list=g_slist_next(list))
  {
  core = list->data;
  core2 = g_slist_nth_data(core_list, i);
  ARR3SET(core->x, core2->x);
  if (core->shell)
    {
    shell = core->shell;
    shell2 = core2->shell;
g_assert(shell2 != NULL);
    ARR3SET(shell->x, shell2->x);
    }
  i++;
  }

/* free docking core/shell lists */
free_slist(core_list);
free_slist(shell_list);

g_string_free(name, TRUE);
fclose(fp);
/* run docking in background unless told to stop after setup */
/*
if (!dock_no_execute)
  submit_task("Docking", &docking_execute, dock, &docking_cleanup, dock, model);
*/
}
예제 #18
0
GSList *
show_file_chooser (const gchar          *title,
                   enum GtkuiFileChooserType type,
                   gboolean             select_multiple)
{
    GtkFileChooserAction action;
    switch (type) {
    case GTKUI_FILECHOOSER_OPENFOLDER:
        action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
        break;
    case GTKUI_FILECHOOSER_OPENFILE:
    case GTKUI_FILECHOOSER_LOADPLAYLIST:
        action = GTK_FILE_CHOOSER_ACTION_OPEN;
        break;
    case GTKUI_FILECHOOSER_SAVEPLAYLIST:
        action = GTK_FILE_CHOOSER_ACTION_SAVE;
        break;
    }

    GtkFileChooser *dlg = get_file_chooser(title, action, select_multiple);

    switch (type) {
    case GTKUI_FILECHOOSER_OPENFILE:
        set_file_filter (dlg, NULL);
        break;
    case GTKUI_FILECHOOSER_LOADPLAYLIST:
        set_file_filter_loadplaylist(dlg);
        break;
    case GTKUI_FILECHOOSER_SAVEPLAYLIST:
        gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dlg), TRUE);
        gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dlg), "untitled.dbpl");
        set_file_filter_saveplaylist(dlg);
        break;
    }

    const char *conf_lastdir;
    switch (type) {
    case GTKUI_FILECHOOSER_OPENFOLDER:
    case GTKUI_FILECHOOSER_OPENFILE:
        conf_lastdir = "filechooser.lastdir";
        break;
    case GTKUI_FILECHOOSER_LOADPLAYLIST:
    case GTKUI_FILECHOOSER_SAVEPLAYLIST:
        conf_lastdir = "filechooser.playlist.lastdir";
        break;
    }

    // restore folder
    /* Windows: setting current folder for native filechooser here breaks restoring dirs, without it it still works fine?
    deadbeef->conf_lock ();
    gtk_file_chooser_set_current_folder_uri (GTK_FILE_CHOOSER (dlg), deadbeef->conf_get_str_fast (conf_lastdir, ""));
    deadbeef->conf_unlock ();
    */

    int response = run_file_chooser(dlg);

    // store folder
    gchar *folder = gtk_file_chooser_get_current_folder_uri (GTK_FILE_CHOOSER (dlg));
    if (folder) {
        deadbeef->conf_set_str (conf_lastdir, folder);
        g_free (folder);
    }
    GSList *lst = NULL;
    if (response == GTK_RESPONSE_ACCEPT)
    {
        lst = gtk_file_chooser_get_filenames (GTK_FILE_CHOOSER (dlg));
#if defined USE_GTK_NATIVE_FILE_CHOOSER && defined __MINGW32__
        // workaround: Gtk's win32 file chooser uses g_slist_prepend internally and forgets to reverse it before returning
        lst = g_slist_reverse (lst);
#endif
    }

    destroy_file_chooser (dlg);
    return lst;
}
gint
gimp_plug_in_manager_query (GimpPlugInManager   *manager,
                            const gchar         *search_str,
                            gchar             ***menu_strs,
                            gchar             ***accel_strs,
                            gchar             ***prog_strs,
                            gchar             ***types_strs,
                            gchar             ***realname_strs,
                            gint32             **time_ints)
{
  gint32   num_plugins = 0;
  GSList  *list;
  GSList  *matched     = NULL;
  gint     i           = 0;
  GRegex  *sregex      = NULL;

  g_return_val_if_fail (GIMP_IS_PLUG_IN_MANAGER (manager), 0);
  g_return_val_if_fail (menu_strs != NULL, 0);
  g_return_val_if_fail (accel_strs != NULL, 0);
  g_return_val_if_fail (prog_strs != NULL, 0);
  g_return_val_if_fail (types_strs != NULL, 0);
  g_return_val_if_fail (realname_strs != NULL, 0);
  g_return_val_if_fail (time_ints != NULL, 0);

  *menu_strs     = NULL;
  *accel_strs    = NULL;
  *prog_strs     = NULL;
  *types_strs    = NULL;
  *realname_strs = NULL;
  *time_ints     = NULL;

  if (search_str && ! strlen (search_str))
    search_str = NULL;

  if (search_str)
    {
      sregex = g_regex_new (search_str, G_REGEX_CASELESS | G_REGEX_OPTIMIZE, 0,
                            NULL);
      if (! sregex)
        return 0;
    }

  /* count number of plugin entries, then allocate arrays of correct size
   * where we can store the strings.
   */

  for (list = manager->plug_in_procedures; list; list = g_slist_next (list))
    {
      GimpPlugInProcedure *proc = list->data;

      if (proc->file && proc->menu_paths)
        {
          gchar *name;

          if (proc->menu_label)
            {
              name = proc->menu_label;
            }
          else
            {
              name = strrchr (proc->menu_paths->data, '/');

              if (name)
                name = name + 1;
              else
                name = proc->menu_paths->data;
            }

          name = gimp_strip_uline (name);

          if (! search_str || match_string (sregex, name))
            {
              num_plugins++;
              matched = g_slist_prepend (matched, proc);
            }

          g_free (name);
        }
    }

  *menu_strs     = g_new (gchar *, num_plugins);
  *accel_strs    = g_new (gchar *, num_plugins);
  *prog_strs     = g_new (gchar *, num_plugins);
  *types_strs    = g_new (gchar *, num_plugins);
  *realname_strs = g_new (gchar *, num_plugins);
  *time_ints     = g_new (gint,    num_plugins);

  matched = g_slist_reverse (matched);

  for (list = matched; list; list = g_slist_next (list))
    {
      GimpPlugInProcedure *proc = list->data;
      gchar               *name;

      if (proc->menu_label)
        name = g_strdup_printf ("%s/%s",
                                (gchar *) proc->menu_paths->data,
                                proc->menu_label);
      else
        name = g_strdup (proc->menu_paths->data);

      (*menu_strs)[i]     = gimp_strip_uline (name);
      (*accel_strs)[i]    = NULL;
      (*prog_strs)[i]     = g_file_get_path (proc->file);
      (*types_strs)[i]    = g_strdup (proc->image_types);
      (*realname_strs)[i] = g_strdup (gimp_object_get_name (proc));
      (*time_ints)[i]     = proc->mtime;

      g_free (name);

      i++;
    }

  g_slist_free (matched);

  if (sregex)
    g_regex_unref (sregex);

  return num_plugins;
}
예제 #20
0
static void grouplist_dialog_set_list(const gchar *pattern, gboolean refresh)
{
	static GdkCursor *watch_cursor = NULL;
	GSList *cur;
	GtkCMCTreeNode *node;
	GPatternSpec *pspec;
	GdkWindow *window;

	if (locked) return;
	locked = TRUE;

	if (!pattern || *pattern == '\0')
		pattern = "*";

	if (!watch_cursor)
		watch_cursor = gdk_cursor_new(GDK_WATCH);
	window = gtk_widget_get_window(dialog);
	gdk_window_set_cursor(window, watch_cursor);
	main_window_cursor_wait(mainwindow_get_mainwindow());
	GTK_EVENTS_FLUSH();
	
	if (refresh) {
		ack = TRUE;
		grouplist_clear();
		recv_set_ui_func(grouplist_recv_func, NULL);
		group_list = news_get_group_list(news_folder);
		group_list = g_slist_reverse(group_list);
		recv_set_ui_func(NULL, NULL);
		if (group_list == NULL && ack == TRUE) {
			alertpanel_error(_("Can't retrieve newsgroup list."));
			locked = FALSE;
			gdk_window_set_cursor(window, NULL);
			main_window_cursor_normal(mainwindow_get_mainwindow());
			return;
		}
	} else
		gtk_cmclist_clear(GTK_CMCLIST(ctree));

	gtk_entry_set_text(GTK_ENTRY(entry), pattern);

	grouplist_hash_init();

	gtk_cmclist_freeze(GTK_CMCLIST(ctree));

	pspec = g_pattern_spec_new(pattern);

	for (cur = group_list; cur != NULL ; cur = cur->next) {
		NewsGroupInfo *ginfo = (NewsGroupInfo *)cur->data;

		if (g_pattern_match_string(pspec, ginfo->name)) {
			node = grouplist_create_branch(ginfo, pattern);
			if (g_slist_find_custom(subscribed, ginfo->name,
						(GCompareFunc)g_ascii_strcasecmp)
			    != NULL)
				gtk_cmctree_select(GTK_CMCTREE(ctree), node);
		}
	}
	for (cur = subscribed; cur; cur = g_slist_next(cur))
		grouplist_expand_upwards(GTK_CMCTREE(ctree), (gchar *)cur->data);

	g_pattern_spec_free(pspec);

	gtk_cmclist_thaw(GTK_CMCLIST(ctree));

	grouplist_hash_done();

	gtk_label_set_text(GTK_LABEL(status_label), _("Done."));

	gdk_window_set_cursor(window, NULL);
	main_window_cursor_normal(mainwindow_get_mainwindow());

	locked = FALSE;
}
예제 #21
0
gboolean
lr_fastestmirror_sort_internalmirrorlists(GSList *handles,
                                          GError **err)
{
    assert(!err || *err == NULL);

    if (!handles)
        return TRUE;

    GTimer *timer = g_timer_new();
    g_timer_start(timer);

    LrHandle *main_handle = handles->data;  // Network configuration for the
                                            // test is used from the first
                                            // handle

    // Prepare list of hosts
    gchar *fastestmirrorcache = main_handle->fastestmirrorcache;
    GHashTable *hosts_ht = g_hash_table_new_full(g_str_hash,
                                                 g_str_equal,
                                                 g_free,
                                                 NULL);

    for (GSList *ehandle = handles; ehandle; ehandle = g_slist_next(ehandle)) {
        LrHandle *handle = ehandle->data;
        GSList *mirrors = handle->internal_mirrorlist;
        for (GSList *elem = mirrors; elem; elem = g_slist_next(elem)) {
            LrInternalMirror *imirror = elem->data;
            gchar *host = lr_url_without_path(imirror->url);
            g_hash_table_insert(hosts_ht, host, NULL);
        }

        // Cache related warning
        if (fastestmirrorcache) {
            if (handle->fastestmirrorcache
                && g_strcmp0(fastestmirrorcache, handle->fastestmirrorcache))
                g_warning("%s: Multiple fastestmirror caches are specified! "
                          "Used one is %s (%s is ignored)", __func__,
                          fastestmirrorcache, handle->fastestmirrorcache);
        } else {
            if (handle->fastestmirrorcache)
                g_warning("%s: First handle doesn't have a fastestmirror "
                          "cache specified but other one has: %s",
                          __func__, handle->fastestmirrorcache);
        }
    }

    GList *tmp_list_of_urls = g_hash_table_get_keys(hosts_ht);
    GSList *list_of_urls = NULL;
    int number_of_mirrors = 0;
    for (GList *elem = tmp_list_of_urls; elem; elem = g_list_next(elem)) {
        list_of_urls = g_slist_prepend(list_of_urls, elem->data);
        number_of_mirrors++;
    }
    g_list_free(tmp_list_of_urls);

    if (number_of_mirrors <= 1) {
        // Nothing to do
        g_slist_free(list_of_urls);
        g_hash_table_destroy(hosts_ht);
        g_timer_destroy(timer);
        return TRUE;
    }

    // Sort this list by the connection time
    gboolean ret = lr_fastestmirror(main_handle,
                                    &list_of_urls,
                                    err);
    if (!ret) {
        g_debug("%s: lr_fastestmirror failed", __func__);
        g_slist_free(list_of_urls);
        g_hash_table_destroy(hosts_ht);
        g_timer_destroy(timer);
        return FALSE;
    }

    // Apply sorted order to each handle
    for (GSList *ehandle = handles; ehandle; ehandle = g_slist_next(ehandle)) {
        LrHandle *handle = ehandle->data;
        GSList *mirrors = handle->internal_mirrorlist;
        GSList *new_list = NULL;
        for (GSList *elem = list_of_urls; elem; elem = g_slist_next(elem)) {
            gchar *host = elem->data;
            for (GSList *ime = mirrors; ime; ime = g_slist_next(ime)) {
                LrInternalMirror *im = ime->data;
                gchar *im_host = lr_url_without_path(im->url);
                if (!g_strcmp0(im_host, host)) {
                    new_list = g_slist_prepend(new_list, im);
                    // XXX: Maybe convert GSList to GList to make
                    // this delete more efficient
                    mirrors = g_slist_delete_link(mirrors, ime);
                    break;
                }
            }
        }

        // If multiple mirrors with the same lr_url_without_path(url)
        // were present, only the first occurrence was inserted to the
        // the new_list and removed from the mirrors list.
        // The remaining occurences will be moved here.
        for (GSList *elem = mirrors; elem; elem = g_slist_next(elem)) {
            LrInternalMirror *im = elem->data;
            new_list = g_slist_prepend(new_list, im);
        }
        g_slist_free(mirrors);

        // Set sorted list to the handle (reversed, because the items
        // of the new_list were prepended)
        handle->internal_mirrorlist = g_slist_reverse(new_list);
    }

    g_slist_free(list_of_urls);
    g_hash_table_destroy(hosts_ht);

    g_timer_stop(timer);
    g_debug("%s: Duration: %f", __func__, g_timer_elapsed(timer, NULL));
    g_timer_destroy(timer);

    return TRUE;
}
예제 #22
0
static SeahorseOperation* 
seahorse_hkp_source_import (SeahorseSource *sksrc, GInputStream *input)
{
    SeahorseHKPOperation *hop;
    SeahorseHKPSource *hsrc;
    SoupMessage *message;
    GSList *keydata = NULL;
    GString *buf = NULL;
    GHashTable *form;
    gchar *key, *t;
    SoupURI *uri;
    GSList *l;
    guint len;
    
    g_return_val_if_fail (SEAHORSE_IS_HKP_SOURCE (sksrc), NULL);
    hsrc = SEAHORSE_HKP_SOURCE (sksrc);
    
    g_return_val_if_fail (G_IS_INPUT_STREAM (input), NULL);
    g_object_ref (input);
    
    for (;;) {
     
        buf = g_string_sized_new (2048);
        len = seahorse_util_read_data_block (buf, input, "-----BEGIN PGP PUBLIC KEY BLOCK-----",
                                             "-----END PGP PUBLIC KEY BLOCK-----");
    
        if (len > 0) {
            keydata = g_slist_prepend (keydata, g_string_free (buf, FALSE));
        } else {
            g_string_free (buf, TRUE);
            break;
        }
    }
    
    	if (g_slist_length (keydata) == 0) {
    		g_object_unref (input);
    		return seahorse_operation_new_complete (NULL);
    	}
    
    /* Figure out the URI we're sending to */    
    uri = get_http_server_uri (sksrc, "/pks/add");
    g_return_val_if_fail (uri, FALSE);

    /* New operation and away we go */
    keydata = g_slist_reverse (keydata);   
    hop = setup_hkp_operation (hsrc);
    
    form = g_hash_table_new (g_str_hash, g_str_equal);
    for (l = keydata; l; l = g_slist_next (l)) {
        g_assert (l->data != NULL);

        g_hash_table_insert (form, "keytext", l->data);
        key = soup_form_encode_urlencoded (form);

        message = soup_message_new_from_uri ("POST", uri);
        soup_message_set_request (message, "application/x-www-form-urlencoded",
                                  SOUP_MEMORY_TAKE, key, strlen (key));
        
        soup_session_queue_message (hop->session, message, 
                                    (SoupSessionCallback)send_callback, hop);
        hop->requests++;
    }
    g_hash_table_destroy (form);

    hop->total = hop->requests;
    t = g_strdup_printf (_("Connecting to: %s"), uri->host);
    seahorse_operation_mark_progress (SEAHORSE_OPERATION (hop), t, -1);
    g_free (t);

    soup_uri_free (uri);
    
    	seahorse_util_string_slist_free (keydata);
    	g_object_unref (input);
    
    return SEAHORSE_OPERATION (hop);
}
예제 #23
0
static gboolean
ui_to_setting (CEPageIP4 *self)
{
	CEPageIP4Private *priv = CE_PAGE_IP4_GET_PRIVATE (self);
	GtkTreeModel *model;
	GtkTreeIter tree_iter;
	int int_method = IP4_METHOD_AUTO;
	const char *method;
	GArray *dns_servers = NULL;
	GSList *search_domains = NULL;
	GPtrArray *addresses = NULL;
	gboolean valid = FALSE, iter_valid;
	const char *text;
	gboolean ignore_auto_dns = FALSE;
	const char *dhcp_client_id = NULL;
	char **items = NULL, **iter;

	/* Method */
	if (gtk_combo_box_get_active_iter (priv->method, &tree_iter)) {
		gtk_tree_model_get (GTK_TREE_MODEL (priv->method_store), &tree_iter,
		                    METHOD_COL_NUM, &int_method, -1);
	}

	switch (int_method) {
	case IP4_METHOD_LINK_LOCAL:
		method = NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL;
		break;
	case IP4_METHOD_MANUAL:
		method = NM_SETTING_IP4_CONFIG_METHOD_MANUAL;
		break;
	case IP4_METHOD_SHARED:
		method = NM_SETTING_IP4_CONFIG_METHOD_SHARED;
		break;
	case IP4_METHOD_AUTO_ADDRESSES:
		ignore_auto_dns = TRUE;
		/* fall through */
	default:
		method = NM_SETTING_IP4_CONFIG_METHOD_AUTO;
		break;
	}

	/* IP addresses */
	model = gtk_tree_view_get_model (priv->addr_list);
	iter_valid = gtk_tree_model_get_iter_first (model, &tree_iter);

	addresses = g_ptr_array_sized_new (1);
	while (iter_valid) {
		char *item = NULL;
		struct in_addr tmp_addr, tmp_gateway = { 0 };
		GArray *addr;
		guint32 empty_val = 0, prefix;

		gtk_tree_model_get (model, &tree_iter, COL_ADDRESS, &item, -1);
		if (!item || !inet_aton (item, &tmp_addr)) {
			g_warning ("%s: IPv4 address '%s' missing or invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		gtk_tree_model_get (model, &tree_iter, COL_PREFIX, &item, -1);
		if (!item) {
			g_warning ("%s: IPv4 prefix '%s' missing!",
			           __func__, item ? item : "<none>");
			goto out;
		}

		if (!parse_netmask (item, &prefix)) {
			g_warning ("%s: IPv4 prefix '%s' invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		/* Gateway is optional... */
		gtk_tree_model_get (model, &tree_iter, COL_GATEWAY, &item, -1);
		if (item && !inet_aton (item, &tmp_gateway)) {
			g_warning ("%s: IPv4 gateway '%s' invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		addr = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 3);
		g_array_append_val (addr, tmp_addr.s_addr);
		g_array_append_val (addr, prefix);
		if (tmp_gateway.s_addr)
			g_array_append_val (addr, tmp_gateway.s_addr);
		else
			g_array_append_val (addr, empty_val);
		g_ptr_array_add (addresses, addr);

		iter_valid = gtk_tree_model_iter_next (model, &tree_iter);
	}

	/* Don't pass empty array to the setting */
	if (!addresses->len) {
		g_ptr_array_free (addresses, TRUE);
		addresses = NULL;
	}

	/* DNS servers */
	dns_servers = g_array_new (FALSE, FALSE, sizeof (guint));

	text = gtk_entry_get_text (GTK_ENTRY (priv->dns_servers));
	if (text && strlen (text)) {
		items = g_strsplit_set (text, ", ;:", 0);
		for (iter = items; *iter; iter++) {
			struct in_addr tmp_addr;
			char *stripped = g_strstrip (*iter);

			if (!strlen (stripped))
				continue;

			if (inet_pton (AF_INET, stripped, &tmp_addr))
				g_array_append_val (dns_servers, tmp_addr.s_addr);
			else {
				g_strfreev (items);
				goto out;
			}
		}
		g_strfreev (items);
	}

	/* Search domains */
	text = gtk_entry_get_text (GTK_ENTRY (priv->dns_searches));
	if (text && strlen (text)) {
		items = g_strsplit_set (text, ", ;:", 0);
		for (iter = items; *iter; iter++) {
			char *stripped = g_strstrip (*iter);

			if (strlen (stripped))
				search_domains = g_slist_prepend (search_domains, g_strdup (stripped));
		}

		if (items)
			g_strfreev (items);
	}

	search_domains = g_slist_reverse (search_domains);

	/* DHCP client ID */
	if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO)) {
		dhcp_client_id = gtk_entry_get_text (priv->dhcp_client_id);
		if (dhcp_client_id && !strlen (dhcp_client_id))
			dhcp_client_id = NULL;
	}

	/* Update setting */
	g_object_set (priv->setting,
				  NM_SETTING_IP4_CONFIG_METHOD, method,
				  NM_SETTING_IP4_CONFIG_ADDRESSES, addresses,
				  NM_SETTING_IP4_CONFIG_DNS, dns_servers,
				  NM_SETTING_IP4_CONFIG_DNS_SEARCH, search_domains,
				  NM_SETTING_IP4_CONFIG_IGNORE_AUTO_DNS, ignore_auto_dns,
				  NM_SETTING_IP4_CONFIG_DHCP_CLIENT_ID, dhcp_client_id,
				  NULL);
	valid = TRUE;

out:
	if (addresses) {
		g_ptr_array_foreach (addresses, (GFunc) free_one_addr, NULL);
		g_ptr_array_free (addresses, TRUE);
	}

	if (dns_servers)
		g_array_free (dns_servers, TRUE);

	g_slist_foreach (search_domains, (GFunc) g_free, NULL);
	g_slist_free (search_domains);

	return valid;
}
예제 #24
0
GList *
get_interface_list(int *err, char **err_str)
{
	GList  *il = NULL;
	gint    nonloopback_pos = 0;
	struct  ifreq *ifr, *last;
	struct  ifconf ifc;
	struct  ifreq ifrflags;
	int     sock = socket(AF_INET, SOCK_DGRAM, 0);
	struct search_user_data user_data;
	pcap_t *pch;
	int len, lastlen;
	char *buf;
	if_info_t *if_info;
	char errbuf[PCAP_ERRBUF_SIZE];
	gboolean loopback;

	if (sock < 0) {
		*err = CANT_GET_INTERFACE_LIST;
		if (err_str != NULL) {
			*err_str = g_strdup_printf(
			    "Can't get list of interfaces: error opening socket: %s",
			    g_strerror(errno));
		}
		return NULL;
	}

	/*
	 * This code came from: W. Richard Stevens: "UNIX Network Programming",
	 * Networking APIs: Sockets and XTI, Vol 1, page 434.
	 */
	lastlen = 0;
	len = 100 * sizeof(struct ifreq);
	for ( ; ; ) {
		buf = (char *)g_malloc(len);
		ifc.ifc_len = len;
		ifc.ifc_buf = buf;
		memset (buf, 0, len);
		if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) {
			if (errno != EINVAL || lastlen != 0) {
				if (err_str != NULL) {
					*err_str = g_strdup_printf(
					    "Can't get list of interfaces: SIOCGIFCONF ioctl error: %s",
					    g_strerror(errno));
				}
				goto fail;
			}
		} else {
			if ((unsigned int) ifc.ifc_len < sizeof(struct ifreq)) {
				if (err_str != NULL) {
					*err_str = g_strdup(
					    "Can't get list of interfaces: SIOCGIFCONF ioctl gave too small return buffer");
				}
				goto fail;
			}
			if (ifc.ifc_len == lastlen)
				break;			/* success, len has not changed */
			lastlen = ifc.ifc_len;
		}
		len += 10 * sizeof(struct ifreq);	/* increment */
		g_free(buf);
	}
	ifr = (struct ifreq *) ifc.ifc_req;
	last = (struct ifreq *) ((char *) ifr + ifc.ifc_len);
	while (ifr < last) {
		/*
		 * Skip entries that begin with "dummy", or that include
		 * a ":" (the latter are Solaris virtuals).
		 */
		if (strncmp(ifr->ifr_name, "dummy", 5) == 0 ||
		    strchr(ifr->ifr_name, ':') != NULL)
			goto next;

		/*
		 * If we already have this interface name on the list,
		 * don't add it, but, if we don't already have an IP
		 * address for it, add that address (SIOCGIFCONF returns,
		 * at least on BSD-flavored systems, one entry per
		 * interface *address*; if an interface has multiple
		 * addresses, we get multiple entries for it).
		 */
		user_data.name = ifr->ifr_name;
		user_data.if_info = NULL;
		g_list_foreach(il, search_for_if_cb, &user_data);
		if (user_data.if_info != NULL) {
			if_info_add_address(user_data.if_info, &ifr->ifr_addr);
			if (user_data.if_info->addrs) {
				g_slist_reverse(user_data.if_info->addrs);
			}
			goto next;
		}

		/*
		 * Get the interface flags.
		 */
		memset(&ifrflags, 0, sizeof ifrflags);
		g_strlcpy(ifrflags.ifr_name, ifr->ifr_name,
		    sizeof ifrflags.ifr_name);
		if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
			if (errno == ENXIO)
				goto next;
			if (err_str != NULL) {
				*err_str = g_strdup_printf(
				    "Can't get list of interfaces: SIOCGIFFLAGS error getting flags for interface %s: %s",
				    ifr->ifr_name, g_strerror(errno));
			}
			goto fail;
		}

		/*
		 * Skip interfaces that aren't up.
		 */
		if (!(ifrflags.ifr_flags & IFF_UP))
			goto next;

		/*
		 * Skip interfaces that we can't open with "libpcap".
		 * Open with the minimum packet size - it appears that the
		 * IRIX SIOCSNOOPLEN "ioctl" may fail if the capture length
		 * supplied is too large, rather than just truncating it.
		 */
		pch = pcap_open_live(ifr->ifr_name, MIN_PACKET_SIZE, 0, 0,
		    errbuf);
		if (pch == NULL)
			goto next;
		pcap_close(pch);

		/*
		 * If it's a loopback interface, add it at the end of the
		 * list, otherwise add it after the last non-loopback
		 * interface, so all loopback interfaces go at the end - we
		 * don't want a loopback interface to be the default capture
		 * device unless there are no non-loopback devices.
		 */
		loopback = ((ifrflags.ifr_flags & IFF_LOOPBACK) ||
		    strncmp(ifr->ifr_name, "lo", 2) == 0);
		if_info = if_info_new(ifr->ifr_name, NULL, loopback);
		if_info_add_address(if_info, &ifr->ifr_addr);
		if (if_info->addrs) {
			g_slist_reverse(if_info->addrs);
		}
		if (loopback)
			il = g_list_append(il, if_info);
		else {
			il = g_list_insert(il, if_info, nonloopback_pos);
			/*
			 * Insert the next non-loopback interface after this
			 * one.
			 */
			nonloopback_pos++;
		}

	next:
#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
		ifr = (struct ifreq *) ((char *) ifr +
		    (ifr->ifr_addr.sa_len > sizeof(ifr->ifr_addr) ?
			ifr->ifr_addr.sa_len : sizeof(ifr->ifr_addr)) +
		    IFNAMSIZ);
#else
		ifr = (struct ifreq *) ((char *) ifr + sizeof(struct ifreq));
#endif
	}

#ifdef linux
	/*
	 * OK, maybe we have support for the "any" device, to do a cooked
	 * capture on all interfaces at once.
	 * Try opening it and, if that succeeds, add it to the end of
	 * the list of interfaces.
	 */
	pch = pcap_open_live("any", MIN_PACKET_SIZE, 0, 0, errbuf);
	if (pch != NULL) {
		/*
		 * It worked; we can use the "any" device.
		 */
		if_info = if_info_new("any",
		    "Pseudo-device that captures on all interfaces", FALSE);
		il = g_list_insert(il, if_info, -1);
		pcap_close(pch);
	}
#endif

	g_free(ifc.ifc_buf);
	close(sock);

	if (il == NULL) {
		/*
		 * No interfaces found.
		 */
		*err = 0;
		if (err_str != NULL)
			*err_str = NULL;
	}
	return il;

fail:
	if (il != NULL)
		free_interface_list(il);
	g_free(ifc.ifc_buf);
	close(sock);
	*err = CANT_GET_INTERFACE_LIST;
	return NULL;
}
예제 #25
0
/** \brief Create and show ground track for a satellite.
 *  \param satmap The satellite map widget.
 *  \param sat Pointer to the satellite object.
 *  \param qth Pointer to the QTH data.
 *  \param obj the satellite object.
 *  
 * Gpredict allows the user to require the ground track for any number of orbits
 * ahead. Therfore, the resulting ground track may cross the map boundaries many
 * times, and using one single polyline for the whole ground track would look very
 * silly. To avoid this, the points will be split into several polylines.
 *
 */
void
ground_track_create (GtkSatMap *satmap, sat_t *sat, qth_t *qth, sat_map_obj_t *obj)
{
     long  this_orbit;  /* current orbit number */
     long  max_orbit;   /* target orbit number, ie. this + num - 1 */
     double         t0;          /* time when this_orbit starts */
     double         t;
     ssp_t         *this_ssp;


     sat_log_log (SAT_LOG_LEVEL_DEBUG,
                     _("%s: Creating ground track for %s"),
                 __FUNCTION__, sat->nickname);

     /* just to be safe... if empty GSList is not NULL => segfault */
     obj->track_data.latlon = NULL;

     /* get configuration parameters */
     this_orbit = sat->orbit;
     max_orbit = sat->orbit -1 + mod_cfg_get_int (satmap->cfgdata,
                                                             MOD_CFG_MAP_SECTION,
                                                             MOD_CFG_MAP_TRACK_NUM,
                                                             SAT_CFG_INT_MAP_TRACK_NUM);

                               
     sat_log_log (SAT_LOG_LEVEL_DEBUG,
                     _("%s: Start orbit: %d"),
                     __FUNCTION__, this_orbit);
     sat_log_log (SAT_LOG_LEVEL_DEBUG,
                     _("%s: End orbit %d"),
                     __FUNCTION__, max_orbit);


     /* find the time when the current orbit started */

     /* Iterate backwards in time until we reach sat->orbit < this_orbit.
        Use predict_calc from predict-tools.c as SGP/SDP driver.
        As a built-in safety, we stop iteration if the orbit crossing is
        more than 24 hours back in time.
     */
     t0 = satmap->tstamp;//get_current_daynum ();
     /* use == instead of >= as it is more robust */
     for (t = t0; (sat->orbit == this_orbit) && ((t + 1.0) > t0); t -= 0.0007) {

          predict_calc (sat, qth, t);

     }

     /* set it so that we are in the same orbit as this_orbit
        and not a different one */
     t += 2*0.0007;
     t0 = t;     
     predict_calc (sat, qth, t0);

     sat_log_log (SAT_LOG_LEVEL_DEBUG,
                     _("%s: T0: %f (%d)"),
                     __FUNCTION__, t0, sat->orbit);


     /* calculate (lat,lon) for the required orbits */
     while ((sat->orbit <= max_orbit) &&
            (sat->orbit >= this_orbit) &&
            (!decayed(sat))) {

          /* We use 30 sec time steps. If resolution is too fine, the
             line drawing routine will filter out unnecessary points
          */
          t += 0.00035;
          predict_calc (sat, qth, t);

          /* store this SSP */

          /* Note: g_slist_append() has to traverse the entire list to find the end, which
             is inefficient when adding multiple elements. Therefore, we use g_slist_prepend()
             and reverse the entire list when we are done.
          */
          this_ssp = g_try_new (ssp_t, 1);

          if (this_ssp == NULL) {
               sat_log_log (SAT_LOG_LEVEL_ERROR,
                               _("%s: MAYDAY: Insufficient memory for ground track!"),
                               __FUNCTION__);
               return;
          }
          
          this_ssp->lat = sat->ssplat;
          this_ssp->lon = sat->ssplon;
          obj->track_data.latlon = g_slist_prepend (obj->track_data.latlon, this_ssp);
          
     }
     /* log if there is a problem with the orbit calculation */
     if (sat->orbit != (max_orbit+1)) {
         sat_log_log (SAT_LOG_LEVEL_ERROR,
                      _("%s: Problem computing ground track for %s"),
                      __FUNCTION__, sat->nickname);
         return;
     }
     

     /* Reset satellite structure to eliminate glitches in single sat 
        view and other places when new ground track is layed out */
     predict_calc(sat, qth, satmap->tstamp);

     /* reverse GSList */
     obj->track_data.latlon = g_slist_reverse (obj->track_data.latlon);

     /* split points into polylines */
     create_polylines (satmap, sat, qth, obj);

     /* misc book-keeping */
     obj->track_orbit = this_orbit;

}
예제 #26
0
GSList *
eab_contact_list_from_string (const gchar *str)
{
	GSList *contacts = NULL;
	GString *gstr = g_string_new (NULL);
	gchar *str_stripped;
	gchar *p = (gchar *) str;
	gchar *q;

	if (!p)
		return NULL;

	if (!strncmp (p, "Book: ", 6)) {
		p = strchr (p, '\n');
		if (!p) {
			g_warning (G_STRLOC ": Got book but no newline!");
			return NULL;
		}
		p++;
	}

	while (*p) {
		if (*p != '\r') g_string_append_c (gstr, *p);

		p++;
	}

	p = str_stripped = g_string_free (gstr, FALSE);

	/* Note: The vCard standard says
	 *
	 * vcard = "BEGIN" [ws] ":" [ws] "VCARD" [ws] 1*CRLF
	 *         items *CRLF "END" [ws] ":" [ws] "VCARD"
	 *
	 * which means we can have whitespace (e.g. "BEGIN : VCARD"). So we're not being
	 * fully compliant here, although I'm not sure it matters. The ideal solution
	 * would be to have a vcard parsing function that returned the end of the vcard
	 * parsed. Arguably, contact list parsing should all be in libebook's e-vcard.c,
	 * where we can do proper parsing and validation without code duplication. */

	for (p = eab_strstrcase (p, "BEGIN:VCARD"); p; p = eab_strstrcase (q, "\nBEGIN:VCARD")) {
		gchar *card_str;

		if (*p == '\n')
			p++;

		for (q = eab_strstrcase (p, "END:VCARD"); q; q = eab_strstrcase (q, "END:VCARD")) {
			gchar *temp;

			q += 9;
			temp = q;
			if (*temp)
				temp += strspn (temp, "\r\n\t ");

			if (*temp == '\0' || !g_ascii_strncasecmp (temp, "BEGIN:VCARD", 11))
				break;  /* Found the outer END:VCARD */
		}

		if (!q)
			break;

		card_str = g_strndup (p, q - p);
		contacts = g_slist_prepend (contacts, e_contact_new_from_vcard (card_str));
		g_free (card_str);
	}

	g_free (str_stripped);

	return g_slist_reverse (contacts);
}
예제 #27
0
gint load_planes(gchar *filename, struct model_pak *data)
{
gint h, k, l, num_tokens;
gint cflag=FALSE, sflag=FALSE, gflag=FALSE;
gdouble m[3];
gchar **buff;
GSList *list, *new_planes;
struct plane_pak *plane=NULL;
struct shift_pak *shift=NULL;
FILE *fp;

fp = fopen(filename, "rt");
if (!fp)
  return(1);

/* get next line */
new_planes = NULL;
for (;;)
  {
  buff = get_tokenized_line(fp, &num_tokens);
  if (!buff)
    break;

/* NB: only update space/cell etc. data if this call did */
/* not originate from an import planes call */
  if (data->id == MORPH)
    {
/* cell parameters */
    if (g_ascii_strncasecmp(*buff,"cell",4) == 0)
      {
      if (num_tokens >= 7)
        {
        cflag=TRUE;
        data->pbc[0] = str_to_float(*(buff+1));
        data->pbc[1] = str_to_float(*(buff+2));
        data->pbc[2] = str_to_float(*(buff+3));
        data->pbc[3] = PI*str_to_float(*(buff+4))/180.0;
        data->pbc[4] = PI*str_to_float(*(buff+5))/180.0;
        data->pbc[5] = PI*str_to_float(*(buff+6))/180.0;
/* compute direct & reciprocal lattices */
/* NB: enables fn_make_plane() to correctly compute Dhkl */
        matrix_lattice_init(data);
        }
      else
        printf("load_planes() error: bad cell line.\n");
      }

/* space group */
    if (g_ascii_strncasecmp(*buff,"space",5) == 0)
      {
      if (num_tokens > 1)
        {
      sflag=TRUE;
      data->sginfo.spacename = g_strjoinv(" ", buff+1);
      data->sginfo.spacenum = 0;
        }
      }

/* default morphology type */
    if (g_ascii_strncasecmp(*buff, "morph", 5) == 0)
      {
      if (num_tokens >= 3)
        {
        if (g_ascii_strncasecmp(*(buff+1), "unrelaxed", 9) == 0)
          {
          if (g_ascii_strncasecmp(*(buff+2), "equil", 5) == 0)
            data->morph_type = EQUIL_UN;
          if (g_ascii_strncasecmp(*(buff+2), "growth", 6) == 0)
            data->morph_type = GROWTH_UN;
          }
  
        if (g_ascii_strncasecmp(*(buff+1), "relaxed", 7) == 0)
          {
          if (g_ascii_strncasecmp(*(buff+2), "equil", 5) == 0)
            data->morph_type = EQUIL_RE;
          if (g_ascii_strncasecmp(*(buff+2), "growth", 6) == 0)
            data->morph_type = GROWTH_RE;
          }
        }
      else
        printf("load_planes() error: bad type line.\n");
      }
    }

/* process miller line */
  if (g_ascii_strncasecmp(*buff,"miller",6) == 0)
    {
/* init space group (latmat? - if so, remove the make_latmat() in cell parse) */
    if (cflag && sflag)
      {
      if (!gflag)
        {
        if (space_lookup(data))
          printf("Error in space group lookup.\n");
        gflag = TRUE;
        }
      }
    else
      {
      if (data->id == MORPH)
        {
        printf("load_planes() error: miller encountered before space or cell.\n");
        return(2);
        }
      }

    if (num_tokens >= 4)
      {
      h = (gint) str_to_float(*(buff+1));
      k = (gint) str_to_float(*(buff+2));
      l = (gint) str_to_float(*(buff+3));
#if DEBUG_LOAD_PLANES
printf("read plane: %d %d %d\n", h, k, l);
#endif
      VEC3SET(m, h, k, l);
/* FIXME - signature change */
/*
      plane = plane_find(m, data);
*/

      if (!plane)
        {
        plane = plane_new(m, data);
        if (plane)
          new_planes = g_slist_prepend(new_planes, plane);
        }
      }
    }

/* potential data */
  if (num_tokens >= 8 && plane)
    {
/* NB: use create_shift(), as it sets some important defaults */
    shift = shift_new(0.0);
    if (shift)
      {
      shift->shift = str_to_float(*(buff+0));
      shift->region[0] = str_to_float(*(buff+1));
      shift->region[1] = str_to_float(*(buff+2));
      shift->esurf[0] = str_to_float(*(buff+3));
      shift->eatt[0] = str_to_float(*(buff+4));
      shift->esurf[1] = str_to_float(*(buff+5));
      shift->eatt[1] = str_to_float(*(buff+6));
      shift->gnorm = str_to_float(*(buff+7));
#if DEBUG_LOAD_PLANES
printf("adding shift: %f\n", shift->shift);
#endif
/* append to preserve order (eg import on existing plane set) */
      plane->shifts = g_slist_append(plane->shifts, shift);
      }
    }
  g_strfreev(buff);
  }
data->planes = g_slist_concat(data->planes, g_slist_reverse(new_planes));

/* compute dhkl's for the plane's list */
for (list=data->planes ; list ; list=g_slist_next(list))
  {
  plane = list->data;

/* create default shift if none found */
  if (!plane->shifts)
    {
    shift = shift_new(0.0);
    if (shift)
      plane->shifts = g_slist_append(plane->shifts, shift);
    }
/* get best energy for the plane */
/* FIXME - signature changed */
/*
  update_plane_energy(plane, data);
*/
  }

/* compute symmetry related faces */
/* FIXME - new surface rewrite */
/*
surf_symmetry_generate(data);
*/

fclose(fp);
return(0);
}
예제 #28
0
static void
calendar_sources_load_esource_list (CalendarSourceData *source_data)
{
  GSList  *clients = NULL;
  GSList  *groups, *l;
  gboolean emit_signal = FALSE;

  g_return_if_fail (source_data->esource_list != NULL);

  debug_dump_selected_sources (source_data->selected_sources);

  dprintf ("Source groups:\n");
  groups = e_source_list_peek_groups (source_data->esource_list);
  for (l = groups; l; l = l->next)
    {
      GSList *esources, *s;

      dprintf ("  %s\n", e_source_group_peek_uid (l->data));
      dprintf ("    sources:\n");

      esources = e_source_group_peek_sources (l->data);
      for (s = esources; s; s = s->next)
	{
	  ESource *esource = E_SOURCE (s->data);
	  ECal    *client;

	  dprintf ("      type = '%s' uid = '%s', name = '%s', relative uri = '%s': \n",
                   source_data->source_type == E_CAL_SOURCE_TYPE_EVENT ? "appointment" : "task",
		   e_source_peek_uid (esource),
		   e_source_peek_name (esource),
		   e_source_peek_relative_uri (esource));

	  if (is_source_selected (esource, source_data->selected_sources) &&
	      (client = get_ecal_from_source (esource, source_data->source_type, source_data->clients)))
	    {
	      clients = g_slist_prepend (clients, client);
	    }
	}
    }
  dprintf ("\n");

  if (source_data->loaded && 
      !compare_ecal_lists (source_data->clients, clients))
    emit_signal = TRUE;

  for (l = source_data->clients; l; l = l->next)
    {
      g_signal_handlers_disconnect_by_func (G_OBJECT (l->data),
                                            G_CALLBACK (backend_died_cb),
                                            source_data);

      g_object_unref (l->data);
    }
  g_slist_free (source_data->clients);
  source_data->clients = g_slist_reverse (clients);

  /* connect to backend_died after we disconnected the previous signal
   * handlers. If we do it before, we'll lose some handlers (for clients that
   * were already there before) */
  for (l = source_data->clients; l; l = l->next)
    {
      g_signal_connect (G_OBJECT (l->data), "backend_died",
                        G_CALLBACK (backend_died_cb), source_data);
    }

  if (emit_signal) 
    {
      dprintf ("Emitting %s-sources-changed signal\n",
	       source_data->source_type == E_CAL_SOURCE_TYPE_EVENT ? "appointment" : "task");
      g_signal_emit (source_data->sources, source_data->changed_signal, 0);
    }

  debug_dump_ecal_list (source_data->clients);
}
예제 #29
0
/**
 * gtk_text_buffer_deserialize:
 * @register_buffer: the #GtkTextBuffer @format is registered with
 * @content_buffer: the #GtkTextBuffer to deserialize into
 * @format: the rich text format to use for deserializing
 * @iter: insertion point for the deserialized text
 * @data: (array length=length): data to deserialize
 * @length: length of @data
 * @error: return location for a #GError
 *
 * This function deserializes rich text in format @format and inserts
 * it at @iter.
 *
 * @format<!-- -->s to be used must be registered using
 * gtk_text_buffer_register_deserialize_format() or
 * gtk_text_buffer_register_deserialize_tagset() beforehand.
 *
 * Return value: %TRUE on success, %FALSE otherwise.
 *
 * Since: 2.10
 **/
gboolean
gtk_text_buffer_deserialize (GtkTextBuffer  *register_buffer,
                             GtkTextBuffer  *content_buffer,
                             GdkAtom         format,
                             GtkTextIter    *iter,
                             const guint8   *data,
                             gsize           length,
                             GError        **error)
{
  GList    *formats;
  GList    *list;

  g_return_val_if_fail (GTK_IS_TEXT_BUFFER (register_buffer), FALSE);
  g_return_val_if_fail (GTK_IS_TEXT_BUFFER (content_buffer), FALSE);
  g_return_val_if_fail (format != GDK_NONE, FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (data != NULL, FALSE);
  g_return_val_if_fail (length > 0, FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  formats = g_object_get_qdata (G_OBJECT (register_buffer),
                                deserialize_quark ());

  for (list = formats; list; list = g_list_next (list))
    {
      GtkRichTextFormat *fmt = list->data;

      if (fmt->atom == format)
        {
          GtkTextBufferDeserializeFunc function = fmt->function;
          gboolean                     success;
          GSList                      *split_tags;
          GSList                      *list;
          GtkTextMark                 *left_end        = NULL;
          GtkTextMark                 *right_start     = NULL;
          GSList                      *left_start_list = NULL;
          GSList                      *right_end_list  = NULL;

          /*  We don't want the tags that are effective at the insertion
           *  point to affect the pasted text, therefore we remove and
           *  remember them, so they can be re-applied left and right of
           *  the inserted text after pasting
           */
          split_tags = gtk_text_iter_get_tags (iter);

          list = split_tags;
          while (list)
            {
              GtkTextTag *tag = list->data;

              list = g_slist_next (list);

              /*  If a tag begins at the insertion point, ignore it
               *  because it doesn't affect the pasted text
               */
              if (gtk_text_iter_begins_tag (iter, tag))
                split_tags = g_slist_remove (split_tags, tag);
            }

          if (split_tags)
            {
              /*  Need to remember text marks, because text iters
               *  don't survive pasting
               */
              left_end = gtk_text_buffer_create_mark (content_buffer,
                                                      NULL, iter, TRUE);
              right_start = gtk_text_buffer_create_mark (content_buffer,
                                                         NULL, iter, FALSE);

              for (list = split_tags; list; list = g_slist_next (list))
                {
                  GtkTextTag  *tag             = list->data;
                  GtkTextIter *backward_toggle = gtk_text_iter_copy (iter);
                  GtkTextIter *forward_toggle  = gtk_text_iter_copy (iter);
                  GtkTextMark *left_start      = NULL;
                  GtkTextMark *right_end       = NULL;

                  gtk_text_iter_backward_to_tag_toggle (backward_toggle, tag);
                  left_start = gtk_text_buffer_create_mark (content_buffer,
                                                            NULL,
                                                            backward_toggle,
                                                            FALSE);

                  gtk_text_iter_forward_to_tag_toggle (forward_toggle, tag);
                  right_end = gtk_text_buffer_create_mark (content_buffer,
                                                           NULL,
                                                           forward_toggle,
                                                           TRUE);

                  left_start_list = g_slist_prepend (left_start_list, left_start);
                  right_end_list = g_slist_prepend (right_end_list, right_end);

                  gtk_text_buffer_remove_tag (content_buffer, tag,
                                              backward_toggle,
                                              forward_toggle);

                  gtk_text_iter_free (forward_toggle);
                  gtk_text_iter_free (backward_toggle);
                }

              left_start_list = g_slist_reverse (left_start_list);
              right_end_list = g_slist_reverse (right_end_list);
            }

          success = function (register_buffer, content_buffer,
                              iter, data, length,
                              fmt->can_create_tags,
                              fmt->user_data,
                              error);

          if (!success && error != NULL && *error == NULL)
            g_set_error (error, 0, 0,
                         _("Unknown error when trying to deserialize %s"),
                         gdk_atom_name (format));

          if (split_tags)
            {
              GSList      *left_list;
              GSList      *right_list;
              GtkTextIter  left_e;
              GtkTextIter  right_s;

              /*  Turn the remembered marks back into iters so they
               *  can by used to re-apply the remembered tags
               */
              gtk_text_buffer_get_iter_at_mark (content_buffer,
                                                &left_e, left_end);
              gtk_text_buffer_get_iter_at_mark (content_buffer,
                                                &right_s, right_start);

              for (list = split_tags,
                     left_list = left_start_list,
                     right_list = right_end_list;
                   list && left_list && right_list;
                   list = g_slist_next (list),
                     left_list = g_slist_next (left_list),
                     right_list = g_slist_next (right_list))
                {
                  GtkTextTag  *tag        = list->data;
                  GtkTextMark *left_start = left_list->data;
                  GtkTextMark *right_end  = right_list->data;
                  GtkTextIter  left_s;
                  GtkTextIter  right_e;

                  gtk_text_buffer_get_iter_at_mark (content_buffer,
                                                    &left_s, left_start);
                  gtk_text_buffer_get_iter_at_mark (content_buffer,
                                                    &right_e, right_end);

                  gtk_text_buffer_apply_tag (content_buffer, tag,
                                             &left_s, &left_e);
                  gtk_text_buffer_apply_tag (content_buffer, tag,
                                             &right_s, &right_e);

                  gtk_text_buffer_delete_mark (content_buffer, left_start);
                  gtk_text_buffer_delete_mark (content_buffer, right_end);
                }

              gtk_text_buffer_delete_mark (content_buffer, left_end);
              gtk_text_buffer_delete_mark (content_buffer, right_start);

              g_slist_free (split_tags);
              g_slist_free (left_start_list);
              g_slist_free (right_end_list);
            }

          return success;
        }
    }

  g_set_error (error, 0, 0,
               _("No deserialize function found for format %s"),
               gdk_atom_name (format));

  return FALSE;
}
예제 #30
0
enum command_return
client_process_line(struct client *client, char *line)
{
	enum command_return ret;

	if (strcmp(line, "noidle") == 0) {
		if (client->idle_waiting) {
			/* send empty idle response and leave idle mode */
			client->idle_waiting = false;
			command_success(client);
			client_write_output(client);
		}

		/* do nothing if the client wasn't idling: the client
		   has already received the full idle response from
		   client_idle_notify(), which he can now evaluate */

		return COMMAND_RETURN_OK;
	} else if (client->idle_waiting) {
		/* during idle mode, clients must not send anything
		   except "noidle" */
		g_warning("[%u] command \"%s\" during idle",
			  client->num, line);
		return COMMAND_RETURN_CLOSE;
	}

	if (client->cmd_list_OK >= 0) {
		if (strcmp(line, CLIENT_LIST_MODE_END) == 0) {
			g_debug("[%u] process command list",
				client->num);

			/* for scalability reasons, we have prepended
			   each new command; now we have to reverse it
			   to restore the correct order */
			client->cmd_list = g_slist_reverse(client->cmd_list);

			ret = client_process_command_list(client,
							  client->cmd_list_OK,
							  client->cmd_list);
			g_debug("[%u] process command "
				"list returned %i", client->num, ret);

			if (ret == COMMAND_RETURN_CLOSE ||
			    client_is_expired(client))
				return COMMAND_RETURN_CLOSE;

			if (ret == COMMAND_RETURN_OK)
				command_success(client);

			client_write_output(client);
			free_cmd_list(client->cmd_list);
			client->cmd_list = NULL;
			client->cmd_list_OK = -1;
		} else {
			size_t len = strlen(line) + 1;
			client->cmd_list_size += len;
			if (client->cmd_list_size >
			    client_max_command_list_size) {
				g_warning("[%u] command list size (%lu) "
					  "is larger than the max (%lu)",
					  client->num,
					  (unsigned long)client->cmd_list_size,
					  (unsigned long)client_max_command_list_size);
				return COMMAND_RETURN_CLOSE;
			}

			new_cmd_list_ptr(client, line);
			ret = COMMAND_RETURN_OK;
		}
	} else {
		if (strcmp(line, CLIENT_LIST_MODE_BEGIN) == 0) {
			client->cmd_list_OK = 0;
			ret = COMMAND_RETURN_OK;
		} else if (strcmp(line, CLIENT_LIST_OK_MODE_BEGIN) == 0) {
			client->cmd_list_OK = 1;
			ret = COMMAND_RETURN_OK;
		} else {
			g_debug("[%u] process command \"%s\"",
				client->num, line);
			ret = command_process(client, 0, line);
			g_debug("[%u] command returned %i",
				client->num, ret);

			if (ret == COMMAND_RETURN_CLOSE ||
			    client_is_expired(client))
				return COMMAND_RETURN_CLOSE;

			if (ret == COMMAND_RETURN_OK)
				command_success(client);

			client_write_output(client);
		}
	}

	return ret;
}