source: util.c @ 35b6eb9

release-1.10release-1.8release-1.9
Last change on this file since 35b6eb9 was 35b6eb9, checked in by Anders Kaseorg <andersk@mit.edu>, 13 years ago
Replace owl_realloc with g_renew. Signed-off-by: Anders Kaseorg <andersk@mit.edu> Reviewed-by: Karl Ramm <kcr@mit.edu>
  • Property mode set to 100644
File size: 20.2 KB
Line 
1#include "owl.h"
2#include <stdlib.h>
3#include <string.h>
4#include <unistd.h>
5#include <ctype.h>
6#include <pwd.h>
7#include <sys/stat.h>
8#include <sys/types.h>
9#include <assert.h>
10#include <stdarg.h>
11#include <glib.h>
12#include <glib/gstdio.h>
13#include <glib-object.h>
14
15const char *skiptokens(const char *buff, int n) {
16  /* skips n tokens and returns where that would be. */
17  char quote = 0;
18  while (*buff && n>0) {
19      while (*buff == ' ') buff++;
20      while (*buff && (quote || *buff != ' ')) {
21        if(quote) {
22          if(*buff == quote) quote = 0;
23        } else if(*buff == '"' || *buff == '\'') {
24          quote = *buff;
25        }
26        buff++;
27      }
28      while (*buff == ' ') buff++;
29      n--;
30  }
31  return buff;
32}
33
34/* Return a "nice" version of the path.  Tilde expansion is done, and
35 * duplicate slashes are removed.  Caller must free the return.
36 */
37char *owl_util_makepath(const char *in)
38{
39  int i, j, x;
40  char *out, user[MAXPATHLEN];
41  struct passwd *pw;
42
43  out=g_new(char, MAXPATHLEN+1);
44  out[0]='\0';
45  j=strlen(in);
46  x=0;
47  for (i=0; i<j; i++) {
48    if (in[i]=='~') {
49      if ( (i==(j-1)) ||          /* last character */
50           (in[i+1]=='/') ) {     /* ~/ */
51        /* use my homedir */
52        pw=getpwuid(getuid());
53        if (!pw) {
54          out[x]=in[i];
55        } else {
56          out[x]='\0';
57          strcat(out, pw->pw_dir);
58          x+=strlen(pw->pw_dir);
59        }
60      } else {
61        /* another user homedir */
62        int a, b;
63        b=0;
64        for (a=i+1; i<j; a++) {
65          if (in[a]==' ' || in[a]=='/') {
66            break;
67          } else {
68            user[b]=in[a];
69            i++;
70            b++;
71          }
72        }
73        user[b]='\0';
74        pw=getpwnam(user);
75        if (!pw) {
76          out[x]=in[i];
77        } else {
78          out[x]='\0';
79          strcat(out, pw->pw_dir);
80          x+=strlen(pw->pw_dir);
81        }
82      }
83    } else if (in[i]=='/') {
84      /* check for a double / */
85      if (i<(j-1) && (in[i+1]=='/')) {
86        /* do nothing */
87      } else {
88        out[x]=in[i];
89        x++;
90      }
91    } else {
92      out[x]=in[i];
93      x++;
94    }
95  }
96  out[x]='\0';
97  return(out);
98}
99
100void owl_parse_delete(char **argv, int argc)
101{
102  g_strfreev(argv);
103}
104
105char **owl_parseline(const char *line, int *argc)
106{
107  /* break a command line up into argv, argc.  The caller must free
108     the returned values.  If there is an error argc will be set to
109     -1, argv will be NULL and the caller does not need to free
110     anything. The returned vector is NULL-terminated. */
111
112  GPtrArray *argv;
113  int i, len, between=1;
114  GString *curarg;
115  char quote;
116
117  argv = g_ptr_array_new();
118  len=strlen(line);
119  curarg = g_string_new("");
120  quote='\0';
121  *argc=0;
122  for (i=0; i<len+1; i++) {
123    /* find the first real character */
124    if (between) {
125      if (line[i]==' ' || line[i]=='\t' || line[i]=='\0') {
126        continue;
127      } else {
128        between=0;
129        i--;
130        continue;
131      }
132    }
133
134    /* deal with a quote character */
135    if (line[i]=='"' || line[i]=="'"[0]) {
136      /* if this type of quote is open, close it */
137      if (quote==line[i]) {
138        quote='\0';
139        continue;
140      }
141
142      /* if no quoting is open then open with this */
143      if (quote=='\0') {
144        quote=line[i];
145        continue;
146      }
147
148      /* if another type of quote is open then treat this as a literal */
149      g_string_append_c(curarg, line[i]);
150      continue;
151    }
152
153    /* if it's not a space or end of command, then use it */
154    if (line[i]!=' ' && line[i]!='\t' && line[i]!='\n' && line[i]!='\0') {
155      g_string_append_c(curarg, line[i]);
156      continue;
157    }
158
159    /* otherwise, if we're not in quotes, add the whole argument */
160    if (quote=='\0') {
161      /* add the argument */
162      g_ptr_array_add(argv, g_string_free(curarg, false));
163      curarg = g_string_new("");
164      between=1;
165      continue;
166    }
167
168    /* if it is a space and we're in quotes, then use it */
169    g_string_append_c(curarg, line[i]);
170  }
171
172  *argc = argv->len;
173  g_ptr_array_add(argv, NULL);
174  g_string_free(curarg, true);
175
176  /* check for unbalanced quotes */
177  if (quote!='\0') {
178    /* TODO: when we move to requiring glib 2.22+, use
179     * g_ptr_array_new_with_free_func. */
180    g_ptr_array_foreach(argv, (GFunc)owl_free, NULL);
181    g_ptr_array_free(argv, true);
182    *argc = -1;
183    return(NULL);
184  }
185
186  return (char**)g_ptr_array_free(argv, false);
187}
188
189/* Appends a quoted version of arg suitable for placing in a
190 * command-line to a GString. Does not append a space. */
191void owl_string_append_quoted_arg(GString *buf, const char *arg)
192{
193  const char *argp;
194  if (arg[0] == '\0') {
195    /* Quote the empty string. */
196    g_string_append(buf, "''");
197  } else if (arg[strcspn(arg, "'\" \n\t")] == '\0') {
198    /* If there are no nasty characters, return as-is. */
199    g_string_append(buf, arg);
200  } else if (!strchr(arg, '\'')) {
201    /* Single-quote if possible. */
202    g_string_append_c(buf, '\'');
203    g_string_append(buf, arg);
204    g_string_append_c(buf, '\'');
205  } else {
206    /* Nasty case: double-quote, but change all internal "s to "'"'"
207     * so that they are single-quoted because we're too cool for
208     * backslashes.
209     */
210    g_string_append_c(buf, '"');
211    for (argp = arg; *argp; argp++) {
212      if (*argp == '"')
213        g_string_append(buf, "\"'\"'\"");
214      else
215        g_string_append_c(buf, *argp);
216    }
217    g_string_append_c(buf, '"');
218  }
219}
220
221/*
222 * Appends 'tmpl' to 'buf', replacing any instances of '%q' with arguments from
223 * the varargs provided, quoting them to be safe for placing in a barnowl
224 * command line.
225 */
226void owl_string_appendf_quoted(GString *buf, const char *tmpl, ...)
227{
228  va_list ap;
229  va_start(ap, tmpl);
230  owl_string_vappendf_quoted(buf, tmpl, ap);
231  va_end(ap);
232}
233
234void owl_string_vappendf_quoted(GString *buf, const char *tmpl, va_list ap)
235{
236  const char *p = tmpl, *last = tmpl;
237  while (true) {
238    p = strchr(p, '%');
239    if (p == NULL) break;
240    if (*(p+1) != 'q') {
241      p++;
242      if (*p) p++;
243      continue;
244    }
245    g_string_append_len(buf, last, p - last);
246    owl_string_append_quoted_arg(buf, va_arg(ap, char *));
247    p += 2; last = p;
248  }
249
250  g_string_append(buf, last);
251}
252
253char *owl_string_build_quoted(const char *tmpl, ...)
254{
255  GString *buf = g_string_new("");
256  va_list ap;
257  va_start(ap, tmpl);
258  owl_string_vappendf_quoted(buf, tmpl, ap);
259  va_end(ap);
260  return g_string_free(buf, false); 
261}
262
263/* Returns a quoted version of arg suitable for placing in a
264 * command-line. Result should be freed with owl_free. */
265char *owl_arg_quote(const char *arg)
266{
267  GString *buf = g_string_new("");;
268  owl_string_append_quoted_arg(buf, arg);
269  return g_string_free(buf, false);
270}
271
272/* caller must free the return */
273char *owl_util_minutes_to_timestr(int in)
274{
275  int days, hours;
276  long run;
277  char *out;
278
279  run=in;
280
281  days=run/1440;
282  run-=days*1440;
283  hours=run/60;
284  run-=hours*60;
285
286  if (days>0) {
287    out=owl_sprintf("%i d %2.2i:%2.2li", days, hours, run);
288  } else {
289    out=owl_sprintf("    %2.2i:%2.2li", hours, run);
290  }
291  return(out);
292}
293
294/* hooks for doing memory allocation et. al. in owl */
295
296void owl_free(void *ptr)
297{
298  g_free(ptr);
299}
300
301char *owl_strdup(const char *s1)
302{
303  return(g_strdup(s1));
304}
305
306/* allocates memory and returns the string or null.
307 * caller must free the string.
308 */
309char *owl_sprintf(const char *fmt, ...)
310{
311  va_list ap;
312  char *ret = NULL;
313  va_start(ap, fmt);
314  ret = g_strdup_vprintf(fmt, ap);
315  va_end(ap);
316  return ret;
317}
318
319/* These are in order of their value in owl.h */
320static const struct {
321  int number;
322  const char *name;
323} color_map[] = {
324  {OWL_COLOR_INVALID, "invalid"},
325  {OWL_COLOR_DEFAULT, "default"},
326  {OWL_COLOR_BLACK, "black"},
327  {OWL_COLOR_RED, "red"},
328  {OWL_COLOR_GREEN, "green"},
329  {OWL_COLOR_YELLOW,"yellow"},
330  {OWL_COLOR_BLUE, "blue"},
331  {OWL_COLOR_MAGENTA, "magenta"},
332  {OWL_COLOR_CYAN, "cyan"},
333  {OWL_COLOR_WHITE, "white"},
334};
335
336/* Return the owl color associated with the named color.  Return -1
337 * if the named color is not available
338 */
339int owl_util_string_to_color(const char *color)
340{
341  int c, i;
342  char *p;
343
344  for (i = 0; i < (sizeof(color_map)/sizeof(color_map[0])); i++)
345    if (strcasecmp(color, color_map[i].name) == 0)
346      return color_map[i].number;
347
348  c = strtol(color, &p, 10);
349  if (p != color && c >= -1 && c < COLORS) {
350    return(c);
351  }
352  return(OWL_COLOR_INVALID);
353}
354
355/* Return a string name of the given owl color */
356const char *owl_util_color_to_string(int color)
357{
358  if (color >= OWL_COLOR_INVALID && color <= OWL_COLOR_WHITE)
359    return color_map[color - OWL_COLOR_INVALID].name;
360  return("Unknown color");
361}
362
363/* Get the default tty name.  Caller must free the return */
364char *owl_util_get_default_tty(void)
365{
366  const char *tmp;
367  char *out;
368
369  if (getenv("DISPLAY")) {
370    out=owl_strdup(getenv("DISPLAY"));
371  } else if ((tmp=ttyname(fileno(stdout)))!=NULL) {
372    out=owl_strdup(tmp);
373    if (!strncmp(out, "/dev/", 5)) {
374      owl_free(out);
375      out=owl_strdup(tmp+5);
376    }
377  } else {
378    out=owl_strdup("unknown");
379  }
380  return(out);
381}
382
383/* strip leading and trailing new lines.  Caller must free the
384 * return.
385 */
386char *owl_util_stripnewlines(const char *in)
387{
388 
389  char  *tmp, *ptr1, *ptr2, *out;
390
391  ptr1=tmp=owl_strdup(in);
392  while (ptr1[0]=='\n') {
393    ptr1++;
394  }
395  ptr2=ptr1+strlen(ptr1)-1;
396  while (ptr2>ptr1 && ptr2[0]=='\n') {
397    ptr2[0]='\0';
398    ptr2--;
399  }
400
401  out=owl_strdup(ptr1);
402  owl_free(tmp);
403  return(out);
404}
405
406
407/* If filename is a link, recursively resolve symlinks.  Otherwise, return the filename
408 * unchanged.  On error, call owl_function_error and return NULL.
409 *
410 * This function assumes that filename eventually resolves to an acutal file.
411 * If you want to check this, you should stat() the file first.
412 *
413 * The caller of this function is responsible for freeing the return value.
414 *
415 * Error conditions are the same as g_file_read_link.
416 */
417gchar *owl_util_recursive_resolve_link(const char *filename)
418{
419  gchar *last_path = g_strdup(filename);
420  GError *err = NULL;
421
422  while (g_file_test(last_path, G_FILE_TEST_IS_SYMLINK)) {
423    gchar *link_path = g_file_read_link(last_path, &err);
424    if (link_path == NULL) {
425      owl_function_error("Cannot resolve symlink %s: %s",
426                         last_path, err->message);
427      g_error_free(err);
428      g_free(last_path);
429      return NULL;
430    }
431
432    /* Deal with obnoxious relative paths. If we really care, all this
433     * is racy. Whatever. */
434    if (!g_path_is_absolute(link_path)) {
435      char *last_dir = g_path_get_dirname(last_path);
436      char *tmp = g_build_path(G_DIR_SEPARATOR_S,
437                               last_dir,
438                               link_path,
439                               NULL);
440      g_free(last_dir);
441      g_free(link_path);
442      link_path = tmp;
443    }
444
445    g_free(last_path);
446    last_path = link_path;
447  }
448  return last_path;
449}
450
451/* Delete all lines matching "line" from the named file.  If no such
452 * line is found the file is left intact.  If backup==1 then leave a
453 * backup file containing the original contents.  The match is
454 * case-insensitive.
455 *
456 * Returns the number of lines removed on success.  Returns -1 on failure.
457 */
458int owl_util_file_deleteline(const char *filename, const char *line, int backup)
459{
460  char *backupfile, *newfile, *buf = NULL;
461  gchar *actual_filename; /* gchar; we need to g_free it */
462  FILE *old, *new;
463  struct stat st;
464  int numremoved = 0;
465
466  if ((old = fopen(filename, "r")) == NULL) {
467    owl_function_error("Cannot open %s (for reading): %s",
468                       filename, strerror(errno));
469    return -1;
470  }
471
472  if (fstat(fileno(old), &st) != 0) {
473    owl_function_error("Cannot stat %s: %s", filename, strerror(errno));
474    return -1;
475  }
476
477  /* resolve symlinks, because link() fails on symlinks, at least on AFS */
478  actual_filename = owl_util_recursive_resolve_link(filename);
479  if (actual_filename == NULL)
480    return -1; /* resolving the symlink failed, but we already logged this error */
481
482  newfile = owl_sprintf("%s.new", actual_filename);
483  if ((new = fopen(newfile, "w")) == NULL) {
484    owl_function_error("Cannot open %s (for writing): %s",
485                       actual_filename, strerror(errno));
486    owl_free(newfile);
487    fclose(old);
488    free(actual_filename);
489    return -1;
490  }
491
492  if (fchmod(fileno(new), st.st_mode & 0777) != 0) {
493    owl_function_error("Cannot set permissions on %s: %s",
494                       actual_filename, strerror(errno));
495    unlink(newfile);
496    fclose(new);
497    owl_free(newfile);
498    fclose(old);
499    free(actual_filename);
500    return -1;
501  }
502
503  while (owl_getline_chomp(&buf, old))
504    if (strcasecmp(buf, line) != 0)
505      fprintf(new, "%s\n", buf);
506    else
507      numremoved++;
508  owl_free(buf);
509
510  fclose(new);
511  fclose(old);
512
513  if (backup) {
514    backupfile = owl_sprintf("%s.backup", actual_filename);
515    unlink(backupfile);
516    if (link(actual_filename, backupfile) != 0) {
517      owl_function_error("Cannot link %s: %s", backupfile, strerror(errno));
518      owl_free(backupfile);
519      unlink(newfile);
520      owl_free(newfile);
521      return -1;
522    }
523    owl_free(backupfile);
524  }
525
526  if (rename(newfile, actual_filename) != 0) {
527    owl_function_error("Cannot move %s to %s: %s",
528                       newfile, actual_filename, strerror(errno));
529    numremoved = -1;
530  }
531
532  unlink(newfile);
533  owl_free(newfile);
534
535  g_free(actual_filename);
536
537  return numremoved;
538}
539
540/* Return the base class or instance from a zephyr class, by removing
541   leading `un' or trailing `.d'.
542   The caller is responsible for freeing the allocated string.
543*/
544char * owl_util_baseclass(const char * class)
545{
546  char *start, *end;
547
548  while(!strncmp(class, "un", 2)) {
549    class += 2;
550  }
551
552  start = owl_strdup(class);
553  end = start + strlen(start) - 1;
554  while(end > start && *end == 'd' && *(end-1) == '.') {
555    end -= 2;
556  }
557  *(end + 1) = 0;
558
559  return start;
560}
561
562const char * owl_get_datadir(void)
563{
564  const char * datadir = getenv("BARNOWL_DATA_DIR");
565  if(datadir != NULL)
566    return datadir;
567  return DATADIR;
568}
569
570const char * owl_get_bindir(void)
571{
572  const char * bindir = getenv("BARNOWL_BIN_DIR");
573  if(bindir != NULL)
574    return bindir;
575  return BINDIR;
576}
577
578/* Strips format characters from a valid utf-8 string. Returns the
579   empty string if 'in' does not validate. */
580char * owl_strip_format_chars(const char *in)
581{
582  char *r;
583  if (g_utf8_validate(in, -1, NULL)) {
584    const char *s, *p;
585    r = g_new(char, strlen(in)+1);
586    r[0] = '\0';
587    s = in;
588    p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
589    while(p) {
590      /* If it's a format character, copy up to it, and skip all
591         immediately following format characters. */
592      if (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
593        strncat(r, s, p-s);
594        p = g_utf8_next_char(p);
595        while (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
596          p = g_utf8_next_char(p);
597        }
598        s = p;
599        p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
600      }
601      else {
602        p = strchr(p+1, OWL_FMTEXT_UC_STARTBYTE_UTF8);
603      }
604    }
605    if (s) strcat(r,s);
606  }
607  else {
608    r = owl_strdup("");
609  }
610  return r;
611}
612
613/* If in is not UTF-8, convert from ISO-8859-1. We may want to allow
614 * the caller to specify an alternative in the future. We also strip
615 * out characters in Unicode Plane 16, as we use that plane internally
616 * for formatting.
617 */
618char * owl_validate_or_convert(const char *in)
619{
620  if (g_utf8_validate(in, -1, NULL)) {
621    return owl_strip_format_chars(in);
622  }
623  else {
624    return g_convert(in, -1,
625                     "UTF-8", "ISO-8859-1",
626                     NULL, NULL, NULL);
627  }
628}
629/*
630 * Validate 'in' as UTF-8, and either return a copy of it, or an empty
631 * string if it is invalid utf-8.
632 */
633char * owl_validate_utf8(const char *in)
634{
635  char *out;
636  if (g_utf8_validate(in, -1, NULL)) {
637    out = owl_strdup(in);
638  } else {
639    out = owl_strdup("");
640  }
641  return out;
642}
643
644/* This is based on _extract() and _isCJ() from perl's Text::WrapI18N */
645int owl_util_can_break_after(gunichar c)
646{
647 
648  if (c == ' ') return 1;
649  if (c >= 0x3000 && c <= 0x312f) {
650    /* CJK punctuations, Hiragana, Katakana, Bopomofo */
651    if (c == 0x300a || c == 0x300c || c == 0x300e ||
652        c == 0x3010 || c == 0x3014 || c == 0x3016 ||
653        c == 0x3018 || c == 0x301a)
654      return 0;
655    return 1;
656  }
657  if (c >= 0x31a0 && c <= 0x31bf) {return 1;}  /* Bopomofo */
658  if (c >= 0x31f0 && c <= 0x31ff) {return 1;}  /* Katakana extension */
659  if (c >= 0x3400 && c <= 0x9fff) {return 1;}  /* Han Ideogram */
660  if (c >= 0xf900 && c <= 0xfaff) {return 1;}  /* Han Ideogram */
661  if (c >= 0x20000 && c <= 0x2ffff) {return 1;}  /* Han Ideogram */
662  return 0;
663}
664
665char *owl_escape_highbit(const char *str)
666{
667  GString *out = g_string_new("");
668  unsigned char c;
669  while((c = (*str++))) {
670    if(c == '\\') {
671      g_string_append(out, "\\\\");
672    } else if(c & 0x80) {
673      g_string_append_printf(out, "\\x%02x", (int)c);
674    } else {
675      g_string_append_c(out, c);
676    }
677  }
678  return g_string_free(out, 0);
679}
680
681/* innards of owl_getline{,_chomp} below */
682static int owl_getline_internal(char **s, FILE *fp, int newline)
683{
684  int size = 0;
685  int target = 0;
686  int count = 0;
687  int c;
688
689  while (1) {
690    c = getc(fp);
691    if ((target + 1) > size) {
692      size += BUFSIZ;
693      *s = g_renew(char, *s, size);
694    }
695    if (c == EOF)
696      break;
697    count++;
698    if (c != '\n' || newline)
699        (*s)[target++] = c;
700    if (c == '\n')
701      break;
702  }
703  (*s)[target] = 0;
704
705  return count;
706}
707
708/* Read a line from fp, allocating memory to hold it, returning the number of
709 * byte read.  *s should either be NULL or a pointer to memory allocated with
710 * g_malloc; it will be g_renew'd as appropriate.  The caller must
711 * eventually free it.  (This is roughly the interface of getline in the gnu
712 * libc).
713 *
714 * The final newline will be included if it's there.
715 */
716int owl_getline(char **s, FILE *fp)
717{
718  return owl_getline_internal(s, fp, 1);
719}
720
721/* As above, but omitting the final newline */
722int owl_getline_chomp(char **s, FILE *fp)
723{
724  return owl_getline_internal(s, fp, 0);
725}
726
727/* Read the rest of the input available in fp into a string. */
728char *owl_slurp(FILE *fp)
729{
730  char *buf = NULL;
731  char *p;
732  int size = 0;
733  int count;
734
735  while (1) {
736    buf = g_renew(char, buf, size + BUFSIZ);
737    p = &buf[size];
738    size += BUFSIZ;
739
740    if ((count = fread(p, 1, BUFSIZ, fp)) < BUFSIZ)
741      break;
742  }
743  p[count] = 0;
744
745  return buf;
746}
747
748gulong owl_dirty_window_on_signal(owl_window *w, gpointer sender, const gchar *detailed_signal)
749{
750  return owl_signal_connect_object(sender, detailed_signal, G_CALLBACK(owl_window_dirty), w, G_CONNECT_SWAPPED);
751}
752
753typedef struct { /*noproto*/
754  GObject  *sender;
755  gulong    signal_id;
756} SignalData;
757
758static void _closure_invalidated(gpointer data, GClosure *closure);
759
760/*
761 * GObject's g_signal_connect_object has a documented bug. This function is
762 * identical except it does not leak the signal handler.
763 */
764gulong owl_signal_connect_object(gpointer sender, const gchar *detailed_signal, GCallback c_handler, gpointer receiver, GConnectFlags connect_flags)
765{
766  g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (sender), 0);
767  g_return_val_if_fail (detailed_signal != NULL, 0);
768  g_return_val_if_fail (c_handler != NULL, 0);
769
770  if (receiver) {
771    SignalData *sdata;
772    GClosure *closure;
773    gulong signal_id;
774
775    g_return_val_if_fail (G_IS_OBJECT (receiver), 0);
776
777    closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, receiver);
778    signal_id = g_signal_connect_closure (sender, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
779
780    /* Register the missing hooks */
781    sdata = g_slice_new0(SignalData);
782    sdata->sender = sender;
783    sdata->signal_id = signal_id;
784
785    g_closure_add_invalidate_notifier(closure, sdata, _closure_invalidated);
786
787    return signal_id;
788  } else {
789    return g_signal_connect_data(sender, detailed_signal, c_handler, NULL, NULL, connect_flags);
790  }
791}
792
793/*
794 * There are three ways the signal could come to an end:
795 *
796 * 1. The user explicitly disconnects it with the returned signal_id.
797 *    - In that case, the disconnection unref's the closure, causing it
798 *      to first be invalidated. The handler's already disconnected, so
799 *      we have no work to do.
800 * 2. The sender gets destroyed.
801 *    - GObject will disconnect each signal which then goes into the above
802 *      case. Our handler does no work.
803 * 3. The receiver gets destroyed.
804 *    - The GClosure was created by g_cclosure_new_object_{,swap} which gets
805 *      invalidated when the receiver is destroyed. We then follow through case 1
806 *      again, but *this* time, the handler has not been disconnected. We then
807 *      clean up ourselves.
808 *
809 * We can't actually hook into this process earlier with weakrefs as GObject
810 * will, on object dispose, first disconnect signals, then invalidate closures,
811 * and notify weakrefs last.
812 */
813static void _closure_invalidated(gpointer data, GClosure *closure)
814{
815  SignalData *sdata = data;
816  if (g_signal_handler_is_connected(sdata->sender, sdata->signal_id)) {
817    g_signal_handler_disconnect(sdata->sender, sdata->signal_id);
818  }
819  g_slice_free(SignalData, sdata);
820}
821
Note: See TracBrowser for help on using the repository browser.