示例#1
0
static gboolean
cogl_create_context ()
{
  GLubyte default_texture_data[] = { 0xff, 0xff, 0xff, 0x0 };
  gulong  enable_flags = 0;
  CoglDrawBufferState *draw_buffer;

  if (_context != NULL)
    return FALSE;

  /* Allocate context memory */
  _context = (CoglContext*) g_malloc (sizeof (CoglContext));

  /* Init default values */
  _context->feature_flags = 0;
  _context->features_cached = FALSE;

  _context->enable_flags = 0;
  _context->color_alpha = 0;

  _context->enable_backface_culling = FALSE;

  _context->indirect = gl_is_indirect;

  _context->default_material = cogl_material_new ();
  _context->source_material = NULL;

  _context->default_gl_texture_2d_tex = COGL_INVALID_HANDLE;
  _context->default_gl_texture_rect_tex = COGL_INVALID_HANDLE;

  _context->journal = g_array_new (FALSE, FALSE, sizeof (CoglJournalEntry));
  _context->logged_vertices = g_array_new (FALSE, FALSE, sizeof (GLfloat));
  _context->journal_vbo = 0;
  _context->journal_vbo_len = 0;

  _context->current_material = NULL;
  _context->current_material_flags = 0;
  memset (&_context->current_material_flush_options,
          0, sizeof (CoglMaterialFlushOptions));
  _context->current_layers = g_array_new (FALSE, FALSE,
                                          sizeof (CoglLayerInfo));
  _context->n_texcoord_arrays_enabled = 0;

  draw_buffer = g_slice_new0 (CoglDrawBufferState);
  draw_buffer->target = COGL_WINDOW_BUFFER;
  draw_buffer->offscreen = COGL_INVALID_HANDLE;
  _context->draw_buffer_stack =
    g_slist_prepend (NULL, draw_buffer);

  _context->path_nodes = g_array_new (FALSE, FALSE, sizeof (CoglPathNode));
  _context->last_path = 0;
  _context->stencil_material = cogl_material_new ();

  _context->in_begin_gl_block = FALSE;

  _context->viewport_width = 0;
  _context->viewport_height = 0;

  _context->pf_glGenRenderbuffersEXT = NULL;
  _context->pf_glBindRenderbufferEXT = NULL;
  _context->pf_glRenderbufferStorageEXT = NULL;
  _context->pf_glGenFramebuffersEXT = NULL;
  _context->pf_glBindFramebufferEXT = NULL;
  _context->pf_glFramebufferTexture2DEXT = NULL;
  _context->pf_glFramebufferRenderbufferEXT = NULL;
  _context->pf_glCheckFramebufferStatusEXT = NULL;
  _context->pf_glDeleteFramebuffersEXT = NULL;
  _context->pf_glBlitFramebufferEXT = NULL;
  _context->pf_glRenderbufferStorageMultisampleEXT = NULL;

  _context->pf_glCreateProgramObjectARB = NULL;
  _context->pf_glCreateShaderObjectARB = NULL;
  _context->pf_glShaderSourceARB = NULL;
  _context->pf_glCompileShaderARB = NULL;
  _context->pf_glAttachObjectARB = NULL;
  _context->pf_glLinkProgramARB = NULL;
  _context->pf_glUseProgramObjectARB = NULL;
  _context->pf_glGetUniformLocationARB = NULL;
  _context->pf_glDeleteObjectARB = NULL;
  _context->pf_glGetInfoLogARB = NULL;
  _context->pf_glGetObjectParameterivARB = NULL;
  _context->pf_glUniform1fARB = NULL;
  _context->pf_glUniform2fARB = NULL;
  _context->pf_glUniform3fARB = NULL;
  _context->pf_glUniform4fARB = NULL;
  _context->pf_glUniform1fvARB = NULL;
  _context->pf_glUniform2fvARB = NULL;
  _context->pf_glUniform3fvARB = NULL;
  _context->pf_glUniform4fvARB = NULL;
  _context->pf_glUniform1iARB = NULL;
  _context->pf_glUniform2iARB = NULL;
  _context->pf_glUniform3iARB = NULL;
  _context->pf_glUniform4iARB = NULL;
  _context->pf_glUniform1ivARB = NULL;
  _context->pf_glUniform2ivARB = NULL;
  _context->pf_glUniform3ivARB = NULL;
  _context->pf_glUniform4ivARB = NULL;
  _context->pf_glUniformMatrix2fvARB = NULL;
  _context->pf_glUniformMatrix3fvARB = NULL;
  _context->pf_glUniformMatrix4fvARB = NULL;

  _context->pf_glDrawRangeElements = NULL;
  _context->pf_glActiveTexture = NULL;
  _context->pf_glClientActiveTexture = NULL;

  _context->pf_glBlendFuncSeparate = NULL;
  _context->pf_glBlendEquationSeparate = NULL;

  /* Initialise the clip stack */
  _cogl_clip_stack_state_init ();

  /* Initialise matrix stack */
  _cogl_current_matrix_state_init ();

  /* Create default textures used for fall backs */
  _context->default_gl_texture_2d_tex =
    cogl_texture_new_from_data (1, /* width */
                                1, /* height */
                                COGL_TEXTURE_NO_SLICING,
                                COGL_PIXEL_FORMAT_RGBA_8888_PRE, /* data format */
                                /* internal format */
                                COGL_PIXEL_FORMAT_RGBA_8888_PRE,
                                0, /* auto calc row stride */
                                default_texture_data);
  _context->default_gl_texture_rect_tex =
    cogl_texture_new_from_data (1, /* width */
                                1, /* height */
                                COGL_TEXTURE_NO_SLICING,
                                COGL_PIXEL_FORMAT_RGBA_8888_PRE, /* data format */
                                /* internal format */
                                COGL_PIXEL_FORMAT_RGBA_8888_PRE,
                                0, /* auto calc row stride */
                                default_texture_data);

  cogl_set_source (_context->default_material);
  _cogl_material_flush_gl_state (_context->source_material, NULL);
  enable_flags =
    _cogl_material_get_cogl_enable_flags (_context->source_material);
  cogl_enable (enable_flags);

  _context->quad_indices_byte = COGL_INVALID_HANDLE;
  _context->quad_indices_short = COGL_INVALID_HANDLE;
  _context->quad_indices_short_len = 0;

  return TRUE;
}
void
bastile_keyserver_sync (GList *keys)
{
    BastileSource *sksrc;
    BastileSource *lsksrc;
    BastileMultiOperation *mop;
    BastileOperation *op;
    gchar *keyserver;
    GSList *ks, *l;
    GList *k;
    GSList *keyids = NULL;
    
    if (!keys)
        return;
    
    g_assert (BASTILE_IS_OBJECT (keys->data));
    
    /* Build a keyid list */
    for (k = keys; k; k = g_list_next (k)) 
        keyids = g_slist_prepend (keyids, 
                    GUINT_TO_POINTER (bastile_object_get_id (BASTILE_OBJECT (k->data))));

    mop = bastile_multi_operation_new ();

    /* And now synchronizing keys from the servers */
    ks = bastile_servers_get_uris ();
    
    for (l = ks; l; l = g_slist_next (l)) {
        
        sksrc = bastile_context_remote_source (SCTX_APP (), (const gchar*)(l->data));

        /* This can happen if the URI scheme is not supported */
        if (sksrc == NULL)
            continue;
        
        lsksrc = bastile_context_find_source (SCTX_APP (), 
                        bastile_source_get_tag (sksrc), BASTILE_LOCATION_LOCAL);
        
        if (lsksrc) {
            op = bastile_transfer_operation_new (_("Synchronizing keys"), sksrc, lsksrc, keyids);
            g_return_if_fail (op != NULL);

            bastile_multi_operation_take (mop, op);
            bastile_operation_watch (op, (BastileDoneFunc) sync_export_complete, sksrc, NULL, NULL);
        }
    }
    
    bastile_util_string_slist_free (ks);
    
    /* Publishing keys online */    
    keyserver = bastile_mateconf_get_string (PUBLISH_TO_KEY);
    if (keyserver && keyserver[0]) {
        
        sksrc = bastile_context_remote_source (SCTX_APP (), keyserver);

        /* This can happen if the URI scheme is not supported */
        if (sksrc != NULL) {

            op = bastile_context_transfer_objects (SCTX_APP (), keys, sksrc);
            g_return_if_fail (sksrc != NULL);

            bastile_multi_operation_take (mop, op);
            bastile_operation_watch (op, (BastileDoneFunc) sync_import_complete, sksrc, NULL, NULL);

        }
    }

    g_slist_free (keyids);
    g_free (keyserver);
    
    /* Show the progress window if necessary */
    bastile_progress_show (BASTILE_OPERATION (mop), _("Synchronizing keys..."), FALSE);
    g_object_unref (mop);
}
示例#3
0
static GSList*
get_strut_list (int which)
{
    GSList *ans;
    MetaDirection wc = 0; /* wc == who cares? ;-) */

    ans = NULL;

    g_assert (which >=0 && which <= 6);
    switch (which)
    {
    case 0:
        break;
    case 1:
        ans = g_slist_prepend (ans, new_meta_strut (   0,    0, 1600,   20, wc));
        ans = g_slist_prepend (ans, new_meta_strut ( 400, 1160, 1600,   40, wc));
        break;
    case 2:
        ans = g_slist_prepend (ans, new_meta_strut (   0,    0, 1600,   20, wc));
        ans = g_slist_prepend (ans, new_meta_strut ( 800, 1100,  400,  100, wc));
        ans = g_slist_prepend (ans, new_meta_strut ( 300, 1150,  150,   50, wc));
        break;
    case 3:
        ans = g_slist_prepend (ans, new_meta_strut (   0,    0, 1600,   20, wc));
        ans = g_slist_prepend (ans, new_meta_strut ( 800, 1100,  400,  100, wc));
        ans = g_slist_prepend (ans, new_meta_strut ( 300, 1150,   80,   50, wc));
        ans = g_slist_prepend (ans, new_meta_strut ( 700,  525,  200,  150, wc));
        break;
    case 4:
        ans = g_slist_prepend (ans, new_meta_strut (   0,    0,  800, 1200, wc));
        ans = g_slist_prepend (ans, new_meta_strut ( 800,    0, 1600,   20, wc));
        break;
    case 5:
        ans = g_slist_prepend (ans, new_meta_strut ( 800,    0, 1600,   20, wc));
        ans = g_slist_prepend (ans, new_meta_strut (   0,    0,  800, 1200, wc));
        ans = g_slist_prepend (ans, new_meta_strut ( 800,   10,  800, 1200, wc));
        break;
    case 6:
        ans = g_slist_prepend (ans, new_meta_strut (   0,    0, 1600,   40, wc));
        ans = g_slist_prepend (ans, new_meta_strut (   0,    0, 1600,   20, wc));
        break;
    }

    return ans;
}
示例#4
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;
}
示例#5
0
static void statusbar_calc_item_positions(STATUSBAR_REC *bar)
{
        WINDOW_REC *old_active_win;
	GSList *tmp, *right_items;
	int xpos, rxpos;

	old_active_win = active_win;
        if (bar->parent_window != NULL)
		active_win = bar->parent_window->active;

	statusbar_resize_items(bar, term_width);

        /* left-aligned items */
	xpos = 0;
	for (tmp = bar->items; tmp != NULL; tmp = tmp->next) {
		SBAR_ITEM_REC *rec = tmp->data;

		if (!rec->config->right_alignment &&
		    (rec->size > 0 || rec->current_size > 0)) {
			if (SBAR_ITEM_REDRAW_NEEDED(bar, rec, xpos)) {
                                /* redraw the item */
				rec->dirty = TRUE;
				if (bar->dirty_xpos == -1 ||
				    xpos < bar->dirty_xpos) {
                                        irssi_set_dirty();
					bar->dirty = TRUE;
					bar->dirty_xpos = xpos;
				}

				rec->xpos = xpos;
			}
			xpos += rec->size;
		}
	}

	/* right-aligned items - first copy them to a new list backwards,
	   easier to draw them in right order */
        right_items = NULL;
	for (tmp = bar->items; tmp != NULL; tmp = tmp->next) {
		SBAR_ITEM_REC *rec = tmp->data;

		if (rec->config->right_alignment) {
                        if (rec->size > 0)
				right_items = g_slist_prepend(right_items, rec);
			else if (rec->current_size > 0 &&
				 (bar->dirty_xpos == -1 ||
				  rec->xpos < bar->dirty_xpos)) {
				/* item was hidden - set the dirty position
				   to begin from the item's old xpos */
				irssi_set_dirty();
				bar->dirty = TRUE;
                                bar->dirty_xpos = rec->xpos;
			}
		}
	}

	rxpos = term_width;
	for (tmp = right_items; tmp != NULL; tmp = tmp->next) {
		SBAR_ITEM_REC *rec = tmp->data;

		rxpos -= rec->size;
		if (SBAR_ITEM_REDRAW_NEEDED(bar, rec, rxpos)) {
			rec->dirty = TRUE;
			if (bar->dirty_xpos == -1 ||
			    rxpos < bar->dirty_xpos) {
				irssi_set_dirty();
				bar->dirty = TRUE;
				bar->dirty_xpos = rxpos;
			}
			rec->xpos = rxpos;
		}
	}
        g_slist_free(right_items);

	active_win = old_active_win;
}
示例#6
0
static InternalEvent *
cspi_internal_event_add (const InternalEvent *e)
{
  _cspi_event_queue = g_slist_prepend (_cspi_event_queue, (gpointer) e);
  return (InternalEvent *) e;
}
示例#7
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);
}
示例#8
0
static void
add_iso3166 (Layout *layout,
             gchar  *id)
{
  layout->iso3166Ids = g_slist_prepend (layout->iso3166Ids, id);
}
示例#9
0
void
find_window_r (guint32 pid, Window window, Display *display, Atom atom_pid, guint32 level, GSList **result)
{
	Atom actual_type_return;
	int actual_format_return;
	unsigned long nitems_return;
	unsigned long bytes_after_return;
	unsigned char *prop_return;
	guint32 pid_of_window = 0;
	XWindowAttributes window_attributes;
	WindowInfoEx *wix = NULL;
	WindowInfo *wi = NULL;
	Window dummy;
	int x, y;

	if (Success != XGetWindowProperty (display, window, atom_pid, 0, 1, False, XA_CARDINAL, &actual_type_return, &actual_format_return, &nitems_return, &bytes_after_return, &prop_return))
		return;

	if (prop_return != NULL) {
		pid_of_window = *(guint32 *) prop_return;
		XFree (prop_return);
	}

	if (pid_of_window == pid) {
		Atom _NET_WM_NAME = XInternAtom (display, "_NET_WM_NAME", False);
		Atom UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);

//		printf ("[%i shocker] %*sFound window %p for pid %i\n", getpid (), level, " ", (void *) window, pid);

		XGetWindowAttributes (display, window, &window_attributes);
		if (window_attributes.map_state != IsViewable || window_attributes.c_class != InputOutput) {
// 			printf ("[%i shocker] WindowHelper_GetWindowInfo (%i): Window %x isn't viewable and inputoutput.\n", getpid (), pid, (int) window);
			goto recurse;
		}

		XTranslateCoordinates (display, window, window_attributes.root, -window_attributes.border_width, -window_attributes.border_width, &x, &y, &dummy);

		wix = (WindowInfoEx *) g_malloc0 (sizeof (WindowInfoEx));
		wix->window = window;
		wi = &wix->wi;
		// This is not entirely correct: we're not taking into account the title bar of the window
		wi->windowLeft = x - window_attributes.border_width;
		wi->windowTop = y - window_attributes.border_width;
		wi->windowWidth = window_attributes.width;
		wi->windowHeight = window_attributes.height;
		wi->windowRight = wi->windowLeft + wi->windowWidth;
		wi->windowBottom = wi->windowTop + wi->windowBottom;
		
		wi->clientLeft = x;
		wi->clientTop = y;
		wi->clientWidth = window_attributes.width - window_attributes.border_width * 2;
		wi->clientHeight = window_attributes.height - window_attributes.border_width * 2;
		wi->clientRight = wi->clientLeft + wi->clientWidth;
		wi->clientBottom = wi->clientTop + wi->clientHeight;
		
		// Get window name
		XGetWindowProperty (display, window, _NET_WM_NAME, 0, MAX_WINDOW_TITLE / 4, False, UTF8_STRING, &actual_type_return, &actual_format_return, &nitems_return, &bytes_after_return, &prop_return);
		if (nitems_return > 0 && prop_return != NULL) {
			memcpy (wi->title, prop_return, MIN (nitems_return, MAX_WINDOW_TITLE - 1));
		}
		
		*result = g_slist_prepend (*result, wix);
		return;
	}

