source: util.c @ a223b6b

release-1.10release-1.9
Last change on this file since a223b6b was 7b89e8c, checked in by David Benjamin <davidben@mit.edu>, 13 years ago
Add owl_argv_quote convenience function Did we really never write this thing?
  • Property mode set to 100644
File size: 22.0 KB
Line 
1#include "owl.h"
2#include <pwd.h>
3#include <sys/stat.h>
4#include <stdarg.h>
5#include <glib/gstdio.h>
6#include <glib-object.h>
7
8const char *skiptokens(const char *buff, int n) {
9  /* skips n tokens and returns where that would be. */
10  char quote = 0;
11  while (*buff && n>0) {
12      while (*buff == ' ') buff++;
13      while (*buff && (quote || *buff != ' ')) {
14        if(quote) {
15          if(*buff == quote) quote = 0;
16        } else if(*buff == '"' || *buff == '\'') {
17          quote = *buff;
18        }
19        buff++;
20      }
21      while (*buff == ' ') buff++;
22      n--;
23  }
24  return buff;
25}
26
27CALLER_OWN char *owl_util_homedir_for_user(const char *name)
28{
29  int err;
30  struct passwd pw_buf;
31  struct passwd *pw;
32
33  char *pw_strbuf, *ret;
34  long pw_strbuf_len = sysconf(_SC_GETPW_R_SIZE_MAX);
35  if (pw_strbuf_len < 0) {
36    /* If we really hate ourselves, we can be fancy and loop until we stop
37     * getting ERANGE. For now just pick a random number. */
38    owl_function_error("owl_util_homedir_for_user: Could not get _SC_GETPW_R_SIZE_MAX");
39    pw_strbuf_len = 16384;
40  }
41  pw_strbuf = g_new0(char, pw_strbuf_len);
42  err = getpwnam_r(name, &pw_buf, pw_strbuf, pw_strbuf_len, &pw);
43  if (err) {
44    owl_function_error("getpwuid_r: %s", strerror(err));
45    /* Fall through; pw will be NULL. */
46  }
47  ret = pw ? g_strdup(pw->pw_dir) : NULL;
48  g_free(pw_strbuf);
49  return ret;
50}
51
52/* Return a "nice" version of the path.  Tilde expansion is done, and
53 * duplicate slashes are removed.  Caller must free the return.
54 */
55CALLER_OWN char *owl_util_makepath(const char *in)
56{
57  char *out;
58  int i, j;
59  if (in[0] == '~') {
60    /* Attempt tilde-expansion of the first component. Get the
61       tilde-prefix, which goes up to the next slash. */
62    const char *end = strchr(in + 1, '/');
63    if (end == NULL)
64      end = in + strlen(in);
65
66    /* Patch together a new path. Replace the ~ and tilde-prefix with
67       the homedir, if available. */
68    if (end == in + 1) {
69      /* My home directory. Use the one in owl_global for consistency with
70       * owl_zephyr_dotfile. */
71      out = g_strconcat(owl_global_get_homedir(&g), end, NULL);
72    } else {
73      /* Someone else's home directory. */
74      char *user = g_strndup(in + 1, end - (in + 1));
75      char *home = owl_util_homedir_for_user(user);
76      if (home) {
77        out = g_strconcat(home, end, NULL);
78      } else {
79        out = g_strdup(in);
80      }
81      g_free(home);
82      g_free(user);
83    }
84  } else {
85    out = g_strdup(in);
86  }
87
88  /* And a quick pass to remove duplicate slashes. */
89  for (i = j = 0; out[i] != '\0'; i++) {
90    if (out[i] != '/' || i == 0 || out[i-1] != '/')
91      out[j++] = out[i];
92  }
93  out[j] = '\0';
94  return out;
95}
96
97void owl_ptr_array_free(GPtrArray *array, GDestroyNotify element_free_func)
98{
99  /* TODO: when we move to requiring glib 2.22+, use
100   * g_ptr_array_new_with_free_func instead. */
101  if (element_free_func)
102    g_ptr_array_foreach(array, (GFunc)element_free_func, NULL);
103  g_ptr_array_free(array, true);
104}
105
106/* Break a command line up into argv, argc.  The caller must free
107   the returned values with g_strfreev.  If there is an error argc will be set
108   to -1, argv will be NULL and the caller does not need to free anything. The
109   returned vector is NULL-terminated. */
110CALLER_OWN char **owl_parseline(const char *line, int *argc)
111{
112  GPtrArray *argv;
113  int i, len, between=1;
114  GString *curarg;
115  char quote;
116
117  argv = g_ptr_array_new();
118  len=strlen(line);
119  curarg = g_string_new("");
120  quote='\0';
121  if (argc) *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  if (argc) *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    owl_ptr_array_free(argv, g_free);
179    if (argc) *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
250CALLER_OWN char *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 g_free. */
262CALLER_OWN char *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/* Returns a quoted version of argv. owl_parseline on the result should give
270 * back the input. */
271CALLER_OWN char *owl_argv_quote(int argc, const char *const *argv)
272{
273  int i;
274  GString *buf = g_string_new("");
275  for (i = 0; i < argc; i++) {
276    if (i > 0)
277      g_string_append_c(buf, ' ');
278    owl_string_append_quoted_arg(buf, argv[i]);
279  }
280  return g_string_free(buf, false);
281}
282
283/* caller must free the return */
284CALLER_OWN char *owl_util_format_minutes(int in)
285{
286  int days, hours;
287  long run;
288  char *out;
289
290  run=in;
291
292  days=run/1440;
293  run-=days*1440;
294  hours=run/60;
295  run-=hours*60;
296
297  if (days>0) {
298    out=g_strdup_printf("%i d %2.2i:%2.2li", days, hours, run);
299  } else {
300    out=g_strdup_printf("    %2.2i:%2.2li", hours, run);
301  }
302  return(out);
303}
304
305CALLER_OWN char *owl_util_format_time(const struct tm *time)
306{
307  /* 32 chosen for first attempt because timestr will end up being
308   * something like "Www Mmm dd hh:mm:ss AM yyyy UTC\0" */ 
309  size_t timestr_size = 16;
310  char *timestr = NULL;
311  do {
312    timestr_size *= 2;
313    timestr = g_renew(char, timestr, timestr_size);
314  } while (strftime(timestr, timestr_size, "%c", time) == 0);
315  return timestr;
316}
317
318/* These are in order of their value in owl.h */
319static const struct {
320  int number;
321  const char *name;
322} color_map[] = {
323  {OWL_COLOR_INVALID, "invalid"},
324  {OWL_COLOR_DEFAULT, "default"},
325  {OWL_COLOR_BLACK, "black"},
326  {OWL_COLOR_RED, "red"},
327  {OWL_COLOR_GREEN, "green"},
328  {OWL_COLOR_YELLOW,"yellow"},
329  {OWL_COLOR_BLUE, "blue"},
330  {OWL_COLOR_MAGENTA, "magenta"},
331  {OWL_COLOR_CYAN, "cyan"},
332  {OWL_COLOR_WHITE, "white"},
333};
334
335/* Return the owl color associated with the named color.  Return -1
336 * if the named color is not available
337 */
338int owl_util_string_to_color(const char *color)
339{
340  int c, i;
341  char *p;
342
343  for (i = 0; i < (sizeof(color_map)/sizeof(color_map[0])); i++)
344    if (strcasecmp(color, color_map[i].name) == 0)
345      return color_map[i].number;
346
347  c = strtol(color, &p, 10);
348  if (p != color && c >= -1 && c < COLORS) {
349    return(c);
350  }
351  return(OWL_COLOR_INVALID);
352}
353
354/* Return a string name of the given owl color */
355const char *owl_util_color_to_string(int color)
356{
357  if (color >= OWL_COLOR_INVALID && color <= OWL_COLOR_WHITE)
358    return color_map[color - OWL_COLOR_INVALID].name;
359  return("Unknown color");
360}
361
362/* Get the default tty name.  Caller must free the return */
363CALLER_OWN char *owl_util_get_default_tty(void)
364{
365  const char *tmp;
366  char *out;
367
368  if (getenv("DISPLAY")) {
369    out=g_strdup(getenv("DISPLAY"));
370  } else if ((tmp=ttyname(fileno(stdout)))!=NULL) {
371    out=g_strdup(tmp);
372    if (!strncmp(out, "/dev/", 5)) {
373      g_free(out);
374      out=g_strdup(tmp+5);
375    }
376  } else {
377    out=g_strdup("unknown");
378  }
379  return(out);
380}
381
382/* strip leading and trailing new lines.  Caller must free the
383 * return.
384 */
385CALLER_OWN char *owl_util_stripnewlines(const char *in)
386{
387 
388  char  *tmp, *ptr1, *ptr2, *out;
389
390  ptr1=tmp=g_strdup(in);
391  while (ptr1[0]=='\n') {
392    ptr1++;
393  }
394  ptr2=ptr1+strlen(ptr1)-1;
395  while (ptr2>ptr1 && ptr2[0]=='\n') {
396    ptr2[0]='\0';
397    ptr2--;
398  }
399
400  out=g_strdup(ptr1);
401  g_free(tmp);
402  return(out);
403}
404
405
406/* If filename is a link, recursively resolve symlinks.  Otherwise, return the filename
407 * unchanged.  On error, call owl_function_error and return NULL.
408 *
409 * This function assumes that filename eventually resolves to an acutal file.
410 * If you want to check this, you should stat() the file first.
411 *
412 * The caller of this function is responsible for freeing the return value.
413 *
414 * Error conditions are the same as g_file_read_link.
415 */
416CALLER_OWN gchar *owl_util_recursive_resolve_link(const char *filename)
417{
418  gchar *last_path = g_strdup(filename);
419  GError *err = NULL;
420
421  while (g_file_test(last_path, G_FILE_TEST_IS_SYMLINK)) {
422    gchar *link_path = g_file_read_link(last_path, &err);
423    if (link_path == NULL) {
424      owl_function_error("Cannot resolve symlink %s: %s",
425                         last_path, err->message);
426      g_error_free(err);
427      g_free(last_path);
428      return NULL;
429    }
430
431    /* Deal with obnoxious relative paths. If we really care, all this
432     * is racy. Whatever. */
433    if (!g_path_is_absolute(link_path)) {
434      char *last_dir = g_path_get_dirname(last_path);
435      char *tmp = g_build_filename(last_dir, link_path, NULL);
436      g_free(last_dir);
437      g_free(link_path);
438      link_path = tmp;
439    }
440
441    g_free(last_path);
442    last_path = link_path;
443  }
444  return last_path;
445}
446
447/* Delete all lines matching "line" from the named file.  If no such
448 * line is found the file is left intact.  If backup==1 then leave a
449 * backup file containing the original contents.  The match is
450 * case-insensitive.
451 *
452 * Returns the number of lines removed on success.  Returns -1 on failure.
453 */
454int owl_util_file_deleteline(const char *filename, const char *line, int backup)
455{
456  char *backupfile, *newfile, *buf = NULL;
457  gchar *actual_filename; /* gchar; we need to g_free it */
458  FILE *old, *new;
459  struct stat st;
460  int numremoved = 0;
461
462  if ((old = fopen(filename, "r")) == NULL) {
463    owl_function_error("Cannot open %s (for reading): %s",
464                       filename, strerror(errno));
465    return -1;
466  }
467
468  if (fstat(fileno(old), &st) != 0) {
469    owl_function_error("Cannot stat %s: %s", filename, strerror(errno));
470    return -1;
471  }
472
473  /* resolve symlinks, because link() fails on symlinks, at least on AFS */
474  actual_filename = owl_util_recursive_resolve_link(filename);
475  if (actual_filename == NULL)
476    return -1; /* resolving the symlink failed, but we already logged this error */
477
478  newfile = g_strdup_printf("%s.new", actual_filename);
479  if ((new = fopen(newfile, "w")) == NULL) {
480    owl_function_error("Cannot open %s (for writing): %s",
481                       actual_filename, strerror(errno));
482    g_free(newfile);
483    fclose(old);
484    g_free(actual_filename);
485    return -1;
486  }
487
488  if (fchmod(fileno(new), st.st_mode & 0777) != 0) {
489    owl_function_error("Cannot set permissions on %s: %s",
490                       actual_filename, strerror(errno));
491    unlink(newfile);
492    fclose(new);
493    g_free(newfile);
494    fclose(old);
495    g_free(actual_filename);
496    return -1;
497  }
498
499  while (owl_getline_chomp(&buf, old))
500    if (strcasecmp(buf, line) != 0)
501      fprintf(new, "%s\n", buf);
502    else
503      numremoved++;
504  g_free(buf);
505
506  fclose(new);
507  fclose(old);
508
509  if (backup) {
510    backupfile = g_strdup_printf("%s.backup", actual_filename);
511    unlink(backupfile);
512    if (link(actual_filename, backupfile) != 0) {
513      owl_function_error("Cannot link %s: %s", backupfile, strerror(errno));
514      g_free(backupfile);
515      unlink(newfile);
516      g_free(newfile);
517      return -1;
518    }
519    g_free(backupfile);
520  }
521
522  if (rename(newfile, actual_filename) != 0) {
523    owl_function_error("Cannot move %s to %s: %s",
524                       newfile, actual_filename, strerror(errno));
525    numremoved = -1;
526  }
527
528  unlink(newfile);
529  g_free(newfile);
530
531  g_free(actual_filename);
532
533  return numremoved;
534}
535
536/* Return the base class or instance from a zephyr class, by removing
537   leading `un' or trailing `.d'.
538   The caller is responsible for freeing the allocated string.
539*/
540CALLER_OWN char *owl_util_baseclass(const char *class)
541{
542  char *start, *end;
543
544  while(!strncmp(class, "un", 2)) {
545    class += 2;
546  }
547
548  start = g_strdup(class);
549  end = start + strlen(start) - 1;
550  while(end > start && *end == 'd' && *(end-1) == '.') {
551    end -= 2;
552  }
553  *(end + 1) = 0;
554
555  return start;
556}
557
558const char * owl_get_datadir(void)
559{
560  const char * datadir = getenv("BARNOWL_DATA_DIR");
561  if(datadir != NULL)
562    return datadir;
563  return DATADIR;
564}
565
566const char * owl_get_bindir(void)
567{
568  const char * bindir = getenv("BARNOWL_BIN_DIR");
569  if(bindir != NULL)
570    return bindir;
571  return BINDIR;
572}
573
574/* Strips format characters from a valid utf-8 string. Returns the
575   empty string if 'in' does not validate.  Caller must free the return. */
576CALLER_OWN char *owl_strip_format_chars(const char *in)
577{
578  char *r;
579  if (g_utf8_validate(in, -1, NULL)) {
580    const char *s, *p;
581    r = g_new(char, strlen(in)+1);
582    r[0] = '\0';
583    s = in;
584    p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
585    while(p) {
586      /* If it's a format character, copy up to it, and skip all
587         immediately following format characters. */
588      if (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
589        strncat(r, s, p-s);
590        p = g_utf8_next_char(p);
591        while (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
592          p = g_utf8_next_char(p);
593        }
594        s = p;
595        p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
596      }
597      else {
598        p = strchr(p+1, OWL_FMTEXT_UC_STARTBYTE_UTF8);
599      }
600    }
601    if (s) strcat(r,s);
602  }
603  else {
604    r = g_strdup("");
605  }
606  return r;
607}
608
609/* If in is not UTF-8, convert from ISO-8859-1. We may want to allow
610 * the caller to specify an alternative in the future. We also strip
611 * out characters in Unicode Plane 16, as we use that plane internally
612 * for formatting.
613 * Caller must free the return.
614 */
615CALLER_OWN char *owl_validate_or_convert(const char *in)
616{
617  if (g_utf8_validate(in, -1, NULL)) {
618    return owl_strip_format_chars(in);
619  }
620  else {
621    return g_convert(in, -1,
622                     "UTF-8", "ISO-8859-1",
623                     NULL, NULL, NULL);
624  }
625}
626/*
627 * Validate 'in' as UTF-8, and either return a copy of it, or an empty
628 * string if it is invalid utf-8.
629 * Caller must free the return.
630 */
631CALLER_OWN char *owl_validate_utf8(const char *in)
632{
633  char *out;
634  if (g_utf8_validate(in, -1, NULL)) {
635    out = g_strdup(in);
636  } else {
637    out = g_strdup("");
638  }
639  return out;
640}
641
642/* This is based on _extract() and _isCJ() from perl's Text::WrapI18N */
643int owl_util_can_break_after(gunichar c)
644{
645 
646  if (c == ' ') return 1;
647  if (c >= 0x3000 && c <= 0x312f) {
648    /* CJK punctuations, Hiragana, Katakana, Bopomofo */
649    if (c == 0x300a || c == 0x300c || c == 0x300e ||
650        c == 0x3010 || c == 0x3014 || c == 0x3016 ||
651        c == 0x3018 || c == 0x301a)
652      return 0;
653    return 1;
654  }
655  if (c >= 0x31a0 && c <= 0x31bf) {return 1;}  /* Bopomofo */
656  if (c >= 0x31f0 && c <= 0x31ff) {return 1;}  /* Katakana extension */
657  if (c >= 0x3400 && c <= 0x9fff) {return 1;}  /* Han Ideogram */
658  if (c >= 0xf900 && c <= 0xfaff) {return 1;}  /* Han Ideogram */
659  if (c >= 0x20000 && c <= 0x2ffff) {return 1;}  /* Han Ideogram */
660  return 0;
661}
662
663/* caller must free the return */
664CALLER_OWN char *owl_escape_highbit(const char *str)
665{
666  GString *out = g_string_new("");
667  unsigned char c;
668  while((c = (*str++))) {
669    if(c == '\\') {
670      g_string_append(out, "\\\\");
671    } else if(c & 0x80) {
672      g_string_append_printf(out, "\\x%02x", (int)c);
673    } else {
674      g_string_append_c(out, c);
675    }
676  }
677  return g_string_free(out, 0);
678}
679
680/* innards of owl_getline{,_chomp} below */
681static int owl_getline_internal(char **s, FILE *fp, int newline)
682{
683  int size = 0;
684  int target = 0;
685  int count = 0;
686  int c;
687
688  while (1) {
689    c = getc(fp);
690    if ((target + 1) > size) {
691      size += BUFSIZ;
692      *s = g_renew(char, *s, size);
693    }
694    if (c == EOF)
695      break;
696    count++;
697    if (c != '\n' || newline)
698        (*s)[target++] = c;
699    if (c == '\n')
700      break;
701  }
702  (*s)[target] = 0;
703
704  return count;
705}
706
707/* Read a line from fp, allocating memory to hold it, returning the number of
708 * byte read.  *s should either be NULL or a pointer to memory allocated with
709 * g_malloc; it will be g_renew'd as appropriate.  The caller must
710 * eventually free it.  (This is roughly the interface of getline in the gnu
711 * libc).
712 *
713 * The final newline will be included if it's there.
714 */
715int owl_getline(char **s, FILE *fp)
716{
717  return owl_getline_internal(s, fp, 1);
718}
719
720/* As above, but omitting the final newline */
721int owl_getline_chomp(char **s, FILE *fp)
722{
723  return owl_getline_internal(s, fp, 0);
724}
725
726/* Read the rest of the input available in fp into a string. */
727CALLER_OWN char *owl_slurp(FILE *fp)
728{
729  char *buf = NULL;
730  char *p;
731  int size = 0;
732  int count;
733
734  while (1) {
735    buf = g_renew(char, buf, size + BUFSIZ);
736    p = &buf[size];
737    size += BUFSIZ;
738
739    if ((count = fread(p, 1, BUFSIZ, fp)) < BUFSIZ)
740      break;
741  }
742  p[count] = 0;
743
744  return buf;
745}
746
747int owl_util_get_colorpairs(void) {
748#ifndef NCURSES_EXT_COLORS
749  /* Without ext-color support (an ABI change), ncurses only supports 256
750   * different color pairs. However, it gives us a larger number even if your
751   * ncurses is compiled without ext-color. */
752  return MIN(COLOR_PAIRS, 256);
753#else
754  return COLOR_PAIRS;
755#endif
756}
757
758gulong owl_dirty_window_on_signal(owl_window *w, gpointer sender, const gchar *detailed_signal)
759{
760  return owl_signal_connect_object(sender, detailed_signal, G_CALLBACK(owl_window_dirty), w, G_CONNECT_SWAPPED);
761}
762
763typedef struct { /*noproto*/
764  GObject  *sender;
765  gulong    signal_id;
766} SignalData;
767
768static void _closure_invalidated(gpointer data, GClosure *closure);
769
770/*
771 * GObject's g_signal_connect_object has a documented bug. This function is
772 * identical except it does not leak the signal handler.
773 */
774gulong owl_signal_connect_object(gpointer sender, const gchar *detailed_signal, GCallback c_handler, gpointer receiver, GConnectFlags connect_flags)
775{
776  g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (sender), 0);
777  g_return_val_if_fail (detailed_signal != NULL, 0);
778  g_return_val_if_fail (c_handler != NULL, 0);
779
780  if (receiver) {
781    SignalData *sdata;
782    GClosure *closure;
783    gulong signal_id;
784
785    g_return_val_if_fail (G_IS_OBJECT (receiver), 0);
786
787    closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, receiver);
788    signal_id = g_signal_connect_closure (sender, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
789
790    /* Register the missing hooks */
791    sdata = g_slice_new0(SignalData);
792    sdata->sender = sender;
793    sdata->signal_id = signal_id;
794
795    g_closure_add_invalidate_notifier(closure, sdata, _closure_invalidated);
796
797    return signal_id;
798  } else {
799    return g_signal_connect_data(sender, detailed_signal, c_handler, NULL, NULL, connect_flags);
800  }
801}
802
803/*
804 * There are three ways the signal could come to an end:
805 *
806 * 1. The user explicitly disconnects it with the returned signal_id.
807 *    - In that case, the disconnection unref's the closure, causing it
808 *      to first be invalidated. The handler's already disconnected, so
809 *      we have no work to do.
810 * 2. The sender gets destroyed.
811 *    - GObject will disconnect each signal which then goes into the above
812 *      case. Our handler does no work.
813 * 3. The receiver gets destroyed.
814 *    - The GClosure was created by g_cclosure_new_object_{,swap} which gets
815 *      invalidated when the receiver is destroyed. We then follow through case 1
816 *      again, but *this* time, the handler has not been disconnected. We then
817 *      clean up ourselves.
818 *
819 * We can't actually hook into this process earlier with weakrefs as GObject
820 * will, on object dispose, first disconnect signals, then invalidate closures,
821 * and notify weakrefs last.
822 */
823static void _closure_invalidated(gpointer data, GClosure *closure)
824{
825  SignalData *sdata = data;
826  if (g_signal_handler_is_connected(sdata->sender, sdata->signal_id)) {
827    g_signal_handler_disconnect(sdata->sender, sdata->signal_id);
828  }
829  g_slice_free(SignalData, sdata);
830}
831
Note: See TracBrowser for help on using the repository browser.