source: util.c @ a3e61a2

release-1.10release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since a3e61a2 was a3e61a2, checked in by Karl Ramm <kcr@1ts.org>, 15 years ago
Rewrite color name<->number mapping code Make it data-driven, as opposed to a giant, ugly if-ladder.
  • Property mode set to 100644
File size: 17.3 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
10void sepbar(const char *in)
11{
12  char buff[1024];
13  WINDOW *sepwin;
14  const owl_messagelist *ml;
15  const owl_view *v;
16  int x, y, i;
17  const char *foo, *appendtosepbar;
18
19  sepwin=owl_global_get_curs_sepwin(&g);
20  ml=owl_global_get_msglist(&g);
21  v=owl_global_get_current_view(&g);
22
23  werase(sepwin);
24  wattron(sepwin, A_REVERSE);
25  if (owl_global_is_fancylines(&g)) {
26    whline(sepwin, ACS_HLINE, owl_global_get_cols(&g));
27  } else {
28    whline(sepwin, '-', owl_global_get_cols(&g));
29  }
30
31  if (owl_global_is_sepbar_disable(&g)) {
32    getyx(sepwin, y, x);
33    wmove(sepwin, y, owl_global_get_cols(&g)-1);
34    return;
35  }
36
37  wmove(sepwin, 0, 2); 
38
39  if (owl_messagelist_get_size(ml)==0) {
40    strcpy(buff, " (-/-) ");
41  } else {
42    snprintf(buff, 1024, " (%i/%i/%i) ", owl_global_get_curmsg(&g)+1,
43            owl_view_get_size(v),
44            owl_messagelist_get_size(ml));
45  }
46  waddstr(sepwin, buff);
47
48  foo=owl_view_get_filtname(v);
49  if (strcmp(foo, owl_global_get_view_home(&g))) wattroff(sepwin, A_REVERSE);
50  waddstr(sepwin, " ");
51  waddstr(sepwin, owl_view_get_filtname(v));
52  waddstr(sepwin, " ");
53  if (strcmp(foo, owl_global_get_view_home(&g))) wattron(sepwin, A_REVERSE);
54
55  if (owl_mainwin_is_curmsg_truncated(owl_global_get_mainwin(&g))) {
56    getyx(sepwin, y, x);
57    wmove(sepwin, y, x+2);
58    wattron(sepwin, A_BOLD);
59    waddstr(sepwin, " <truncated> ");
60    wattroff(sepwin, A_BOLD);
61  }
62
63  i=owl_mainwin_get_last_msg(owl_global_get_mainwin(&g));
64  if ((i != -1) &&
65      (i < owl_view_get_size(v)-1)) {
66    getyx(sepwin, y, x);
67    wmove(sepwin, y, x+2);
68    wattron(sepwin, A_BOLD);
69    waddstr(sepwin, " <more> ");
70    wattroff(sepwin, A_BOLD);
71  }
72
73  if (owl_global_get_rightshift(&g)>0) {
74    getyx(sepwin, y, x);
75    wmove(sepwin, y, x+2);
76    snprintf(buff, 1024, " right: %i ", owl_global_get_rightshift(&g));
77    waddstr(sepwin, buff);
78  }
79
80  if (owl_global_is_zaway(&g) || owl_global_is_aaway(&g)) {
81    getyx(sepwin, y, x);
82    wmove(sepwin, y, x+2);
83    wattron(sepwin, A_BOLD);
84    wattroff(sepwin, A_REVERSE);
85    if (owl_global_is_zaway(&g) && owl_global_is_aaway(&g)) {
86      waddstr(sepwin, " AWAY ");
87    } else if (owl_global_is_zaway(&g)) {
88      waddstr(sepwin, " Z-AWAY ");
89    } else if (owl_global_is_aaway(&g)) {
90      waddstr(sepwin, " A-AWAY ");
91    }
92    wattron(sepwin, A_REVERSE);
93    wattroff(sepwin, A_BOLD);
94  }
95
96  if (owl_global_get_curmsg_vert_offset(&g)) {
97    getyx(sepwin, y, x);
98    wmove(sepwin, y, x+2);
99    wattron(sepwin, A_BOLD);
100    wattroff(sepwin, A_REVERSE);
101    waddstr(sepwin, " SCROLL ");
102    wattron(sepwin, A_REVERSE);
103    wattroff(sepwin, A_BOLD);
104  }
105 
106  if (in) {
107    getyx(sepwin, y, x);
108    wmove(sepwin, y, x+2);
109    waddstr(sepwin, in);
110  }
111
112  appendtosepbar = owl_global_get_appendtosepbar(&g);
113  if (appendtosepbar && *appendtosepbar) {
114    getyx(sepwin, y, x);
115    wmove(sepwin, y, x+2);
116    waddstr(sepwin, " ");
117    waddstr(sepwin, owl_global_get_appendtosepbar(&g));
118    waddstr(sepwin, " ");
119  }
120
121  getyx(sepwin, y, x);
122  wmove(sepwin, y, owl_global_get_cols(&g)-1);
123   
124  wattroff(sepwin, A_BOLD);
125  wattroff(sepwin, A_REVERSE);
126  wnoutrefresh(sepwin);
127}
128
129char **atokenize(const char *buffer, const char *sep, int *i)
130{
131  /* each element of return must be freed by user */
132  char **args;
133  char *workbuff, *foo;
134  int done=0, first=1, count=0;
135
136  workbuff=owl_malloc(strlen(buffer)+1);
137  memcpy(workbuff, buffer, strlen(buffer)+1);
138
139  args=NULL;
140  while (!done) {
141    if (first) {
142      first=0;
143      foo=strtok(workbuff, sep);
144    } else {
145      foo=strtok(NULL, sep);
146    }
147    if (foo==NULL) {
148      done=1;
149    } else {
150      args=owl_realloc(args, sizeof(char *) * (count+1));
151      args[count] = owl_strdup(foo);
152      count++;
153    }
154  }
155  *i=count;
156  owl_free(workbuff);
157  return(args);
158}
159
160const char *skiptokens(const char *buff, int n) {
161  /* skips n tokens and returns where that would be. */
162  char quote = 0;
163  while (*buff && n>0) {
164      while (*buff == ' ') buff++;
165      while (*buff && (quote || *buff != ' ')) {
166        if(quote) {
167          if(*buff == quote) quote = 0;
168        } else if(*buff == '"' || *buff == '\'') {
169          quote = *buff;
170        }
171        buff++;
172      }
173      while (*buff == ' ') buff++;
174      n--;
175  }
176  return buff;
177}
178
179/* Return a "nice" version of the path.  Tilde expansion is done, and
180 * duplicate slashes are removed.  Caller must free the return.
181 */
182char *owl_util_makepath(const char *in)
183{
184  int i, j, x;
185  char *out, user[MAXPATHLEN];
186  struct passwd *pw;
187
188  out=owl_malloc(MAXPATHLEN+1);
189  out[0]='\0';
190  j=strlen(in);
191  x=0;
192  for (i=0; i<j; i++) {
193    if (in[i]=='~') {
194      if ( (i==(j-1)) ||          /* last character */
195           (in[i+1]=='/') ) {     /* ~/ */
196        /* use my homedir */
197        pw=getpwuid(getuid());
198        if (!pw) {
199          out[x]=in[i];
200        } else {
201          out[x]='\0';
202          strcat(out, pw->pw_dir);
203          x+=strlen(pw->pw_dir);
204        }
205      } else {
206        /* another user homedir */
207        int a, b;
208        b=0;
209        for (a=i+1; i<j; a++) {
210          if (in[a]==' ' || in[a]=='/') {
211            break;
212          } else {
213            user[b]=in[a];
214            i++;
215            b++;
216          }
217        }
218        user[b]='\0';
219        pw=getpwnam(user);
220        if (!pw) {
221          out[x]=in[i];
222        } else {
223          out[x]='\0';
224          strcat(out, pw->pw_dir);
225          x+=strlen(pw->pw_dir);
226        }
227      }
228    } else if (in[i]=='/') {
229      /* check for a double / */
230      if (i<(j-1) && (in[i+1]=='/')) {
231        /* do nothing */
232      } else {
233        out[x]=in[i];
234        x++;
235      }
236    } else {
237      out[x]=in[i];
238      x++;
239    }
240  }
241  out[x]='\0';
242  return(out);
243}
244
245void atokenize_free(char **tok, int nels)
246{
247  int i;
248  for (i=0; i<nels; i++) {
249    owl_free(tok[i]);
250  }
251  owl_free(tok);
252}
253
254
255void owl_parsefree(char **argv, int argc)
256{
257  int i;
258
259  if (!argv) return;
260 
261  for (i=0; i<argc; i++) {
262    if (argv[i]) owl_free(argv[i]);
263  }
264  owl_free(argv);
265}
266
267char **owl_parseline(const char *line, int *argc)
268{
269  /* break a command line up into argv, argc.  The caller must free
270     the returned values.  If there is an error argc will be set to
271     -1, argv will be NULL and the caller does not need to free
272     anything */
273
274  char **argv;
275  int i, len, between=1;
276  char *curarg;
277  char quote;
278
279  argv=owl_malloc(sizeof(char *));
280  len=strlen(line);
281  curarg=owl_malloc(len+10);
282  strcpy(curarg, "");
283  quote='\0';
284  *argc=0;
285  for (i=0; i<len+1; i++) {
286    /* find the first real character */
287    if (between) {
288      if (line[i]==' ' || line[i]=='\t' || line[i]=='\0') {
289        continue;
290      } else {
291        between=0;
292        i--;
293        continue;
294      }
295    }
296
297    /* deal with a quote character */
298    if (line[i]=='"' || line[i]=="'"[0]) {
299      /* if this type of quote is open, close it */
300      if (quote==line[i]) {
301        quote='\0';
302        continue;
303      }
304
305      /* if no quoting is open then open with this */
306      if (quote=='\0') {
307        quote=line[i];
308        continue;
309      }
310
311      /* if another type of quote is open then treat this as a literal */
312      curarg[strlen(curarg)+1]='\0';
313      curarg[strlen(curarg)]=line[i];
314      continue;
315    }
316
317    /* if it's not a space or end of command, then use it */
318    if (line[i]!=' ' && line[i]!='\t' && line[i]!='\n' && line[i]!='\0') {
319      curarg[strlen(curarg)+1]='\0';
320      curarg[strlen(curarg)]=line[i];
321      continue;
322    }
323
324    /* otherwise, if we're not in quotes, add the whole argument */
325    if (quote=='\0') {
326      /* add the argument */
327      argv=owl_realloc(argv, sizeof(char *)*((*argc)+1));
328      argv[*argc] = owl_strdup(curarg);
329      *argc=*argc+1;
330      strcpy(curarg, "");
331      between=1;
332      continue;
333    }
334
335    /* if it is a space and we're in quotes, then use it */
336    curarg[strlen(curarg)+1]='\0';
337    curarg[strlen(curarg)]=line[i];
338  }
339
340  owl_free(curarg);
341
342  /* check for unbalanced quotes */
343  if (quote!='\0') {
344    owl_parsefree(argv, *argc);
345    *argc=-1;
346    return(NULL);
347  }
348
349  return(argv);
350}
351
352/* caller must free the return */
353char *owl_util_minutes_to_timestr(int in)
354{
355  int days, hours;
356  long run;
357  char *out;
358
359  run=in;
360
361  days=run/1440;
362  run-=days*1440;
363  hours=run/60;
364  run-=hours*60;
365
366  if (days>0) {
367    out=owl_sprintf("%i d %2.2i:%2.2li", days, hours, run);
368  } else {
369    out=owl_sprintf("    %2.2i:%2.2li", hours, run);
370  }
371  return(out);
372}
373
374/* hooks for doing memory allocation et. al. in owl */
375
376void *owl_malloc(size_t size)
377{
378  return(g_malloc(size));
379}
380
381void owl_free(void *ptr)
382{
383  g_free(ptr);
384}
385
386char *owl_strdup(const char *s1)
387{
388  return(g_strdup(s1));
389}
390
391void *owl_realloc(void *ptr, size_t size)
392{
393  return(g_realloc(ptr, size));
394}
395
396/* allocates memory and returns the string or null.
397 * caller must free the string.
398 */
399char *owl_sprintf(const char *fmt, ...)
400{
401  va_list ap;
402  char *ret = NULL;
403  va_start(ap, fmt);
404  ret = g_strdup_vprintf(fmt, ap);
405  va_end(ap);
406  return ret;
407}
408
409/* These are in order of their value in owl.h */
410static const struct {
411  int number;
412  const char *name;
413} color_map[] = {
414  {OWL_COLOR_INVALID, "invalid"},
415  {OWL_COLOR_DEFAULT, "default"},
416  {OWL_COLOR_BLACK, "black"},
417  {OWL_COLOR_RED, "red"},
418  {OWL_COLOR_GREEN, "green"},
419  {OWL_COLOR_YELLOW,"yellow"},
420  {OWL_COLOR_BLUE, "blue"},
421  {OWL_COLOR_MAGENTA, "magenta"},
422  {OWL_COLOR_CYAN, "cyan"},
423  {OWL_COLOR_WHITE, "white"},
424};
425
426/* Return the owl color associated with the named color.  Return -1
427 * if the named color is not available
428 */
429int owl_util_string_to_color(const char *color)
430{
431  int c, i;
432
433  for (i = 0; i < (sizeof(color_map)/sizeof(color_map[0])); i++)
434    if (strcasecmp(color, color_map[i].name) == 0)
435      return color_map[i].number;
436
437  c = atoi(color);
438  if (c >= -1 && c < COLORS) {
439    return(c);
440  }
441  return(OWL_COLOR_INVALID);
442}
443
444/* Return a string name of the given owl color */
445const char *owl_util_color_to_string(int color)
446{
447  if (color >= OWL_COLOR_INVALID && color <= OWL_COLOR_WHITE)
448    return color_map[color - OWL_COLOR_INVALID].name;
449  return("Unknown color");
450}
451
452/* Get the default tty name.  Caller must free the return */
453char *owl_util_get_default_tty(void)
454{
455  const char *tmp;
456  char *out;
457
458  if (getenv("DISPLAY")) {
459    out=owl_strdup(getenv("DISPLAY"));
460  } else if ((tmp=ttyname(fileno(stdout)))!=NULL) {
461    out=owl_strdup(tmp);
462    if (!strncmp(out, "/dev/", 5)) {
463      owl_free(out);
464      out=owl_strdup(tmp+5);
465    }
466  } else {
467    out=owl_strdup("unknown");
468  }
469  return(out);
470}
471
472/* strip leading and trailing new lines.  Caller must free the
473 * return.
474 */
475char *owl_util_stripnewlines(const char *in)
476{
477 
478  char  *tmp, *ptr1, *ptr2, *out;
479
480  ptr1=tmp=owl_strdup(in);
481  while (ptr1[0]=='\n') {
482    ptr1++;
483  }
484  ptr2=ptr1+strlen(ptr1)-1;
485  while (ptr2>ptr1 && ptr2[0]=='\n') {
486    ptr2[0]='\0';
487    ptr2--;
488  }
489
490  out=owl_strdup(ptr1);
491  owl_free(tmp);
492  return(out);
493}
494
495/* Delete all lines matching "line" from the named file.  If no such
496 * line is found the file is left intact.  If backup==1 then leave a
497 * backup file containing the original contents.  The match is
498 * case-insensitive.
499 *
500 * Returns the number of lines removed
501 */
502int owl_util_file_deleteline(const char *filename, const char *line, int backup)
503{
504  char *backupfile, *newfile, *buf = NULL;
505  FILE *old, *new;
506  struct stat st;
507  int numremoved = 0;
508
509  if ((old = fopen(filename, "r")) == NULL) {
510    owl_function_error("Cannot open %s (for reading): %s",
511                       filename, strerror(errno));
512    return 0;
513  }
514
515  if (fstat(fileno(old), &st) != 0) {
516    owl_function_error("Cannot stat %s: %s", filename, strerror(errno));
517    return 0;
518  }
519
520  newfile = owl_sprintf("%s.new", filename);
521  if ((new = fopen(newfile, "w")) == NULL) {
522    owl_function_error("Cannot open %s (for writing): %s",
523                       filename, strerror(errno));
524    free(newfile);
525    fclose(old);
526    return 0;
527  }
528
529  if (fchmod(fileno(new), st.st_mode & 0777) != 0) {
530    owl_function_error("Cannot set permissions on %s: %s",
531                       filename, strerror(errno));
532    unlink(newfile);
533    fclose(new);
534    free(newfile);
535    fclose(old);
536    return 0;
537  }
538
539  while (owl_getline_chomp(&buf, old))
540    if (strcasecmp(buf, line) != 0)
541      fprintf(new, "%s\n", buf);
542    else
543      numremoved++;
544
545  fclose(new);
546  fclose(old);
547
548  if (backup) {
549    backupfile = owl_sprintf("%s.backup", filename);
550    unlink(backupfile);
551    if (link(filename, backupfile) != 0) {
552      owl_function_error("Cannot link %s: %s", backupfile, strerror(errno));
553      owl_free(backupfile);
554      unlink(newfile);
555      owl_free(newfile);
556      return 0;
557    }
558    owl_free(backupfile);
559  }
560
561  if (rename(newfile, filename) != 0) {
562    owl_function_error("Cannot move %s to %s: %s",
563                       newfile, filename, strerror(errno));
564    numremoved = 0;
565  }
566
567  unlink(newfile);
568  owl_free(newfile);
569
570  return numremoved;
571}
572
573int owl_util_max(int a, int b)
574{
575  if (a>b) return(a);
576  return(b);
577}
578
579int owl_util_min(int a, int b)
580{
581  if (a<b) return(a);
582  return(b);
583}
584
585/* Return the base class or instance from a zephyr class, by removing
586   leading `un' or trailing `.d'.
587   The caller is responsible for freeing the allocated string.
588*/
589char * owl_util_baseclass(const char * class)
590{
591  char *start, *end;
592
593  while(!strncmp(class, "un", 2)) {
594    class += 2;
595  }
596
597  start = owl_strdup(class);
598  end = start + strlen(start) - 1;
599  while(end > start && *end == 'd' && *(end-1) == '.') {
600    end -= 2;
601  }
602  *(end + 1) = 0;
603
604  return start;
605}
606
607const char * owl_get_datadir(void)
608{
609  const char * datadir = getenv("BARNOWL_DATA_DIR");
610  if(datadir != NULL)
611    return datadir;
612  return DATADIR;
613}
614
615/* Strips format characters from a valid utf-8 string. Returns the
616   empty string if 'in' does not validate. */
617char * owl_strip_format_chars(const char *in)
618{
619  char *r;
620  if (g_utf8_validate(in, -1, NULL)) {
621    const char *s, *p;
622    r = owl_malloc(strlen(in)+1);
623    r[0] = '\0';
624    s = in;
625    p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
626    while(p) {
627      /* If it's a format character, copy up to it, and skip all
628         immediately following format characters. */
629      if (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
630        strncat(r, s, p-s);
631        p = g_utf8_next_char(p);
632        while (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
633          p = g_utf8_next_char(p);
634        }
635        s = p;
636        p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
637      }
638      else {
639        p = strchr(p+1, OWL_FMTEXT_UC_STARTBYTE_UTF8);
640      }
641    }
642    if (s) strcat(r,s);
643  }
644  else {
645    r = owl_strdup("");
646  }
647  return r;
648}
649
650/* If in is not UTF-8, convert from ISO-8859-1. We may want to allow
651 * the caller to specify an alternative in the future. We also strip
652 * out characters in Unicode Plane 16, as we use that plane internally
653 * for formatting.
654 */
655char * owl_validate_or_convert(const char *in)
656{
657  if (g_utf8_validate(in, -1, NULL)) {
658    return owl_strip_format_chars(in);
659  }
660  else {
661    return g_convert(in, -1,
662                     "UTF-8", "ISO-8859-1",
663                     NULL, NULL, NULL);
664  }
665}
666/*
667 * Validate 'in' as UTF-8, and either return a copy of it, or an empty
668 * string if it is invalid utf-8.
669 */
670char * owl_validate_utf8(const char *in)
671{
672  char *out;
673  if (g_utf8_validate(in, -1, NULL)) {
674    out = owl_strdup(in);
675  } else {
676    out = owl_strdup("");
677  }
678  return out;
679}
680
681/* This is based on _extract() and _isCJ() from perl's Text::WrapI18N */
682int owl_util_can_break_after(gunichar c)
683{
684 
685  if (c == ' ') return 1;
686  if (c >= 0x3000 && c <= 0x312f) {
687    /* CJK punctuations, Hiragana, Katakana, Bopomofo */
688    if (c == 0x300a || c == 0x300c || c == 0x300e ||
689        c == 0x3010 || c == 0x3014 || c == 0x3016 ||
690        c == 0x3018 || c == 0x301a)
691      return 0;
692    return 1;
693  }
694  if (c >= 0x31a0 && c <= 0x31bf) {return 1;}  /* Bopomofo */
695  if (c >= 0x31f0 && c <= 0x31ff) {return 1;}  /* Katakana extension */
696  if (c >= 0x3400 && c <= 0x9fff) {return 1;}  /* Han Ideogram */
697  if (c >= 0xf900 && c <= 0xfaff) {return 1;}  /* Han Ideogram */
698  if (c >= 0x20000 && c <= 0x2ffff) {return 1;}  /* Han Ideogram */
699  return 0;
700}
701
702char *owl_escape_highbit(const char *str)
703{
704  GString *out = g_string_new("");
705  unsigned char c;
706  while((c = (*str++))) {
707    if(c == '\\') {
708      g_string_append(out, "\\\\");
709    } else if(c & 0x80) {
710      g_string_append_printf(out, "\\x%02x", (int)c);
711    } else {
712      g_string_append_c(out, c);
713    }
714  }
715  return g_string_free(out, 0);
716}
717
718/* innards of owl_getline{,_chomp} below */
719static int owl_getline_internal(char **s, FILE *fp, int newline)
720{
721  int size = 0;
722  int target = 0;
723  int count = 0;
724  int c;
725
726  while (1) {
727    c = getc(fp);
728    if ((target + 1) > size) {
729      size += BUFSIZ;
730      *s = owl_realloc(*s, size);
731    }
732    if (c == EOF)
733      break;
734    count++;
735    if (c != '\n' || newline)
736        (*s)[target++] = c;
737    if (c == '\n')
738      break;
739  }
740  (*s)[target] = 0;
741
742  return count;
743}
744
745/* Read a line from fp, allocating memory to hold it, returning the number of
746 * byte read.  *s should either be NULL or a pointer to memory allocated with
747 * owl_malloc; it will be owl_realloc'd as appropriate.  The caller must
748 * eventually free it.  (This is roughly the interface of getline in the gnu
749 * libc).
750 *
751 * The final newline will be included if it's there.
752 */
753int owl_getline(char **s, FILE *fp)
754{
755  return owl_getline_internal(s, fp, 1);
756}
757
758/* As above, but omitting the final newline */
759int owl_getline_chomp(char **s, FILE *fp)
760{
761  return owl_getline_internal(s, fp, 0);
762}
763
764/* Read the rest of the input available in fp into a string. */
765char *owl_slurp(FILE *fp)
766{
767  char *buf = NULL;
768  char *p;
769  int size = 0;
770  int count;
771
772  while (1) {
773    buf = owl_realloc(buf, size + BUFSIZ);
774    p = &buf[size];
775    size += BUFSIZ;
776
777    if ((count = fread(p, 1, BUFSIZ, fp)) < BUFSIZ)
778      break;
779  }
780  p[count] = 0;
781
782  return buf;
783}
Note: See TracBrowser for help on using the repository browser.