source: util.c @ 0290b2a

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