recurse:
// 	printf ("[%i shocker] %*sFound window %p is not in pid %i\n", getpid (), level, " ", (void *) window, pid);
	
	// Recurse into children
	Window root_return;
	Window parent_return;
	Window *children;
	unsigned int n_children;
	if (0 != (XQueryTree (display, window, &root_return, &parent_return, &children, &n_children))) {
		for (unsigned int i = 0; i < n_children; i++) {
			find_window_r (pid, children [i], display, atom_pid, level + 1, result);
		}
	}
}
示例#10
0
文件: icon.c 项目: dimkr/literocks
/* Menu was clicked over this icon. Set things up correctly (shade items,
 * add app menu stuff, etc).
 * You should show icon_menu after calling this...
 */
void icon_prepare_menu(Icon *icon, GtkWidget *options_item, ...)
{
	gboolean shaded;
	GSList *link;
	va_list ap;
	GtkWidget *trailing;
	static GtkWidget *current_options_item;	/* Pin/Pan Options */
	static GSList *current_trailing_items = NULL;

	appmenu_remove();

	if (current_options_item)
	{
		gtk_widget_destroy(current_options_item);
		current_options_item = NULL;
	}
	for (link = current_trailing_items; link; link = g_slist_next(link))
	{
		gtk_widget_destroy(link->data);
	}
	if (current_trailing_items)
	{
		g_slist_free(current_trailing_items);
		current_trailing_items = NULL;
	}

	menu_icon = icon;

	if (!icon_menu)
		create_menu();

	current_options_item = options_item;
	add_stock_to_menu_item(options_item, GTK_STOCK_PREFERENCES);

	gtk_menu_shell_append(GTK_MENU_SHELL(icon_menu), options_item);
	gtk_widget_show_all(options_item);

	va_start(ap, options_item);
	while ((trailing = va_arg(ap, GtkWidget *)) != NULL)
	{
		current_trailing_items = g_slist_prepend(current_trailing_items,
				trailing);
		gtk_menu_shell_append(GTK_MENU_SHELL(icon_menu), trailing);
		gtk_widget_show(trailing);
	}
	va_end(ap);
	
	/* Shade Remove Item(s) if any item is locked or nothing is selected */
	if (icon_selection)
		shaded = any_selected_item_is_locked();
	else if (menu_icon)
		shaded = menu_icon->locked;
	else
		shaded = TRUE;
	
	menu_set_items_shaded(icon_menu, shaded, 4, 1);

	menu_show_shift_action(file_shift_item, icon ? icon->item : NULL,
			FALSE);

	/* Shade the File/Edit/Show items unless an item was clicked */
	if (icon)
	{
		guchar *tmp;

		menu_set_items_shaded(icon_menu, FALSE, 1, 3);
		menu_set_items_shaded(icon_file_menu, FALSE, 0, 5);
		if (!can_set_run_action(icon->item))
			menu_set_items_shaded(icon_file_menu, TRUE, 2, 1);

		tmp = g_strdup_printf(_("%s '%s'"),
				basetype_name(icon->item),
				icon->item->leafname);
		gtk_label_set_text(GTK_LABEL(icon_file_item), tmp);
		g_free(tmp);

		/* Check for app-specific menu */
		appmenu_add(icon->path, icon->item, icon_menu);
	}
	else
	{
		menu_set_items_shaded(icon_menu, TRUE, 1, 3);
		menu_set_items_shaded(icon_file_menu, TRUE, 0, 5);
		gtk_label_set_text(GTK_LABEL(icon_file_item), _("Nothing"));
	}
}
示例#11
0
文件: style.c 项目: UIKit0/gnumeric
static void
list_cached_fonts (GnmFont *font, G_GNUC_UNUSED gpointer value, GSList **lp)
{
	*lp = g_slist_prepend (*lp, font);
}
示例#12
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;
}
示例#13
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;
}
示例#14
0
文件: replay.c 项目: CTU-IIG/qemu
void replay_add_blocker(Error *reason)
{
    replay_blockers = g_slist_prepend(replay_blockers, reason);
}
示例#15
0
gint64 *
arv_gc_enumeration_get_available_int_values (ArvGcEnumeration *enumeration, guint *n_values, GError **error)
{
	gint64 *values;
	const GSList *entries, *iter;
	GSList *available_entries = NULL;
	unsigned int i;
	GError *local_error = NULL;

	g_return_val_if_fail (n_values != NULL, NULL);

	*n_values = 0;

	g_return_val_if_fail (ARV_IS_GC_ENUMERATION (enumeration), NULL);
	g_return_val_if_fail (error == NULL || *error == NULL, NULL);

	entries = arv_gc_enumeration_get_entries (enumeration);

	*n_values = 0;
	for (iter = entries; iter != NULL; iter = iter->next) {
		gboolean is_available;

		is_available = arv_gc_feature_node_is_available (iter->data, &local_error);

		if (local_error != NULL) {
			g_propagate_error (error, local_error);
			*n_values = 0;
			g_slist_free (available_entries);

			return NULL;
		}

		if (is_available) {
			gboolean is_implemented;

			is_implemented = arv_gc_feature_node_is_implemented (iter->data, &local_error);

			if (local_error != NULL) {
				g_propagate_error (error, local_error);
				*n_values = 0;
				g_slist_free (available_entries);

				return NULL;
			}

			if (is_implemented) {
				(*n_values)++;
				available_entries = g_slist_prepend (available_entries, iter->data);
			}
		}
	}

	if (*n_values == 0) {
		g_slist_free (available_entries);
		return NULL;
	}

	values = g_new (gint64, *n_values);
	for (iter = available_entries, i = 0; iter != NULL; iter = iter->next) {

		values[i] = arv_gc_enum_entry_get_value (iter->data, &local_error);

		if (local_error != NULL) {
			g_propagate_error (error, local_error);
			*n_values = 0;
			g_slist_free (available_entries);
			g_free (values);

			return NULL;
		}
		i++;
	}

	g_slist_free (available_entries);

	return values;
}
示例#16
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;
}
示例#17
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);
	}
}
示例#18
0
void
html_colorset_add_slave (HTMLColorSet *set,
                         HTMLColorSet *slave)
{
	set->slaves = g_slist_prepend (set->slaves, slave);
}
示例#19
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);
}
示例#20
0
文件: tls_user.c 项目: regit/nufw
/**
 * Function called on new client connection:
 *    - Call accept()
 *    - Drop client if there are to much clients or if NuAuth is in reload
 *    - Create a client_connection structure
 *    - Add client to ::pre_client_list
 *    - Add client to ::tls_sasl_worker queue (see sasl_worker())
 *
 * \return If an error occurs returns 1, else returns 0.
 */
