source: util.c @ c0c48d14

release-1.8release-1.9
Last change on this file since c0c48d14 was c0c48d14, checked in by David Benjamin <davidben@mit.edu>, 10 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
RevLine 
[7d4fbcd]1#include "owl.h"
2#include <stdlib.h>
3#include <string.h>
[5145235]4#include <unistd.h>
[7d4fbcd]5#include <ctype.h>
[f36222f]6#include <pwd.h>
[435001d]7#include <sys/stat.h>
8#include <sys/types.h>
[950e2da]9#include <assert.h>
[f47696f]10#include <stdarg.h>
[950e2da]11#include <glib.h>
12#include <glib/gstdio.h>
[05ca0d8]13#include <glib-object.h>
14
[e19eb97]15const char *skiptokens(const char *buff, int n) {
[e30ed92]16  /* skips n tokens and returns where that would be. */
17  char quote = 0;
[7d4fbcd]18  while (*buff && n>0) {
19      while (*buff == ' ') buff++;
[e30ed92]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++;
[7d4fbcd]27      }
28      while (*buff == ' ') buff++;
29      n--;
30  }
31  return buff;
32}
33
[f36222f]34/* Return a "nice" version of the path.  Tilde expansion is done, and
35 * duplicate slashes are removed.  Caller must free the return.
36 */
[6829afc]37CALLER_OWN char *owl_util_makepath(const char *in)
[f36222f]38{
[c0c48d14]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);
[f36222f]48
[c0c48d14]49    if (end == in + 1) {
50      /* My home directory. */
51      pw = getpwuid(getuid());
[f36222f]52    } else {
[c0c48d14]53      /* Someone else's home directory. */
54      char *user = g_strndup(in + 1, end - (in + 1));
55      pw = getpwnam(user);
56      g_free(user);
[f36222f]57    }
[c0c48d14]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];
[f36222f]74  }
[c0c48d14]75  out[j] = '\0';
76  return out;
[f36222f]77}
78
[3cdd6d2]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
[e56303f]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. */
[6829afc]92CALLER_OWN char **owl_parseline(const char *line, int *argc)
[e4eebe8]93{
[65c753e]94  GPtrArray *argv;
[7d4fbcd]95  int i, len, between=1;
[0290b2a]96  GString *curarg;
[7d4fbcd]97  char quote;
98
[6965867]99  argv = g_ptr_array_new();
[7d4fbcd]100  len=strlen(line);
[0290b2a]101  curarg = g_string_new("");
[7d4fbcd]102  quote='\0';
[e56303f]103  if (argc) *argc=0;
[7d4fbcd]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 */
[0290b2a]131      g_string_append_c(curarg, line[i]);
[7d4fbcd]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') {
[0290b2a]137      g_string_append_c(curarg, line[i]);
[7d4fbcd]138      continue;
139    }
140
141    /* otherwise, if we're not in quotes, add the whole argument */
142    if (quote=='\0') {
143      /* add the argument */
[0290b2a]144      g_ptr_array_add(argv, g_string_free(curarg, false));
145      curarg = g_string_new("");
[7d4fbcd]146      between=1;
147      continue;
148    }
149
150    /* if it is a space and we're in quotes, then use it */
[0290b2a]151    g_string_append_c(curarg, line[i]);
[7d4fbcd]152  }
153
[e56303f]154  if (argc) *argc = argv->len;
[65c753e]155  g_ptr_array_add(argv, NULL);
[0290b2a]156  g_string_free(curarg, true);
[95caa16]157
[7d4fbcd]158  /* check for unbalanced quotes */
159  if (quote!='\0') {
[3cdd6d2]160    owl_ptr_array_free(argv, g_free);
[e56303f]161    if (argc) *argc = -1;
[7d4fbcd]162    return(NULL);
163  }
164
[65c753e]165  return (char**)g_ptr_array_free(argv, false);
[7d4fbcd]166}
167
[2bc6ad35]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
[f47696f]200/*
201 * Appends 'tmpl' to 'buf', replacing any instances of '%q' with arguments from
[b8a3e00]202 * the varargs provided, quoting them to be safe for placing in a BarnOwl
[f47696f]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
[6829afc]232CALLER_OWN char *owl_string_build_quoted(const char *tmpl, ...)
[f47696f]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
[2bc6ad35]242/* Returns a quoted version of arg suitable for placing in a
[ddbbcffa]243 * command-line. Result should be freed with g_free. */
[6829afc]244CALLER_OWN char *owl_arg_quote(const char *arg)
[2bc6ad35]245{
246  GString *buf = g_string_new("");;
247  owl_string_append_quoted_arg(buf, arg);
248  return g_string_free(buf, false);
249}
250
[de03334]251/* caller must free the return */
[6829afc]252CALLER_OWN char *owl_util_minutes_to_timestr(int in)
[de03334]253{
[f1e629d]254  int days, hours;
[de03334]255  long run;
256  char *out;
257
[5b85d19]258  run=in;
[de03334]259
[5b85d19]260  days=run/1440;
261  run-=days*1440;
262  hours=run/60;
263  run-=hours*60;
[de03334]264
265  if (days>0) {
[3472845]266    out=g_strdup_printf("%i d %2.2i:%2.2li", days, hours, run);
[de03334]267  } else {
[3472845]268    out=g_strdup_printf("    %2.2i:%2.2li", hours, run);
[de03334]269  }
270  return(out);
271}
272
[a3e61a2]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};
[28ee32b]289
[12c35df]290/* Return the owl color associated with the named color.  Return -1
291 * if the named color is not available
292 */
[e19eb97]293int owl_util_string_to_color(const char *color)
[e4eebe8]294{
[a3e61a2]295  int c, i;
[1b9d3cc]296  char *p;
[a3e61a2]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
[1b9d3cc]302  c = strtol(color, &p, 10);
303  if (p != color && c >= -1 && c < COLORS) {
[c2c5c77]304    return(c);
305  }
[601733d]306  return(OWL_COLOR_INVALID);
[7d4fbcd]307}
308
[e4eebe8]309/* Return a string name of the given owl color */
[e19eb97]310const char *owl_util_color_to_string(int color)
[e4eebe8]311{
[a3e61a2]312  if (color >= OWL_COLOR_INVALID && color <= OWL_COLOR_WHITE)
313    return color_map[color - OWL_COLOR_INVALID].name;
[7d4fbcd]314  return("Unknown color");
315}
[e1c4636]316
[e4eebe8]317/* Get the default tty name.  Caller must free the return */
[6829afc]318CALLER_OWN char *owl_util_get_default_tty(void)
[e4eebe8]319{
[e19eb97]320  const char *tmp;
[65b2173]321  char *out;
[61e79a9]322
323  if (getenv("DISPLAY")) {
[d4927a7]324    out=g_strdup(getenv("DISPLAY"));
[5145235]325  } else if ((tmp=ttyname(fileno(stdout)))!=NULL) {
[d4927a7]326    out=g_strdup(tmp);
[61e79a9]327    if (!strncmp(out, "/dev/", 5)) {
[ddbbcffa]328      g_free(out);
[d4927a7]329      out=g_strdup(tmp+5);
[61e79a9]330    }
331  } else {
[d4927a7]332    out=g_strdup("unknown");
[61e79a9]333  }
334  return(out);
335}
336
[e4eebe8]337/* strip leading and trailing new lines.  Caller must free the
338 * return.
339 */
[6829afc]340CALLER_OWN char *owl_util_stripnewlines(const char *in)
[e4eebe8]341{
[7e3e00a]342 
343  char  *tmp, *ptr1, *ptr2, *out;
344
[d4927a7]345  ptr1=tmp=g_strdup(in);
[7e3e00a]346  while (ptr1[0]=='\n') {
347    ptr1++;
348  }
349  ptr2=ptr1+strlen(ptr1)-1;
[1bb1e67]350  while (ptr2>ptr1 && ptr2[0]=='\n') {
[7e3e00a]351    ptr2[0]='\0';
352    ptr2--;
353  }
354
[d4927a7]355  out=g_strdup(ptr1);
[ddbbcffa]356  g_free(tmp);
[7e3e00a]357  return(out);
358}
359
[950e2da]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 */
[6829afc]371CALLER_OWN gchar *owl_util_recursive_resolve_link(const char *filename)
[950e2da]372{
[fa90c34]373  gchar *last_path = g_strdup(filename);
[950e2da]374  GError *err = NULL;
[fa90c34]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;
[950e2da]401  }
[fa90c34]402  return last_path;
[950e2da]403}
404
[946058b]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.
[da60ba9]409 *
[5fca55f]410 * Returns the number of lines removed on success.  Returns -1 on failure.
[38cf544c]411 */
[da60ba9]412int owl_util_file_deleteline(const char *filename, const char *line, int backup)
[38cf544c]413{
[946058b]414  char *backupfile, *newfile, *buf = NULL;
[950e2da]415  gchar *actual_filename; /* gchar; we need to g_free it */
[946058b]416  FILE *old, *new;
417  struct stat st;
[da60ba9]418  int numremoved = 0;
[38cf544c]419
[946058b]420  if ((old = fopen(filename, "r")) == NULL) {
421    owl_function_error("Cannot open %s (for reading): %s",
422                       filename, strerror(errno));
[5fca55f]423    return -1;
[38cf544c]424  }
[e6449bc]425
[946058b]426  if (fstat(fileno(old), &st) != 0) {
427    owl_function_error("Cannot stat %s: %s", filename, strerror(errno));
[5fca55f]428    return -1;
[38cf544c]429  }
430
[950e2da]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
[3472845]436  newfile = g_strdup_printf("%s.new", actual_filename);
[946058b]437  if ((new = fopen(newfile, "w")) == NULL) {
438    owl_function_error("Cannot open %s (for writing): %s",
[950e2da]439                       actual_filename, strerror(errno));
[ddbbcffa]440    g_free(newfile);
[946058b]441    fclose(old);
[83a4af3]442    g_free(actual_filename);
[5fca55f]443    return -1;
[946058b]444  }
445
446  if (fchmod(fileno(new), st.st_mode & 0777) != 0) {
447    owl_function_error("Cannot set permissions on %s: %s",
[950e2da]448                       actual_filename, strerror(errno));
[946058b]449    unlink(newfile);
450    fclose(new);
[ddbbcffa]451    g_free(newfile);
[946058b]452    fclose(old);
[83a4af3]453    g_free(actual_filename);
[5fca55f]454    return -1;
[946058b]455  }
456
457  while (owl_getline_chomp(&buf, old))
458    if (strcasecmp(buf, line) != 0)
459      fprintf(new, "%s\n", buf);
460    else
[da60ba9]461      numremoved++;
[ddbbcffa]462  g_free(buf);
[38cf544c]463
[946058b]464  fclose(new);
465  fclose(old);
466
467  if (backup) {
[3472845]468    backupfile = g_strdup_printf("%s.backup", actual_filename);
[946058b]469    unlink(backupfile);
[950e2da]470    if (link(actual_filename, backupfile) != 0) {
[946058b]471      owl_function_error("Cannot link %s: %s", backupfile, strerror(errno));
[ddbbcffa]472      g_free(backupfile);
[946058b]473      unlink(newfile);
[ddbbcffa]474      g_free(newfile);
[5fca55f]475      return -1;
[6a50af2]476    }
[ddbbcffa]477    g_free(backupfile);
[38cf544c]478  }
479
[950e2da]480  if (rename(newfile, actual_filename) != 0) {
[946058b]481    owl_function_error("Cannot move %s to %s: %s",
[950e2da]482                       newfile, actual_filename, strerror(errno));
[5fca55f]483    numremoved = -1;
[38cf544c]484  }
485
[946058b]486  unlink(newfile);
[ddbbcffa]487  g_free(newfile);
[da60ba9]488
[950e2da]489  g_free(actual_filename);
490
[da60ba9]491  return numremoved;
[38cf544c]492}
493
[7a20e4c]494/* Return the base class or instance from a zephyr class, by removing
495   leading `un' or trailing `.d'.
[be5aa09]496   The caller is responsible for freeing the allocated string.
[7a20e4c]497*/
[6829afc]498CALLER_OWN char *owl_util_baseclass(const char *class)
[7a20e4c]499{
[59916e8]500  char *start, *end;
501
[fa4562c]502  while(!strncmp(class, "un", 2)) {
503    class += 2;
[7a20e4c]504  }
[f166580]505
[d4927a7]506  start = g_strdup(class);
[59916e8]507  end = start + strlen(start) - 1;
[04166e9]508  while(end > start && *end == 'd' && *(end-1) == '.') {
[7a20e4c]509    end -= 2;
510  }
511  *(end + 1) = 0;
[59916e8]512
[f166580]513  return start;
[7a20e4c]514}
515
[c79a047]516const char * owl_get_datadir(void)
[5376a95]517{
[e19eb97]518  const char * datadir = getenv("BARNOWL_DATA_DIR");
[5376a95]519  if(datadir != NULL)
[7bf51d5]520    return datadir;
[5376a95]521  return DATADIR;
522}
523
[9a7b4f2]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
[5376a95]532/* Strips format characters from a valid utf-8 string. Returns the
[d427f08]533   empty string if 'in' does not validate.  Caller must free the return. */
[6829afc]534CALLER_OWN char *owl_strip_format_chars(const char *in)
[5376a95]535{
536  char *r;
537  if (g_utf8_validate(in, -1, NULL)) {
[7f6a8a2]538    const char *s, *p;
[96828e4]539    r = g_new(char, strlen(in)+1);
[5376a95]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. */
[c1522ec]546      if (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
[5376a95]547        strncat(r, s, p-s);
548        p = g_utf8_next_char(p);
[f119757]549        while (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
[5376a95]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 {
[d4927a7]562    r = g_strdup("");
[5376a95]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.
[d427f08]571 * Caller must free the return.
[5376a95]572 */
[6829afc]573CALLER_OWN char *owl_validate_or_convert(const char *in)
[5376a95]574{
[6201646]575  if (g_utf8_validate(in, -1, NULL)) {
[5376a95]576    return owl_strip_format_chars(in);
577  }
578  else {
[6201646]579    return g_convert(in, -1,
[5376a95]580                     "UTF-8", "ISO-8859-1",
581                     NULL, NULL, NULL);
582  }
[89f5338]583}
[4b17a6c]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.
[d427f08]587 * Caller must free the return.
[7b1d048]588 */
[6829afc]589CALLER_OWN char *owl_validate_utf8(const char *in)
[7b1d048]590{
591  char *out;
592  if (g_utf8_validate(in, -1, NULL)) {
[d4927a7]593    out = g_strdup(in);
[4b17a6c]594  } else {
[d4927a7]595    out = g_strdup("");
[7b1d048]596  }
597  return out;
598}
[89f5338]599
[84027015]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}
[eea72a1]620
[d427f08]621/* caller must free the return */
[6829afc]622CALLER_OWN char *owl_escape_highbit(const char *str)
[eea72a1]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}
[6ace255]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;
[35b6eb9]650      *s = g_renew(char, *s, size);
[6ace255]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
[35b6eb9]667 * g_malloc; it will be g_renew'd as appropriate.  The caller must
[6ace255]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. */
[6829afc]685CALLER_OWN char *owl_slurp(FILE *fp)
[6ace255]686{
687  char *buf = NULL;
688  char *p;
689  int size = 0;
690  int count;
691
692  while (1) {
[35b6eb9]693    buf = g_renew(char, buf, size + BUFSIZ);
[6ace255]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}
[05ca0d8]704
[9efa5bd]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
[c1f1e1e]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
[05ca0d8]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.