source: util.c @ 30d0cf7

release-1.10release-1.8release-1.9
Last change on this file since 30d0cf7 was c0c48d14, checked in by David Benjamin <davidben@mit.edu>, 13 years ago
Reimplement owl_util_makepath The new algorithm is cleaner and much more reasonable. foo/~/bar should not expand the ~. Also don't expand '~user /bar' as '/home/user /bar'. Also leave non-existant users unexpanded. It still has some finicky bits of string manipulations, but what can you do. A unit test is coming in the next commit.
  • Property mode set to 100644
File size: 20.5 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_path(G_DIR_SEPARATOR_S,
391                               last_dir,
392                               link_path,
393                               NULL);
394      g_free(last_dir);
395      g_free(link_path);
396      link_path = tmp;
397    }
398
399    g_free(last_path);
400    last_path = link_path;
401  }
402  return last_path;
403}
404
405/* Delete all lines matching "line" from the named file.  If no such
406 * line is found the file is left intact.  If backup==1 then leave a
407 * backup file containing the original contents.  The match is
408 * case-insensitive.
409 *
410 * Returns the number of lines removed on success.  Returns -1 on failure.
411 */
412int owl_util_file_deleteline(const char *filename, const char *line, int backup)
413{
414  char *backupfile, *newfile, *buf = NULL;
415  gchar *actual_filename; /* gchar; we need to g_free it */
416  FILE *old, *new;
417  struct stat st;
418  int numremoved = 0;
419
420  if ((old = fopen(filename, "r")) == NULL) {
421    owl_function_error("Cannot open %s (for reading): %s",
422                       filename, strerror(errno));
423    return -1;
424  }
425
426  if (fstat(fileno(old), &st) != 0) {
427    owl_function_error("Cannot stat %s: %s", filename, strerror(errno));
428    return -1;
429  }
430
431  /* resolve symlinks, because link() fails on symlinks, at least on AFS */
432  actual_filename = owl_util_recursive_resolve_link(filename);
433  if (actual_filename == NULL)
434    return -1; /* resolving the symlink failed, but we already logged this error */
435
436  newfile = g_strdup_printf("%s.new", actual_filename);
437  if ((new = fopen(newfile, "w")) == NULL) {
438    owl_function_error("Cannot open %s (for writing): %s",
439                       actual_filename, strerror(errno));
440    g_free(newfile);
441    fclose(old);
442    g_free(actual_filename);
443    return -1;
444  }
445
446  if (fchmod(fileno(new), st.st_mode & 0777) != 0) {
447    owl_function_error("Cannot set permissions on %s: %s",
448                       actual_filename, strerror(errno));
449    unlink(newfile);
450    fclose(new);
451    g_free(newfile);
452    fclose(old);
453    g_free(actual_filename);
454    return -1;
455  }
456
457  while (owl_getline_chomp(&buf, old))
458    if (strcasecmp(buf, line) != 0)
459      fprintf(new, "%s\n", buf);
460    else
461      numremoved++;
462  g_free(buf);
463
464  fclose(new);
465  fclose(old);
466
467  if (backup) {
468    backupfile = g_strdup_printf("%s.backup", actual_filename);
469    unlink(backupfile);
470    if (link(actual_filename, backupfile) != 0) {
471      owl_function_error("Cannot link %s: %s", backupfile, strerror(errno));
472      g_free(backupfile);
473      unlink(newfile);
474      g_free(newfile);
475      return -1;
476    }
477    g_free(backupfile);
478  }
479
480  if (rename(newfile, actual_filename) != 0) {
481    owl_function_error("Cannot move %s to %s: %s",
482                       newfile, actual_filename, strerror(errno));
483    numremoved = -1;
484  }
485
486  unlink(newfile);
487  g_free(newfile);
488
489  g_free(actual_filename);
490
491  return numremoved;
492}
493
494/* Return the base class or instance from a zephyr class, by removing
495   leading `un' or trailing `.d'.
496   The caller is responsible for freeing the allocated string.
497*/
498CALLER_OWN char *owl_util_baseclass(const char *class)
499{
500  char *start, *end;
501
502  while(!strncmp(class, "un", 2)) {
503    class += 2;
504  }
505
506  start = g_strdup(class);
507  end = start + strlen(start) - 1;
508  while(end > start && *end == 'd' && *(end-1) == '.') {
509    end -= 2;
510  }
511  *(end + 1) = 0;
512
513  return start;
514}
515
516const char * owl_get_datadir(void)
517{
518  const char * datadir = getenv("BARNOWL_DATA_DIR");
519  if(datadir != NULL)
520    return datadir;
521  return DATADIR;
522}
523
524const char * owl_get_bindir(void)
525{
526  const char * bindir = getenv("BARNOWL_BIN_DIR");
527  if(bindir != NULL)
528    return bindir;
529  return BINDIR;
530}
531
532/* Strips format characters from a valid utf-8 string. Returns the
533   empty string if 'in' does not validate.  Caller must free the return. */
534CALLER_OWN char *owl_strip_format_chars(const char *in)
535{
536  char *r;
537  if (g_utf8_validate(in, -1, NULL)) {
538    const char *s, *p;
539    r = g_new(char, strlen(in)+1);
540    r[0] = '\0';
541    s = in;
542    p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
543    while(p) {
544      /* If it's a format character, copy up to it, and skip all
545         immediately following format characters. */
546      if (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
547        strncat(r, s, p-s);
548        p = g_utf8_next_char(p);
549        while (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
550          p = g_utf8_next_char(p);
551        }
552        s = p;
553        p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
554      }
555      else {
556        p = strchr(p+1, OWL_FMTEXT_UC_STARTBYTE_UTF8);
557      }
558    }
559    if (s) strcat(r,s);
560  }
561  else {
562    r = g_strdup("");
563  }
564  return r;
565}
566
567/* If in is not UTF-8, convert from ISO-8859-1. We may want to allow
568 * the caller to specify an alternative in the future. We also strip
569 * out characters in Unicode Plane 16, as we use that plane internally
570 * for formatting.
571 * Caller must free the return.
572 */
573CALLER_OWN char *owl_validate_or_convert(const char *in)
574{
575  if (g_utf8_validate(in, -1, NULL)) {
576    return owl_strip_format_chars(in);
577  }
578  else {
579    return g_convert(in, -1,
580                     "UTF-8", "ISO-8859-1",
581                     NULL, NULL, NULL);
582  }
583}
584/*
585 * Validate 'in' as UTF-8, and either return a copy of it, or an empty
586 * string if it is invalid utf-8.
587 * Caller must free the return.
588 */
589CALLER_OWN char *owl_validate_utf8(const char *in)
590{
591  char *out;
592  if (g_utf8_validate(in, -1, NULL)) {
593    out = g_strdup(in);
594  } else {
595    out = g_strdup("");
596  }
597  return out;
598}
599
600/* This is based on _extract() and _isCJ() from perl's Text::WrapI18N */
601int owl_util_can_break_after(gunichar c)
602{
603 
604  if (c == ' ') return 1;
605  if (c >= 0x3000 && c <= 0x312f) {
606    /* CJK punctuations, Hiragana, Katakana, Bopomofo */
607    if (c == 0x300a || c == 0x300c || c == 0x300e ||
608        c == 0x3010 || c == 0x3014 || c == 0x3016 ||
609        c == 0x3018 || c == 0x301a)
610      return 0;
611    return 1;
612  }
613  if (c >= 0x31a0 && c <= 0x31bf) {return 1;}  /* Bopomofo */
614  if (c >= 0x31f0 && c <= 0x31ff) {return 1;}  /* Katakana extension */
615  if (c >= 0x3400 && c <= 0x9fff) {return 1;}  /* Han Ideogram */
616  if (c >= 0xf900 && c <= 0xfaff) {return 1;}  /* Han Ideogram */
617  if (c >= 0x20000 && c <= 0x2ffff) {return 1;}  /* Han Ideogram */
618  return 0;
619}
620
621/* caller must free the return */
622CALLER_OWN char *owl_escape_highbit(const char *str)
623{
624  GString *out = g_string_new("");
625  unsigned char c;
626  while((c = (*str++))) {
627    if(c == '\\') {
628      g_string_append(out, "\\\\");
629    } else if(c & 0x80) {
630      g_string_append_printf(out, "\\x%02x", (int)c);
631    } else {
632      g_string_append_c(out, c);
633    }
634  }
635  return g_string_free(out, 0);
636}
637
638/* innards of owl_getline{,_chomp} below */
639static int owl_getline_internal(char **s, FILE *fp, int newline)
640{
641  int size = 0;
642  int target = 0;
643  int count = 0;
644  int c;
645
646  while (1) {
647    c = getc(fp);
648    if ((target + 1) > size) {
649      size += BUFSIZ;
650      *s = g_renew(char, *s, size);
651    }
652    if (c == EOF)
653      break;
654    count++;
655    if (c != '\n' || newline)
656        (*s)[target++] = c;
657    if (c == '\n')
658      break;
659  }
660  (*s)[target] = 0;
661
662  return count;
663}
664
665/* Read a line from fp, allocating memory to hold it, returning the number of
666 * byte read.  *s should either be NULL or a pointer to memory allocated with
667 * g_malloc; it will be g_renew'd as appropriate.  The caller must
668 * eventually free it.  (This is roughly the interface of getline in the gnu
669 * libc).
670 *
671 * The final newline will be included if it's there.
672 */
673int owl_getline(char **s, FILE *fp)
674{
675  return owl_getline_internal(s, fp, 1);
676}
677
678/* As above, but omitting the final newline */
679int owl_getline_chomp(char **s, FILE *fp)
680{
681  return owl_getline_internal(s, fp, 0);
682}
683
684/* Read the rest of the input available in fp into a string. */
685CALLER_OWN char *owl_slurp(FILE *fp)
686{
687  char *buf = NULL;
688  char *p;
689  int size = 0;
690  int count;
691
692  while (1) {
693    buf = g_renew(char, buf, size + BUFSIZ);
694    p = &buf[size];
695    size += BUFSIZ;
696
697    if ((count = fread(p, 1, BUFSIZ, fp)) < BUFSIZ)
698      break;
699  }
700  p[count] = 0;
701
702  return buf;
703}
704
705int owl_util_get_colorpairs(void) {
706#ifndef NCURSES_EXT_COLORS
707  /* Without ext-color support (an ABI change), ncurses only supports 256
708   * different color pairs. However, it gives us a larger number even if your
709   * ncurses is compiled without ext-color. */
710  return MIN(COLOR_PAIRS, 256);
711#else
712  return COLOR_PAIRS;
713#endif
714}
715
716gulong owl_dirty_window_on_signal(owl_window *w, gpointer sender, const gchar *detailed_signal)
717{
718  return owl_signal_connect_object(sender, detailed_signal, G_CALLBACK(owl_window_dirty), w, G_CONNECT_SWAPPED);
719}
720
721typedef struct { /*noproto*/
722  GObject  *sender;
723  gulong    signal_id;
724} SignalData;
725
726static void _closure_invalidated(gpointer data, GClosure *closure);
727
728/*
729 * GObject's g_signal_connect_object has a documented bug. This function is
730 * identical except it does not leak the signal handler.
731 */
732gulong owl_signal_connect_object(gpointer sender, const gchar *detailed_signal, GCallback c_handler, gpointer receiver, GConnectFlags connect_flags)
733{
734  g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (sender), 0);
735  g_return_val_if_fail (detailed_signal != NULL, 0);
736  g_return_val_if_fail (c_handler != NULL, 0);
737
738  if (receiver) {
739    SignalData *sdata;
740    GClosure *closure;
741    gulong signal_id;
742
743    g_return_val_if_fail (G_IS_OBJECT (receiver), 0);
744
745    closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, receiver);
746    signal_id = g_signal_connect_closure (sender, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
747
748    /* Register the missing hooks */
749    sdata = g_slice_new0(SignalData);
750    sdata->sender = sender;
751    sdata->signal_id = signal_id;
752
753    g_closure_add_invalidate_notifier(closure, sdata, _closure_invalidated);
754
755    return signal_id;
756  } else {
757    return g_signal_connect_data(sender, detailed_signal, c_handler, NULL, NULL, connect_flags);
758  }
759}
760
761/*
762 * There are three ways the signal could come to an end:
763 *
764 * 1. The user explicitly disconnects it with the returned signal_id.
765 *    - In that case, the disconnection unref's the closure, causing it
766 *      to first be invalidated. The handler's already disconnected, so
767 *      we have no work to do.
768 * 2. The sender gets destroyed.
769 *    - GObject will disconnect each signal which then goes into the above
770 *      case. Our handler does no work.
771 * 3. The receiver gets destroyed.
772 *    - The GClosure was created by g_cclosure_new_object_{,swap} which gets
773 *      invalidated when the receiver is destroyed. We then follow through case 1
774 *      again, but *this* time, the handler has not been disconnected. We then
775 *      clean up ourselves.
776 *
777 * We can't actually hook into this process earlier with weakrefs as GObject
778 * will, on object dispose, first disconnect signals, then invalidate closures,
779 * and notify weakrefs last.
780 */
781static void _closure_invalidated(gpointer data, GClosure *closure)
782{
783  SignalData *sdata = data;
784  if (g_signal_handler_is_connected(sdata->sender, sdata->signal_id)) {
785    g_signal_handler_disconnect(sdata->sender, sdata->signal_id);
786  }
787  g_slice_free(SignalData, sdata);
788}
789
Note: See TracBrowser for help on using the repository browser.