source: util.c @ a5f477c

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