source: util.c @ 055e366

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