int tls_user_accept(struct tls_user_context_t *context)
{
    struct sockaddr_storage sockaddr;
    struct sockaddr_in *sockaddr4 = (struct sockaddr_in *) &sockaddr;
    struct sockaddr_in6 *sockaddr6 = (struct sockaddr_in6 *) &sockaddr;
    struct in6_addr addr;
    unsigned int len_inet = sizeof sockaddr;
    struct client_connection *current_client_conn;
    struct pre_client_elt *new_pre_client;
    int socket;
    gint option_value;
    unsigned short sport;
    char address[INET6_ADDRSTRLEN];

    current_client_conn = g_new0(struct client_connection, 1);

    current_client_conn->nussl = nussl_session_accept(context->nussl);
    if ( ! current_client_conn->nussl ) {
        /* can be triggered by EAGAIN on non blocking accept socket */
        g_free(current_client_conn);
        return 1;
    }

    if (nussl_session_getpeer(current_client_conn->nussl, (struct sockaddr *) &sockaddr, &len_inet) != NUSSL_OK)
    {
        log_message(WARNING, DEBUG_AREA_MAIN | DEBUG_AREA_USER,
                    "New client connection failed during nussl_session_getpeer(): %s", nussl_get_error(context->nussl));
        g_free(current_client_conn);
        return 1;
    }

    socket = nussl_session_get_fd(current_client_conn->nussl);

    /* if system is in reload: drop new client */
    if (nuauthdatas->need_reload) {
        shutdown(socket, SHUT_RDWR);
        close(socket);
        return 0;
    }

    /* Extract client address (convert it to IPv6 if it's IPv4) */
    /* if (sockaddr.ss_family == AF_INET) { -> same as tls_nufw.c */
    if (sockaddr6->sin6_family == AF_INET) {
        ipv4_to_ipv6(sockaddr4->sin_addr, &addr);
        sport = ntohs(sockaddr4->sin_port);
    } else {
        addr = sockaddr6->sin6_addr;
        sport = ntohs(sockaddr6->sin6_port);
    }

    format_ipv6(&addr, address, sizeof(address), NULL);
    log_message(DEBUG, DEBUG_AREA_MAIN | DEBUG_AREA_USER,
                "nuauth: user connection attempt from %s\n",
                address);

    if (get_number_of_clients() >= context->nuauth_tls_max_clients) {
        log_message(WARNING, DEBUG_AREA_MAIN | DEBUG_AREA_USER,
                    "too many clients (%d configured)",
                    context->nuauth_tls_max_clients);
        shutdown(socket, SHUT_RDWR);
        close(socket);
        return 1;
    }

    current_client_conn->socket = socket;
    current_client_conn->addr = addr;
    current_client_conn->sport = sport;
    current_client_conn->str_addr = g_strdup(address);
    current_client_conn->srv_context = context;

    /* Set KEEP ALIVE on connection */
    option_value = 1;
    setsockopt(socket,
               SOL_SOCKET, SO_KEEPALIVE,
               &option_value, sizeof(option_value));

    /* give the connection to a separate thread */
    /*  add element to pre_client
       create pre_client_elt */
    new_pre_client = g_new0(struct pre_client_elt, 1);
    new_pre_client->socket = socket;
    new_pre_client->validity =
        time(NULL) + context->nuauth_auth_nego_timeout;

    g_static_mutex_lock(&pre_client_list_mutex);
    pre_client_list = g_slist_prepend(pre_client_list, new_pre_client);
    g_static_mutex_unlock(&pre_client_list_mutex);

    thread_pool_push(nuauthdatas->tls_sasl_worker,
                     current_client_conn, NULL);
    return 0;
}
示例#21
0
static void filter_iter(MegaNode* node, struct FilterData* data)
{
  if (data->filter == NULL || data->filter(node, data->user_data))
    data->result = g_slist_prepend(data->result, g_object_ref(node));
}
示例#22
0
文件: jabber.c 项目: luka-n/bitlbee
static void jabber_login(account_t *acc)
{
	struct im_connection *ic = imcb_new(acc);
	struct jabber_data *jd = g_new0(struct jabber_data, 1);
	char *s;

	/* For now this is needed in the _connected() handlers if using
	   GLib event handling, to make sure we're not handling events
	   on dead connections. */
	jabber_connections = g_slist_prepend(jabber_connections, ic);

	jd->ic = ic;
	ic->proto_data = jd;

	jabber_set_me(ic, acc->user);

	jd->fd = jd->r_inpa = jd->w_inpa = -1;

	if (strcmp(acc->prpl->name, "hipchat") == 0) {
		jd->flags |= JFLAG_HIPCHAT;
	}

	if (jd->server == NULL) {
		imcb_error(ic, "Incomplete account name (format it like <*****@*****.**>)");
		imc_logout(ic, FALSE);
		return;
	}

	if ((s = strchr(jd->server, '/'))) {
		*s = 0;
		set_setstr(&acc->set, "resource", s + 1);

		/* Also remove the /resource from the original variable so we
		   won't have to do this again every time. */
		s = strchr(acc->user, '/');
		*s = 0;
	}

	jd->node_cache = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, jabber_cache_entry_free);
	jd->buddies = g_hash_table_new(g_str_hash, g_str_equal);

	if (set_getbool(&acc->set, "oauth")) {
		GSList *p_in = NULL;
		const char *tok;

		jd->fd = jd->r_inpa = jd->w_inpa = -1;

		if (strstr(jd->server, ".facebook.com")) {
			jd->oauth2_service = &oauth2_service_facebook;
		} else {
			jd->oauth2_service = &oauth2_service_google;
		}

		oauth_params_parse(&p_in, ic->acc->pass);

		/* First see if we have a refresh token, in which case any
		   access token we *might* have has probably expired already
		   anyway. */
		if ((tok = oauth_params_get(&p_in, "refresh_token"))) {
			sasl_oauth2_refresh(ic, tok);
		}
		/* If we don't have a refresh token, let's hope the access
		   token is still usable. */
		else if ((tok = oauth_params_get(&p_in, "access_token"))) {
			jd->oauth2_access_token = g_strdup(tok);
			jabber_connect(ic);
		}
		/* If we don't have any, start the OAuth process now. Don't
		   even open an XMPP connection yet. */
		else {
			sasl_oauth2_init(ic);
			ic->flags |= OPT_SLOW_LOGIN;
		}

		oauth_params_free(&p_in);
	} else {
		jabber_connect(ic);
	}
}
示例#23
0
static void
ensure_work_areas_validated (MetaWorkspace *workspace)
{
  GList         *windows;
  GList         *tmp;
  MetaRectangle  work_area;
  int            i;  /* C89 absolutely sucks... */

  if (!workspace->work_areas_invalid)
    return;

  g_assert (workspace->all_struts == NULL);
  g_assert (workspace->monitor_region == NULL);
  g_assert (workspace->screen_region == NULL);
  g_assert (workspace->screen_edges == NULL);
  g_assert (workspace->monitor_edges == NULL);

  /* STEP 1: Get the list of struts */

  workspace->all_struts = copy_strut_list (workspace->builtin_struts);

  windows = meta_workspace_list_windows (workspace);
  for (tmp = windows; tmp != NULL; tmp = tmp->next)
    {
      MetaWindow *win = tmp->data;
      GSList *s_iter;

      for (s_iter = win->struts; s_iter != NULL; s_iter = s_iter->next) {
        workspace->all_struts = g_slist_prepend (workspace->all_struts,
                                                 copy_strut(s_iter->data));
      }
    }
  g_list_free (windows);

  /* STEP 2: Get the maximal/spanning rects for the onscreen and
   *         on-single-monitor regions
   */  
  g_assert (workspace->monitor_region == NULL);
  g_assert (workspace->screen_region   == NULL);

  workspace->monitor_region = g_new (GList*,
                                      workspace->screen->n_monitor_infos);
  for (i = 0; i < workspace->screen->n_monitor_infos; i++)
    {
      workspace->monitor_region[i] =
        meta_rectangle_get_minimal_spanning_set_for_region (
          &workspace->screen->monitor_infos[i].rect,
          workspace->all_struts);
    }
  workspace->screen_region =
    meta_rectangle_get_minimal_spanning_set_for_region (
      &workspace->screen->rect,
      workspace->all_struts);

  /* STEP 3: Get the work areas (region-to-maximize-to) for the screen and
   *         monitors.
   */
  work_area = workspace->screen->rect;  /* start with the screen */
  if (workspace->screen_region == NULL)
    work_area = meta_rect (0, 0, -1, -1);
  else
    meta_rectangle_clip_to_region (workspace->screen_region,
                                   FIXED_DIRECTION_NONE,
                                   &work_area);

  /* Lots of paranoia checks, forcing work_area_screen to be sane */
#define MIN_SANE_AREA 100
  if (work_area.width < MIN_SANE_AREA)
    {
      meta_warning ("struts occupy an unusually large percentage of the screen; "
                    "available remaining width = %d < %d",
                    work_area.width, MIN_SANE_AREA);
      if (work_area.width < 1)
        {
          work_area.x = (workspace->screen->rect.width - MIN_SANE_AREA)/2;
          work_area.width = MIN_SANE_AREA;
        }
      else
        {
          int amount = (MIN_SANE_AREA - work_area.width)/2;
          work_area.x     -=   amount;
          work_area.width += 2*amount;
        }
    }
  if (work_area.height < MIN_SANE_AREA)
    {
      meta_warning ("struts occupy an unusually large percentage of the screen; "
                    "available remaining height = %d < %d",
                    work_area.height, MIN_SANE_AREA);
      if (work_area.height < 1)
        {
          work_area.y = (workspace->screen->rect.height - MIN_SANE_AREA)/2;
          work_area.height = MIN_SANE_AREA;
        }
      else
        {
          int amount = (MIN_SANE_AREA - work_area.height)/2;
          work_area.y      -=   amount;
          work_area.height += 2*amount;
        }
    }
  workspace->work_area_screen = work_area;
  meta_topic (META_DEBUG_WORKAREA,
              "Computed work area for workspace %d: %d,%d %d x %d\n",
              meta_workspace_index (workspace),
              workspace->work_area_screen.x,
              workspace->work_area_screen.y,
              workspace->work_area_screen.width,
              workspace->work_area_screen.height);    

  /* Now find the work areas for each monitor */
  g_free (workspace->work_area_monitor);
  workspace->work_area_monitor = g_new (MetaRectangle,
                                         workspace->screen->n_monitor_infos);

  for (i = 0; i < workspace->screen->n_monitor_infos; i++)
    {
      work_area = workspace->screen->monitor_infos[i].rect;

      if (workspace->monitor_region[i] == NULL)
        /* FIXME: constraints.c untested with this, but it might be nice for
         * a screen reader or magnifier.
         */
        work_area = meta_rect (work_area.x, work_area.y, -1, -1);
      else
        meta_rectangle_clip_to_region (workspace->monitor_region[i],
                                       FIXED_DIRECTION_NONE,
                                       &work_area);

      workspace->work_area_monitor[i] = work_area;
      meta_topic (META_DEBUG_WORKAREA,
                  "Computed work area for workspace %d "
                  "monitor %d: %d,%d %d x %d\n",
                  meta_workspace_index (workspace),
                  i,
                  workspace->work_area_monitor[i].x,
                  workspace->work_area_monitor[i].y,
                  workspace->work_area_monitor[i].width,
                  workspace->work_area_monitor[i].height);
    }

  /* STEP 4: Make sure the screen_region is nonempty (separate from step 2
   *         since it relies on step 3).
   */  
  if (workspace->screen_region == NULL)
    {
      MetaRectangle *nonempty_region;
      nonempty_region = g_new (MetaRectangle, 1);
      *nonempty_region = workspace->work_area_screen;
      workspace->screen_region = g_list_prepend (NULL, nonempty_region);
    }

  /* STEP 5: Cache screen and monitor edges for edge resistance and snapping */
  g_assert (workspace->screen_edges    == NULL);
  g_assert (workspace->monitor_edges  == NULL);
  workspace->screen_edges =
    meta_rectangle_find_onscreen_edges (&workspace->screen->rect,
                                        workspace->all_struts);
  tmp = NULL;
  for (i = 0; i < workspace->screen->n_monitor_infos; i++)
    tmp = g_list_prepend (tmp, &workspace->screen->monitor_infos[i].rect);
  workspace->monitor_edges =
    meta_rectangle_find_nonintersected_monitor_edges (tmp,
                                                       workspace->all_struts);
  g_list_free (tmp);

  /* We're all done, YAAY!  Record that everything has been validated. */
  workspace->work_areas_invalid = FALSE;

  {
    /*
     * Notify the compositor that the workspace geometry has changed.
     */
    MetaScreen     *screen = workspace->screen;
    MetaDisplay    *display = meta_screen_get_display (screen);
    MetaCompositor *comp = meta_display_get_compositor (display);

    if (comp)
      meta_compositor_update_workspace_geometry (comp, workspace);
  }
}
/** \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);

     }
}
示例#25
0
void okc_post_or_get(OkCupidAccount *oca, OkCupidMethod method,
		const gchar *host, const gchar *url, const gchar *postdata,
		OkCupidProxyCallbackFunc callback_func, gpointer user_data,
		gboolean keepalive)
{
	GString *request;
	gchar *cookies;
	OkCupidConnection *okconn;
	gchar *real_url;
	gboolean is_proxy = FALSE;
	const gchar* const *languages;
	gchar *language_names;
	PurpleProxyInfo *proxy_info = NULL;
	gchar *proxy_auth;
	gchar *proxy_auth_base64;

	/* TODO: Fix keepalive and use it as much as possible */
	keepalive = FALSE;
	
	if (purple_account_get_bool(oca->account, "force_https", TRUE) && !(method & OKC_METHOD_SSL) &&
			(!host || g_str_equal(host, "www.okcupid.com") || g_str_equal(host, "api.okcupid.com")))
	{
		method |= OKC_METHOD_SSL;
	}

	if (method & OKC_METHOD_SSL)
		host = "www.okcupid.com";
	if (host == NULL && oca && oca->account)
		host = purple_account_get_string(oca->account, "host", "api.okcupid.com");
	if (host == NULL)
		host = "api.okcupid.com";

	if (oca && oca->account && !(method & OKC_METHOD_SSL))
	{
		proxy_info = purple_proxy_get_setup(oca->account);
		if (purple_proxy_info_get_type(proxy_info) == PURPLE_PROXY_USE_GLOBAL)
			proxy_info = purple_global_proxy_get_info();
		if (purple_proxy_info_get_type(proxy_info) == PURPLE_PROXY_HTTP)
		{
			is_proxy = TRUE;
		}	
	}
	if (is_proxy == TRUE)
	{
		real_url = g_strdup_printf("http://%s%s", host, url);
	} else {
		real_url = g_strdup(url);
	}
	
	cookies = okc_cookies_to_string(oca);
	
	if (method & OKC_METHOD_POST && !postdata)
		postdata = "";
	
	/* Build the request */
	request = g_string_new(NULL);
	g_string_append_printf(request, "%s %s HTTP/1.0\r\n",
			(method & OKC_METHOD_POST) ? "POST" : "GET",
			real_url);
	
	if (is_proxy == FALSE)
		g_string_append_printf(request, "Host: %s\r\n", host);
	g_string_append_printf(request, "Connection: %s\r\n",
			(keepalive ? "Keep-Alive" : "close"));
	g_string_append_printf(request, "User-Agent: %s (libpurple %s)\r\n", purple_core_get_ui(), purple_core_get_version());
	if (method & OKC_METHOD_POST) {
		g_string_append_printf(request,
				"Content-Type: application/x-www-form-urlencoded\r\n");
		g_string_append_printf(request,
				"Content-length: %zu\r\n", strlen(postdata));
	}
	g_string_append_printf(request, "Accept: */*\r\n");
	g_string_append_printf(request, "Cookie: %s\r\n", cookies);
	g_string_append_printf(request, "Accept-Encoding: gzip\r\n");
	g_string_append_printf(request, "X-OkCupid-Api-Version: 1\r\n");
	
	if (is_proxy == TRUE)
	{
		if (purple_proxy_info_get_username(proxy_info) &&
			purple_proxy_info_get_password(proxy_info))
		{
			proxy_auth = g_strdup_printf("%s:%s", purple_proxy_info_get_username(proxy_info), purple_proxy_info_get_password(proxy_info));
			proxy_auth_base64 = purple_base64_encode((guchar *)proxy_auth, strlen(proxy_auth));
			g_string_append_printf(request, "Proxy-Authorization: Basic %s\r\n", proxy_auth_base64);
			g_free(proxy_auth_base64);
			g_free(proxy_auth);
		}
	}
	/* Tell the server what language we accept, so that we get error messages in our language (rather than our IP's) */
	languages = g_get_language_names();
	language_names = g_strjoinv(", ", (gchar **)languages);
	purple_util_chrreplace(language_names, '_', '-');
	g_string_append_printf(request, "Accept-Language: %s\r\n", language_names);
	g_free(language_names);

	purple_debug_misc("okcupid", "requesting url %s\n", url);

	g_string_append_printf(request, "\r\n");
	if (method & OKC_METHOD_POST)
		g_string_append_printf(request, "%s", postdata);

	/* If it needs to go over a SSL connection, we probably shouldn't print
	 * it in the debug log.  Without this condition a user's password is
	 * printed in the debug log */
	if (method == OKC_METHOD_POST)
		purple_debug_misc("okcupid", "sending request data:\n%s\n",
			postdata);

	g_free(cookies);
	g_free(real_url);
	/*
	 * Do a separate DNS lookup for the given host name and cache it
	 * for next time.
	 *
	 * TODO: It would be better if we did this before we call
	 *       purple_proxy_connect(), so we could re-use the result.
	 *       Or even better: Use persistent HTTP connections for servers
	 *       that we access continually.
	 *
	 * TODO: This cache of the hostname<-->IP address does not respect
	 *       the TTL returned by the DNS server.  We should expire things
	 *       from the cache after some amount of time.
	 */
	if (!is_proxy && !g_hostname_is_ip_address(host) && !(method & OKC_METHOD_SSL))
	{
		/* Don't do this for proxy connections, since proxies do the DNS lookup */
		gchar *host_ip;

		host_ip = g_hash_table_lookup(oca->hostname_ip_cache, host);
		if (host_ip != NULL) {
			purple_debug_info("okcupid",
					"swapping original host %s with cached value of %s\n",
					host, host_ip);
			host = host_ip;
		} else if (oca->account && !oca->account->disconnecting) {
			GSList *host_lookup_list = NULL;
			PurpleDnsQueryData *query;

			host_lookup_list = g_slist_prepend(
					host_lookup_list, g_strdup(host));
			host_lookup_list = g_slist_prepend(
					host_lookup_list, oca);

			query = purple_dnsquery_a(host, 80,
					okc_host_lookup_cb, host_lookup_list);
			oca->dns_queries = g_slist_prepend(oca->dns_queries, query);
			host_lookup_list = g_slist_append(host_lookup_list, query);
		}
	}

	okconn = g_new0(OkCupidConnection, 1);
	okconn->oca = oca;
	okconn->method = method;
	okconn->hostname = g_strdup(host);
	okconn->request = request;
	okconn->callback = callback_func;
	okconn->user_data = user_data;
	okconn->fd = -1;
	okconn->connection_keepalive = keepalive;
	okconn->request_time = time(NULL);

	g_queue_push_head(oca->waiting_conns, okconn);
	okc_next_connection(oca);
}
/** \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;

}
示例#27
0
文件: cartesian.c 项目: Gilles86/afni
int main (int argc, char * argv[])
{
  guint i, j, nx, ny;
  gdouble cosa, sina;
  GtsSurface * surface;
  GSList * l, * vertices = NULL;
  GtsTriangle * t;
  GtsVertex * v1, * v2, * v3;
  GTimer * timer;

  if (argc != 4) {
    fprintf (stderr, "usage: cartesian nx ny angle\n");
    return 0;
  }

  nx = atoi (argv[1]);
  ny = atoi (argv[2]);
  cosa = cos (atof (argv[3]));
  sina = sin (atof (argv[3]));

  timer = g_timer_new ();
  g_timer_start (timer);
  for (i = 0; i < nx; i++) {
    gdouble x = (gdouble) i/(gdouble) (nx - 1); 
    for (j = 0; j < ny; j++) {
      gdouble y = (gdouble) j/(gdouble) (nx - 1); 
      vertices = g_slist_prepend (vertices, 
		     gts_vertex_new (gts_vertex_class (),
				     cosa*x - sina*y, sina*x + cosa*y, 0.));
    }
  }

  t = gts_triangle_enclosing (gts_triangle_class (), vertices, 100.);
  gts_triangle_vertices (t, &v1, &v2, &v3);
  surface = gts_surface_new (gts_surface_class (),
			     gts_face_class (),
			     gts_edge_class (),
			     gts_vertex_class ());
  gts_surface_add_face (surface, gts_face_new (gts_face_class (),
					       t->e1, t->e2, t->e3));
  g_timer_stop (timer);
  fprintf (stderr, "Input: %g s\n", g_timer_elapsed (timer, NULL));
  g_timer_reset (timer);

  g_timer_start (timer);
  l = vertices;
  while (l) {
    g_assert (gts_delaunay_add_vertex (surface, l->data, NULL) == NULL);
    l = l->next;
  }

  gts_allow_floating_vertices = TRUE;
  gts_object_destroy (GTS_OBJECT (v1));
  gts_object_destroy (GTS_OBJECT (v2));
  gts_object_destroy (GTS_OBJECT (v3));
  gts_allow_floating_vertices = FALSE;
  g_timer_stop (timer);

  fprintf (stderr, "Triangulation: %g s speed: %.0f vertex/s\n", 
	   g_timer_elapsed (timer, NULL),
	   g_slist_length (vertices)/g_timer_elapsed (timer, NULL));
  g_timer_reset (timer);

  g_timer_start (timer);
  gts_surface_write (surface, stdout);
  g_timer_stop (timer);

  fprintf (stderr, "Output: %g s\n", g_timer_elapsed (timer, NULL));

  if (gts_delaunay_check (surface)) {
    fprintf (stderr, "WARNING: surface is not Delaunay\n");
    return 0;
  }

  return 1;
}
示例#28
0
static void transport_func(GIOChannel *io, GError *err, gpointer user_data)
{
	struct callback_data *callback = user_data;
	struct obc_session *session = callback->session;
	struct obc_driver *driver = session->driver;
	struct obc_transport *transport = session->transport;
	GObex *obex;
	GObexApparam *apparam;
	GObexTransportType type;
	int tx_mtu = -1;
	int rx_mtu = -1;

	DBG("");

	if (err != NULL) {
		error("%s", err->message);
		goto done;
	}

	g_io_channel_set_close_on_unref(io, FALSE);

	if (transport->getpacketopt &&
			transport->getpacketopt(io, &tx_mtu, &rx_mtu) == 0)
		type = G_OBEX_TRANSPORT_PACKET;
	else
		type = G_OBEX_TRANSPORT_STREAM;

	obex = g_obex_new(io, type, tx_mtu, rx_mtu);
	if (obex == NULL)
		goto done;

	g_io_channel_set_close_on_unref(io, TRUE);

	apparam = NULL;

	if (driver->supported_features)
		apparam = driver->supported_features(session);

	if (apparam) {
		uint8_t buf[1024];
		ssize_t len;

		len = g_obex_apparam_encode(apparam, buf, sizeof(buf));
		if (driver->target)
			g_obex_connect(obex, connect_cb, callback, &err,
					G_OBEX_HDR_TARGET,
					driver->target, driver->target_len,
					G_OBEX_HDR_APPARAM,
					buf, len,
					G_OBEX_HDR_INVALID);
		else
			g_obex_connect(obex, connect_cb, callback, &err,
					G_OBEX_HDR_APPARAM, buf, len,
					G_OBEX_HDR_INVALID);
		g_obex_apparam_free(apparam);
	} else if (driver->target)
		g_obex_connect(obex, connect_cb, callback, &err,
			G_OBEX_HDR_TARGET, driver->target, driver->target_len,
			G_OBEX_HDR_INVALID);
	else
		g_obex_connect(obex, connect_cb, callback, &err,
							G_OBEX_HDR_INVALID);

	if (err != NULL) {
		error("%s", err->message);
		g_obex_unref(obex);
		goto done;
	}

	session->obex = obex;
	sessions = g_slist_prepend(sessions, session);

	g_obex_set_disconnect_function(obex, session_disconnected, session);

	return;
done:
	callback_destroy(callback, err);
}
static void
manager_real_set (GdaAttributesManager *mgr, gpointer ptr, 
		  const gchar *att_name, GDestroyNotify destroy, 
		  const GValue *value, gboolean steal_value)
{
	ObjAttrs *objattrs;

	g_return_if_fail (att_name);
	if (mgr->for_objects) 
		g_return_if_fail (G_IS_OBJECT (ptr));
	
	gda_mutex_lock (mgr->mutex);

	/* pick up the correct ObjAttrs */
	objattrs = g_hash_table_lookup (mgr->obj_hash, ptr);
	if (!objattrs) {
		objattrs = g_new0 (ObjAttrs, 1);
		objattrs->mgr = mgr;
		objattrs->objects = g_slist_prepend (NULL, ptr);
		objattrs->values_hash = g_hash_table_new_full (attname_hash, attname_equal, 
							       (GDestroyNotify) attname_free,
							       (GDestroyNotify) gda_value_free);
		g_hash_table_insert (mgr->obj_hash, ptr, objattrs);
		if (mgr->for_objects) 
			g_object_weak_ref (G_OBJECT (ptr), (GWeakNotify) obj_destroyed_cb, objattrs);
	}

	if (objattrs->objects->next) {
		/* create another ObjAttrs specifically for @ptr */
		ObjAttrs *objattrs2;
		CopyData cdata;
		objattrs2 = g_new0 (ObjAttrs, 1);
		objattrs2->mgr = mgr;
		objattrs2->objects = g_slist_prepend (NULL, ptr);
		objattrs2->values_hash = g_hash_table_new_full (attname_hash, attname_equal, 
							       (GDestroyNotify) attname_free, 
								(GDestroyNotify) gda_value_free);

		objattrs->objects = g_slist_remove (objattrs->objects, ptr);
		g_hash_table_remove (mgr->obj_hash, ptr);
		g_hash_table_insert (mgr->obj_hash, ptr, objattrs2);

		if (mgr->for_objects) {
			g_object_weak_unref (G_OBJECT (ptr), (GWeakNotify) obj_destroyed_cb, objattrs);
			g_object_weak_ref (G_OBJECT (ptr), (GWeakNotify) obj_destroyed_cb, objattrs2);
		}

		cdata.to_mgr = mgr;
		cdata.ptr = ptr;
		g_hash_table_foreach (objattrs->values_hash, (GHFunc) foreach_copy_func, &cdata);

		objattrs = objattrs2;
	}

	/* Actually add the attribute */
	if (value) {
		AttName *attname;

		attname = g_new (AttName, 1);
		attname->mgr = mgr;
		attname->att_name = (gchar*) att_name; /* NOT duplicated */
		attname->att_name_destroy = destroy;
		if (steal_value)
			g_hash_table_insert (objattrs->values_hash, attname, (GValue*) value);
		else
			g_hash_table_insert (objattrs->values_hash, attname, gda_value_copy (value));
	}
	else {
		AttName attname;
		attname.att_name = (gchar*) att_name;
		g_hash_table_remove (objattrs->values_hash, &attname);
	}
	if (mgr->signal_func && mgr->for_objects)
		mgr->signal_func ((GObject*) ptr, att_name, value, mgr->signal_data);

	gda_mutex_unlock (mgr->mutex);
}
示例#30
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;
}