source: functions.c @ 52761cc

release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 52761cc was 52761cc, checked in by Karl Ramm <kcr@1ts.org>, 12 years ago
Cleanup owl_function_debugmsg. Nuke two buff[LINE]s in owl_function_debugmsg. Remove now-unused owl_global_get_runtime_string.
  • Property mode set to 100644
File size: 97.9 KB
Line 
1#include <stdio.h>
2#include <stdlib.h>
3#include <unistd.h>
4#include <signal.h>
5#include <netinet/in.h>
6#include <string.h>
7#include <time.h>
8#include <sys/types.h>
9#include <sys/stat.h>
10#include <sys/wait.h>
11#include <errno.h>
12#include <signal.h>
13#include "owl.h"
14
15char *owl_function_command(const char *cmdbuff)
16{
17  owl_function_debugmsg("executing command: %s", cmdbuff);
18  return owl_cmddict_execute(owl_global_get_cmddict(&g), 
19                             owl_global_get_context(&g), cmdbuff);
20}
21
22char *owl_function_command_argv(const char *const *argv, int argc)
23{
24  return owl_cmddict_execute_argv(owl_global_get_cmddict(&g),
25                                  owl_global_get_context(&g),
26                                  argv, argc);
27}
28
29void owl_function_command_norv(const char *cmdbuff)
30{
31  char *rv;
32  rv=owl_function_command(cmdbuff);
33  if (rv) owl_free(rv);
34}
35
36void owl_function_command_alias(const char *alias_from, const char *alias_to)
37{
38  owl_cmddict_add_alias(owl_global_get_cmddict(&g), alias_from, alias_to);
39}
40
41const owl_cmd *owl_function_get_cmd(const char *name)
42{
43  return owl_cmddict_find(owl_global_get_cmddict(&g), name);
44}
45
46void owl_function_show_commands(void)
47{
48  owl_list l;
49  owl_fmtext fm;
50
51  owl_fmtext_init_null(&fm);
52  owl_fmtext_append_bold(&fm, "Commands:  ");
53  owl_fmtext_append_normal(&fm, "(use 'show command <name>' for details)\n");
54  owl_cmddict_get_names(owl_global_get_cmddict(&g), &l);
55  owl_fmtext_append_list(&fm, &l, "\n", owl_function_cmd_describe);
56  owl_fmtext_append_normal(&fm, "\n");
57  owl_function_popless_fmtext(&fm);
58  owl_cmddict_namelist_free(&l);
59  owl_fmtext_free(&fm);
60}
61
62void owl_function_show_view(const char *viewname)
63{
64  const owl_view *v;
65  owl_fmtext fm;
66
67  /* we only have the one view right now */
68  v=owl_global_get_current_view(&g);
69  if (viewname && strcmp(viewname, owl_view_get_name(v))) {
70    owl_function_error("No view named '%s'", viewname);
71    return;
72  }
73
74  owl_fmtext_init_null(&fm);
75  owl_view_to_fmtext(v, &fm);
76  owl_function_popless_fmtext(&fm);
77  owl_fmtext_free(&fm);
78}
79
80void owl_function_show_styles(void) {
81  owl_list l;
82  owl_fmtext fm;
83
84  owl_fmtext_init_null(&fm);
85  owl_fmtext_append_bold(&fm, "Styles:\n");
86  owl_global_get_style_names(&g, &l);
87  owl_fmtext_append_list(&fm, &l, "\n", owl_function_style_describe);
88  owl_fmtext_append_normal(&fm, "\n");
89  owl_function_popless_fmtext(&fm);
90  owl_list_free_all(&l, owl_free);
91  owl_fmtext_free(&fm);
92}
93
94char *owl_function_style_describe(const char *name) {
95  const char *desc;
96  char *s;
97  const owl_style *style;
98  style = owl_global_get_style_by_name(&g, name);
99  if (style) {
100    desc = owl_style_get_description(style);
101  } else {
102    desc = "???";
103  }
104  s = owl_sprintf("%-20s - %s%s", name, 
105                  0==owl_style_validate(style)?"":"[INVALID] ",
106                  desc);
107  return s;
108}
109
110char *owl_function_cmd_describe(const char *name)
111{
112  const owl_cmd *cmd = owl_cmddict_find(owl_global_get_cmddict(&g), name);
113  if (cmd) return owl_cmd_describe(cmd);
114  else return(NULL);
115}
116
117void owl_function_show_command(const char *name)
118{
119  owl_function_help_for_command(name);
120}
121
122void owl_function_show_license(void)
123{
124  const char *text;
125
126  text=""
127    "barnowl version " OWL_VERSION_STRING "\n"
128    "Copyright (c) 2006-2009 The BarnOwl Developers. All rights reserved.\n"
129    "Copyright (c) 2004 James Kretchmar. All rights reserved.\n"
130    "\n"
131    "Redistribution and use in source and binary forms, with or without\n"
132    "modification, are permitted provided that the following conditions are\n"
133    "met:\n"
134    "\n"
135    "   * Redistributions of source code must retain the above copyright\n"
136    "     notice, this list of conditions and the following disclaimer.\n"
137    "\n"
138    "   * Redistributions in binary form must reproduce the above copyright\n"
139    "     notice, this list of conditions and the following disclaimer in\n"
140    "     the documentation and/or other materials provided with the\n"
141    "     distribution.\n"
142    "\n"
143    "   * Redistributions in any form must be accompanied by information on\n"
144    "     how to obtain complete source code for the Owl software and any\n"
145    "     accompanying software that uses the Owl software. The source code\n"
146    "     must either be included in the distribution or be available for no\n"
147    "     more than the cost of distribution plus a nominal fee, and must be\n"
148    "     freely redistributable under reasonable conditions. For an\n"
149    "     executable file, complete source code means the source code for\n"
150    "     all modules it contains. It does not include source code for\n"
151    "     modules or files that typically accompany the major components of\n"
152    "     the operating system on which the executable file runs.\n"
153    "\n"
154    "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
155    "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n"
156    "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR\n"
157    "NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE\n"
158    "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n"
159    "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n"
160    "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n"
161    "BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n"
162    "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n"
163    "OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n"
164    "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n";
165  owl_function_popless_text(text);
166}
167
168void owl_function_show_quickstart(void)
169{
170    const char *message =
171    "Move between messages with the arrow keys, and press 'r' to reply.\n"
172    "For more info, press 'h' or visit http://barnowl.mit.edu/\n\n"
173#ifdef HAVE_LIBZEPHYR
174    "@b(Zephyr:)\n"
175    "To send a message to a user, type ':zwrite @b(username)'. You can also\n"
176    "press 'z' and then type the username. To subscribe to a class, type\n"
177    "':sub @b(class)', and then type ':zwrite -c @b(class)' to send.\n\n"
178#endif
179    "@b(AIM:)\n"
180    "Log in to AIM with ':aimlogin @b(screenname)'. Use ':aimwrite @b(screenname)',\n"
181    "or 'a' and then the screen name, to send someone a message.\n\n"
182    ;
183
184    if (owl_perlconfig_is_function("BarnOwl::Hooks::_get_quickstart")) {
185        char *perlquickstart = owl_perlconfig_execute("BarnOwl::Hooks::_get_quickstart()");
186        if (perlquickstart) {
187            char *result = owl_sprintf("%s%s", message, perlquickstart);
188            owl_function_adminmsg("BarnOwl Quickstart", result);
189            owl_free(result);
190            owl_free(perlquickstart);
191            return;
192        }
193    }
194    owl_function_adminmsg("BarnOwl Quickstart", message);
195}
196
197
198/* Create an admin message, append it to the global list of messages
199 * and redisplay if necessary.
200 */
201void owl_function_adminmsg(const char *header, const char *body)
202{
203  owl_message *m;
204
205  m=owl_malloc(sizeof(owl_message));
206  owl_message_create_admin(m, header, body);
207 
208  /* add it to the global list and current view */
209  owl_messagelist_append_element(owl_global_get_msglist(&g), m);
210  owl_view_consider_message(owl_global_get_current_view(&g), m);
211
212  /* do followlast if necessary */
213  if (owl_global_should_followlast(&g)) owl_function_lastmsg_noredisplay();
214
215  /* redisplay etc. */
216  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
217  if (owl_popwin_is_active(owl_global_get_popwin(&g))) {
218    owl_popwin_refresh(owl_global_get_popwin(&g));
219  }
220  wnoutrefresh(owl_global_get_curs_recwin(&g));
221  owl_global_set_needrefresh(&g);
222}
223
224/* Create an outgoing zephyr message and return a pointer to it.  Does
225 * not put it on the global queue, use owl_global_messagequeue_addmsg() for
226 * that.
227 */
228owl_message *owl_function_make_outgoing_zephyr(const char *body, const char *zwriteline, const char *zsig)
229{
230  owl_message *m;
231  owl_zwrite zw;
232
233  owl_zwrite_create_from_line(&zw, zwriteline);
234  owl_zwrite_set_zsig(&zw, zsig);
235
236  /* create the message */
237  m=owl_malloc(sizeof(owl_message));
238 
239  owl_message_create_from_zwrite(m, &zw, body);
240  owl_zwrite_free(&zw);
241
242  return(m);
243}
244
245/* Create an outgoing AIM message, returns a pointer to the created
246 * message or NULL if we're not logged into AIM (and thus unable to
247 * create the message).  Does not put it on the global queue.  Use
248 * owl_global_messagequeue_addmsg() for that .
249 */
250owl_message *owl_function_make_outgoing_aim(const char *body, const char *to)
251{
252  owl_message *m;
253
254  /* error if we're not logged into aim */
255  if (!owl_global_is_aimloggedin(&g)) return(NULL);
256 
257  m=owl_malloc(sizeof(owl_message));
258  owl_message_create_aim(m,
259                         owl_global_get_aim_screenname(&g),
260                         to,
261                         body,
262                         OWL_MESSAGE_DIRECTION_OUT,
263                         0);
264  return(m);
265}
266
267/* Create an outgoing loopback message and return a pointer to it.
268 * Does not append it to the global queue, use
269 * owl_global_messagequeue_addmsg() for that.
270 */
271owl_message *owl_function_make_outgoing_loopback(const char *body)
272{
273  owl_message *m;
274
275  /* create the message */
276  m=owl_malloc(sizeof(owl_message));
277  owl_message_create_loopback(m, body);
278  owl_message_set_direction_out(m);
279
280  return(m);
281}
282
283void owl_function_start_edit_win(const char *line, void (*callback)(owl_editwin *), void *data)
284{
285  owl_editwin *e;
286  char *s;
287
288  /* create and setup the editwin */
289  e = owl_global_get_typwin(&g);
290  owl_editwin_new_style(e, OWL_EDITWIN_STYLE_MULTILINE,
291                        owl_global_get_msg_history(&g));
292  owl_editwin_clear(e);
293  owl_editwin_set_dotsend(e);
294  s = owl_sprintf("----> %s\n", line);
295  owl_editwin_set_locktext(e, s);
296  owl_free(s);
297
298  /* make it active */
299  owl_global_set_typwin_active(&g);
300
301  owl_editwin_set_cbdata(owl_global_get_typwin(&g), data);
302  owl_global_set_buffercallback(&g, callback);
303}
304
305static void owl_function_write_setup(const char *line, const char *noun, void (*callback)(owl_editwin *))
306{
307
308  if (!owl_global_get_lockout_ctrld(&g))
309    owl_function_makemsg("Type your %s below.  "
310                         "End with ^D or a dot on a line by itself."
311                         "  ^C will quit.", noun);
312  else
313    owl_function_makemsg("Type your %s below.  "
314                         "End with a dot on a line by itself.  ^C will quit.",
315                         noun);
316
317  owl_function_start_edit_win(line, callback, NULL);
318  owl_global_set_buffercommand(&g, line);
319}
320
321void owl_function_zwrite_setup(const char *line)
322{
323  owl_zwrite z;
324  int ret;
325
326  /* check the arguments */
327  ret=owl_zwrite_create_from_line(&z, line);
328  if (ret) {
329    owl_function_error("Error in zwrite arguments");
330    owl_zwrite_free(&z);
331    return;
332  }
333
334  /* send a ping if necessary */
335  if (owl_global_is_txping(&g)) {
336    owl_zwrite_send_ping(&z);
337  }
338  owl_zwrite_free(&z);
339
340  owl_function_write_setup(line, "zephyr", &owl_callback_zwrite);
341}
342
343void owl_function_aimwrite_setup(const char *line)
344{
345  owl_function_write_setup(line, "message", &owl_callback_aimwrite);
346}
347
348void owl_function_loopwrite_setup(void)
349{
350  owl_editwin *e;
351
352  /* create and setup the editwin */
353  e=owl_global_get_typwin(&g);
354  owl_editwin_new_style(e, OWL_EDITWIN_STYLE_MULTILINE, owl_global_get_msg_history(&g));
355
356  if (!owl_global_get_lockout_ctrld(&g)) {
357    owl_function_makemsg("Type your message below.  End with ^D or a dot on a line by itself.  ^C will quit.");
358  } else {
359    owl_function_makemsg("Type your message below.  End with a dot on a line by itself.  ^C will quit.");
360  }
361
362  owl_editwin_clear(e);
363  owl_editwin_set_dotsend(e);
364  owl_editwin_set_locktext(e, "----> loopwrite\n");
365
366  /* make it active */
367  owl_global_set_typwin_active(&g);
368
369  owl_global_set_buffercommand(&g, "loopwrite");
370  owl_global_set_buffercallback(&g, &owl_callback_loopwrite);
371}
372
373void owl_callback_zwrite(owl_editwin *e) {
374  owl_function_zwrite(owl_editwin_get_command(e),
375                      owl_editwin_get_text(e));
376}
377
378/* send, log and display an outgoing zephyr.  If 'msg' is NULL
379 * the message is expected to be set from the zwrite line itself
380 */
381void owl_function_zwrite(const char *line, const char *msg)
382{
383  owl_zwrite z;
384  const char *mymsg;
385  owl_message *m;
386
387  if(!strncmp(line, "zcrypt", strlen("zcrypt"))) {
388    owl_function_zcrypt(line, msg);
389    return;
390  }
391
392  /* create the zwrite and send the message */
393  owl_zwrite_create_from_line(&z, line);
394  owl_zwrite_populate_zsig(&z);
395  if (msg) {
396    owl_zwrite_set_message(&z, msg);
397  }
398  owl_zwrite_send_message(&z);
399  owl_function_makemsg("Waiting for ack...");
400
401  /* If it's personal */
402  if (owl_zwrite_is_personal(&z)) {
403    /* create the outgoing message */
404    mymsg=owl_zwrite_get_message(&z);
405    m=owl_function_make_outgoing_zephyr(mymsg, line, owl_zwrite_get_zsig(&z));
406
407    if (m) {
408      owl_global_messagequeue_addmsg(&g, m);
409    } else {
410      owl_function_error("Could not create outgoing zephyr message");
411    }
412  }
413
414  /* free the zwrite */
415  owl_zwrite_free(&z);
416}
417
418/* send, log and display an outgoing zcrypt zephyr.  If 'msg' is NULL
419 * the message is expected to be set from the zwrite line itself
420 */
421void owl_function_zcrypt(const char *line, const char *msg)
422{
423  owl_zwrite z;
424  const char *mymsg;
425  char *cryptmsg;
426  owl_message *m;
427#ifdef OWL_ENABLE_ZCRYPT
428  int ret;
429#endif
430
431  /* create the zwrite and send the message */
432  owl_zwrite_create_from_line(&z, line);
433  owl_zwrite_populate_zsig(&z);
434  if (msg) {
435    owl_zwrite_set_message(&z, msg);
436  }
437
438  mymsg=owl_zwrite_get_message(&z);
439#ifdef OWL_ENABLE_ZCRYPT
440  /* Allocate enough space for the crypted message. For each byte of
441   * the message, the encoded cyphertext will have two bytes. Block
442   * size is 8 bytes of input, or 16 bytes of output, so make sure we
443   * have at least one block worth of space allocated. If the message
444   * is empty, no blocks are sent, but we still allocate one
445   * block. The additional 16 bytes also provide space for the null
446   * terminator, as we will never use all of it for cyphertext.
447   */
448  cryptmsg=owl_malloc((strlen(mymsg)*2)+16);
449  ret=owl_zcrypt_encrypt(cryptmsg, mymsg, owl_zwrite_get_class(&z), owl_zwrite_get_instance(&z));
450  if (ret) {
451    owl_function_error("Error in zcrypt, possibly no key found.  Message not sent.");
452    owl_function_beep();
453    owl_free(cryptmsg);
454    owl_zwrite_free(&z);
455    return;
456  }
457#else
458  cryptmsg=owl_strdup(mymsg);
459#endif
460
461  owl_zwrite_set_message(&z, cryptmsg);
462  owl_zwrite_set_opcode(&z, "crypt");
463   
464  owl_zwrite_send_message(&z);
465  owl_function_makemsg("Waiting for ack...");
466
467  /* If it's personal */
468  if (owl_zwrite_is_personal(&z)) {
469    /* create the outgoing message */
470    mymsg=owl_zwrite_get_message(&z);
471    m=owl_function_make_outgoing_zephyr(mymsg, line, owl_zwrite_get_zsig(&z));
472    if (m) {
473      owl_global_messagequeue_addmsg(&g, m);
474    } else {
475      owl_function_error("Could not create outgoing zephyr message");
476    }
477  }
478
479  /* free the zwrite */
480  owl_free(cryptmsg);
481  owl_zwrite_free(&z);
482}
483
484void owl_callback_aimwrite(owl_editwin *e) {
485  owl_function_aimwrite(owl_editwin_get_command(e),
486                        owl_editwin_get_text(e));
487}
488
489void owl_function_aimwrite(const char *line, const char *msg)
490{
491  int ret;
492  const char *to;
493  char *format_msg;
494  owl_message *m;
495
496  to = line + 9;
497
498  /* make a formatted copy of the message */
499  format_msg=owl_strdup(msg);
500  owl_text_wordunwrap(format_msg);
501 
502  /* send the message */
503  ret=owl_aim_send_im(to, format_msg);
504  if (!ret) {
505    owl_function_makemsg("AIM message sent.");
506  } else {
507    owl_function_error("Could not send AIM message.");
508  }
509
510  /* create the outgoing message */
511  m=owl_function_make_outgoing_aim(msg, to);
512
513  if (m) {
514    owl_global_messagequeue_addmsg(&g, m);
515  } else {
516    owl_function_error("Could not create outgoing AIM message");
517  }
518
519  owl_free(format_msg);
520}
521
522void owl_function_send_aimawymsg(const char *to, const char *msg)
523{
524  int ret;
525  char *format_msg;
526  owl_message *m;
527
528  /* make a formatted copy of the message */
529  format_msg=owl_strdup(msg);
530  owl_text_wordunwrap(format_msg);
531 
532  /* send the message */
533  ret=owl_aim_send_awaymsg(to, format_msg);
534  if (!ret) {
535    /* owl_function_makemsg("AIM message sent."); */
536  } else {
537    owl_function_error("Could not send AIM message.");
538  }
539
540  /* create the message */
541  m=owl_function_make_outgoing_aim(msg, to);
542  if (m) {
543    owl_global_messagequeue_addmsg(&g, m);
544  } else {
545    owl_function_error("Could not create AIM message");
546  }
547  owl_free(format_msg);
548}
549
550void owl_callback_loopwrite(owl_editwin *e) {
551  owl_function_loopwrite(owl_editwin_get_text(e));
552}
553
554void owl_function_loopwrite(const char *msg)
555{
556  owl_message *min, *mout;
557
558  /* create a message and put it on the message queue.  This simulates
559   * an incoming message */
560  min=owl_malloc(sizeof(owl_message));
561  mout=owl_function_make_outgoing_loopback(msg);
562
563  if (owl_global_is_displayoutgoing(&g)) {
564    owl_global_messagequeue_addmsg(&g, mout);
565  } else {
566    owl_message_free(mout);
567  }
568
569  owl_message_create_loopback(min, msg);
570  owl_message_set_direction_in(min);
571  owl_global_messagequeue_addmsg(&g, min);
572
573  /* fake a makemsg */
574  owl_function_makemsg("loopback message sent");
575}
576
577/* If filter is non-null, looks for the next message matching
578 * that filter.  If skip_deleted, skips any deleted messages.
579 * If last_if_none, will stop at the last message in the view
580 * if no matching messages are found.  */
581void owl_function_nextmsg_full(const char *filter, int skip_deleted, int last_if_none)
582{
583  int curmsg, i, viewsize, found;
584  const owl_view *v;
585  const owl_filter *f = NULL;
586  const owl_message *m;
587
588  v=owl_global_get_current_view(&g);
589
590  if (filter) {
591    f=owl_global_get_filter(&g, filter);
592    if (!f) {
593      owl_function_error("No %s filter defined", filter);
594      return;
595    }
596  }
597
598  curmsg=owl_global_get_curmsg(&g);
599  viewsize=owl_view_get_size(v);
600  found=0;
601
602  /* just check to make sure we're in bounds... */
603  if (curmsg>viewsize-1) curmsg=viewsize-1;
604  if (curmsg<0) curmsg=0;
605
606  for (i=curmsg+1; i<viewsize; i++) {
607    m=owl_view_get_element(v, i);
608    if (skip_deleted && owl_message_is_delete(m)) continue;
609    if (f && !owl_filter_message_match(f, m)) continue;
610    found = 1;
611    break;
612  }
613
614  if (i>owl_view_get_size(v)-1) i=owl_view_get_size(v)-1;
615  if (i<0) i=0;
616
617  if (!found) {
618    owl_function_makemsg("already at last%s message%s%s%s",
619                         skip_deleted?" non-deleted":"",
620                         filter?" in ":"", filter?filter:"",
621                         owl_mainwin_is_curmsg_truncated(owl_global_get_mainwin(&g)) ?
622                         ", press Enter to scroll" : "");
623    /* if (!skip_deleted) owl_function_beep(); */
624  }
625
626  if (last_if_none || found) {
627    owl_global_set_curmsg(&g, i);
628    owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
629    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
630    owl_global_set_direction_downwards(&g);
631  }
632}
633
634void owl_function_prevmsg_full(const char *filter, int skip_deleted, int first_if_none)
635{
636  int curmsg, i, found;
637  const owl_view *v;
638  const owl_filter *f = NULL;
639  const owl_message *m;
640
641  v=owl_global_get_current_view(&g);
642
643  if (filter) {
644    f=owl_global_get_filter(&g, filter);
645    if (!f) {
646      owl_function_error("No %s filter defined", filter);
647      return;
648    }
649  }
650
651  curmsg=owl_global_get_curmsg(&g);
652  found=0;
653
654  /* just check to make sure we're in bounds... */
655  if (curmsg<0) curmsg=0;
656
657  for (i=curmsg-1; i>=0; i--) {
658    m=owl_view_get_element(v, i);
659    if (skip_deleted && owl_message_is_delete(m)) continue;
660    if (f && !owl_filter_message_match(f, m)) continue;
661    found = 1;
662    break;
663  }
664
665  if (i<0) i=0;
666
667  if (!found) {
668    owl_function_makemsg("already at first%s message%s%s",
669                         skip_deleted?" non-deleted":"",
670                         filter?" in ":"", filter?filter:"");
671    /* if (!skip_deleted) owl_function_beep(); */
672  }
673
674  if (first_if_none || found) {
675    owl_global_set_curmsg(&g, i);
676    owl_function_calculate_topmsg(OWL_DIRECTION_UPWARDS);
677    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
678    owl_global_set_direction_upwards(&g);
679  }
680}
681
682void owl_function_nextmsg(void)
683{
684  owl_function_nextmsg_full(NULL, 0, 1);
685}
686
687void owl_function_prevmsg(void)
688{
689  owl_function_prevmsg_full(NULL, 0, 1);
690}
691
692void owl_function_nextmsg_notdeleted(void)
693{
694  owl_function_nextmsg_full(NULL, 1, 1);
695}
696
697void owl_function_prevmsg_notdeleted(void)
698{
699  owl_function_prevmsg_full(NULL, 1, 1);
700}
701
702/* if move_after is 1, moves after the delete */
703void owl_function_deletecur(int move_after)
704{
705  int curmsg;
706  owl_view *v;
707
708  v=owl_global_get_current_view(&g);
709
710  /* bail if there's no current message */
711  if (owl_view_get_size(v) < 1) {
712    owl_function_error("No current message to delete");
713    return;
714  }
715
716  /* mark the message for deletion */
717  curmsg=owl_global_get_curmsg(&g);
718  owl_view_delete_element(v, curmsg);
719
720  if (move_after) {
721    /* move the poiner in the appropriate direction
722     * to the next undeleted msg */
723    if (owl_global_get_direction(&g)==OWL_DIRECTION_UPWARDS) {
724      owl_function_prevmsg_notdeleted();
725    } else {
726      owl_function_nextmsg_notdeleted();
727    }
728  }
729}
730
731void owl_function_undeletecur(int move_after)
732{
733  int curmsg;
734  owl_view *v;
735
736  v=owl_global_get_current_view(&g);
737 
738  if (owl_view_get_size(v) < 1) {
739    owl_function_error("No current message to undelete");
740    return;
741  }
742  curmsg=owl_global_get_curmsg(&g);
743
744  owl_view_undelete_element(v, curmsg);
745
746  if (move_after) {
747    if (owl_global_get_direction(&g)==OWL_DIRECTION_UPWARDS) {
748      if (curmsg>0) {
749        owl_function_prevmsg();
750      } else {
751        owl_function_nextmsg();
752      }
753    } else {
754      owl_function_nextmsg();
755    }
756  }
757
758  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
759}
760
761void owl_function_expunge(void)
762{
763  int curmsg;
764  const owl_message *m;
765  owl_messagelist *ml;
766  owl_view *v;
767  int lastmsgid=0;
768
769  curmsg=owl_global_get_curmsg(&g);
770  v=owl_global_get_current_view(&g);
771  ml=owl_global_get_msglist(&g);
772
773  m=owl_view_get_element(v, curmsg);
774  if (m) lastmsgid = owl_message_get_id(m);
775
776  /* expunge the message list */
777  owl_messagelist_expunge(ml);
778
779  /* update all views (we only have one right now) */
780  owl_view_recalculate(v);
781
782  /* find where the new position should be
783     (as close as possible to where we last where) */
784  curmsg = owl_view_get_nearest_to_msgid(v, lastmsgid);
785  if (curmsg>owl_view_get_size(v)-1) curmsg = owl_view_get_size(v)-1;
786  if (curmsg<0) curmsg = 0;
787  owl_global_set_curmsg(&g, curmsg);
788  owl_function_calculate_topmsg(OWL_DIRECTION_NONE);
789  /* if there are no messages set the direction to down in case we
790     delete everything upwards */
791  owl_global_set_direction_downwards(&g);
792 
793  owl_function_makemsg("Messages expunged");
794  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
795}
796
797void owl_function_firstmsg(void)
798{
799  owl_global_set_curmsg(&g, 0);
800  owl_global_set_topmsg(&g, 0);
801  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
802  owl_global_set_direction_downwards(&g);
803}
804
805void owl_function_lastmsg_noredisplay(void)
806{
807  int oldcurmsg, curmsg;
808  const owl_view *v;
809
810  v=owl_global_get_current_view(&g);
811  oldcurmsg=owl_global_get_curmsg(&g);
812  curmsg=owl_view_get_size(v)-1; 
813  if (curmsg<0) curmsg=0;
814  owl_global_set_curmsg(&g, curmsg);
815  if (oldcurmsg < curmsg) {
816    owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
817  } else if (curmsg<owl_view_get_size(v)) {
818    /* If already at the end, blank the screen and move curmsg
819     * past the end of the messages. */
820    owl_global_set_topmsg(&g, curmsg+1);
821    owl_global_set_curmsg(&g, curmsg+1);
822  } 
823  /* owl_mainwin_redisplay(owl_global_get_mainwin(&g)); */
824  owl_global_set_direction_downwards(&g);
825}
826
827void owl_function_lastmsg(void)
828{
829  owl_function_lastmsg_noredisplay();
830  owl_mainwin_redisplay(owl_global_get_mainwin(&g)); 
831}
832
833void owl_function_shift_right(void)
834{
835  owl_global_set_rightshift(&g, owl_global_get_rightshift(&g)+10);
836  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
837  owl_global_set_needrefresh(&g);
838}
839
840void owl_function_shift_left(void)
841{
842  int shift;
843
844  shift=owl_global_get_rightshift(&g);
845  if (shift>=10) {
846    owl_global_set_rightshift(&g, shift-10);
847    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
848    owl_global_set_needrefresh(&g);
849  } else {
850    owl_function_beep();
851    owl_function_makemsg("Already full left");
852  }
853}
854
855void owl_function_unsuball(void)
856{
857  unsuball();
858  owl_function_makemsg("Unsubscribed from all messages.");
859}
860
861
862/* Load zephyr subscriptions from the named 'file' and load zephyr's
863 * default subscriptions as well.  An error message is printed if
864 * 'file' can't be opened or if zephyr reports an error in
865 * subscribing.
866 *
867 * If 'file' is NULL, this look for the default filename
868 * $HOME/.zephyr.subs.  If the file can not be opened in this case
869 * only, no error message is printed.
870 */
871void owl_function_loadsubs(const char *file)
872{
873  int ret, ret2;
874  const char *foo;
875  char *path;
876
877  if (file==NULL) {
878    ret=owl_zephyr_loadsubs(NULL, 0);
879  } else {
880    path = owl_util_makepath(file);
881    ret=owl_zephyr_loadsubs(path, 1);
882    owl_free(path);
883  }
884
885  /* for backwards compatibility for now */
886  ret2=owl_zephyr_loaddefaultsubs();
887
888  if (!owl_context_is_interactive(owl_global_get_context(&g))) return;
889
890  foo=file?file:"file";
891  if (ret==0 && ret2==0) {
892    if (!file) {
893      owl_function_makemsg("Subscribed to messages.");
894    } else {
895      owl_function_makemsg("Subscribed to messages from %s", file);
896    }
897  } else if (ret==-1) {
898    owl_function_error("Could not read %s", foo);
899  } else {
900    owl_function_error("Error subscribing to messages");
901  }
902}
903
904void owl_function_loadloginsubs(const char *file)
905{
906  int ret;
907
908  ret=owl_zephyr_loadloginsubs(file);
909
910  if (!owl_context_is_interactive(owl_global_get_context(&g))) return;
911  if (ret==0) {
912  } else if (ret==-1) {
913    owl_function_error("Could not open file for login subscriptions.");
914  } else {
915    owl_function_error("Error subscribing to login messages from file.");
916  }
917}
918
919void owl_callback_aimlogin(owl_editwin *e) {
920  owl_function_aimlogin(owl_editwin_get_command(e),
921                        owl_editwin_get_text(e));
922}
923
924void owl_function_aimlogin(const char *user, const char *passwd) {
925  int ret;
926
927  /* clear the buddylist */
928  owl_buddylist_clear(owl_global_get_buddylist(&g));
929
930  /* try to login */
931  ret=owl_aim_login(user, passwd);
932  if (ret) owl_function_makemsg("Warning: login for %s failed.\n", user);
933}
934
935void owl_function_suspend(void)
936{
937  endwin();
938  printf("\n");
939  kill(getpid(), SIGSTOP);
940
941  /* resize to reinitialize all the windows when we come back */
942  owl_command_resize();
943}
944
945void owl_function_zaway_toggle(void)
946{
947  if (!owl_global_is_zaway(&g)) {
948    owl_global_set_zaway_msg(&g, owl_global_get_zaway_msg_default(&g));
949    owl_function_zaway_on();
950  } else {
951    owl_function_zaway_off();
952  }
953}
954
955void owl_function_zaway_on(void)
956{
957  owl_global_set_zaway_on(&g);
958  owl_function_makemsg("zaway set (%s)", owl_global_get_zaway_msg(&g));
959}
960
961void owl_function_zaway_off(void)
962{
963  owl_global_set_zaway_off(&g);
964  owl_function_makemsg("zaway off");
965}
966
967void owl_function_aaway_toggle(void)
968{
969  if (!owl_global_is_aaway(&g)) {
970    owl_global_set_aaway_msg(&g, owl_global_get_aaway_msg_default(&g));
971    owl_function_aaway_on();
972  } else {
973    owl_function_aaway_off();
974  }
975}
976
977void owl_function_aaway_on(void)
978{
979  owl_global_set_aaway_on(&g);
980  /* owl_aim_set_awaymsg(owl_global_get_zaway_msg(&g)); */
981  owl_function_makemsg("AIM away set (%s)", owl_global_get_aaway_msg(&g));
982}
983
984void owl_function_aaway_off(void)
985{
986  owl_global_set_aaway_off(&g);
987  /* owl_aim_set_awaymsg(""); */
988  owl_function_makemsg("AIM away off");
989}
990
991void owl_function_quit(void)
992{
993  char *ret;
994 
995  /* zlog out if we need to */
996  if (owl_global_is_havezephyr(&g) &&
997      owl_global_is_shutdownlogout(&g)) {
998    owl_zephyr_zlog_out();
999  }
1000
1001  /* execute the commands in shutdown */
1002  ret = owl_perlconfig_execute("BarnOwl::Hooks::_shutdown();");
1003  if (ret) owl_free(ret);
1004
1005  /* signal our child process, if any */
1006  if (owl_global_get_newmsgproc_pid(&g)) {
1007    kill(owl_global_get_newmsgproc_pid(&g), SIGHUP);
1008  }
1009
1010  /* Quit zephyr */
1011  owl_zephyr_shutdown();
1012 
1013  /* Quit AIM */
1014  if (owl_global_is_aimloggedin(&g)) {
1015    owl_aim_logout();
1016  }
1017
1018  /* done with curses */
1019  endwin();
1020
1021  /* restore terminal settings */
1022  tcsetattr(0, TCSAFLUSH, owl_global_get_startup_tio(&g));
1023
1024  owl_function_debugmsg("Quitting Owl");
1025  exit(0);
1026}
1027
1028void owl_function_calculate_topmsg(int direction)
1029{
1030  int recwinlines, topmsg, curmsg;
1031  const owl_view *v;
1032
1033  v=owl_global_get_current_view(&g);
1034  curmsg=owl_global_get_curmsg(&g);
1035  topmsg=owl_global_get_topmsg(&g);
1036  recwinlines=owl_global_get_recwin_lines(&g);
1037
1038  /*
1039  if (owl_view_get_size(v) < 1) {
1040    return;
1041  }
1042  */
1043
1044  switch (owl_global_get_scrollmode(&g)) {
1045  case OWL_SCROLLMODE_TOP:
1046    topmsg = owl_function_calculate_topmsg_top(direction, v, curmsg, topmsg, recwinlines);
1047    break;
1048  case OWL_SCROLLMODE_NEARTOP:
1049    topmsg = owl_function_calculate_topmsg_neartop(direction, v, curmsg, topmsg, recwinlines);
1050    break;
1051  case OWL_SCROLLMODE_CENTER:
1052    topmsg = owl_function_calculate_topmsg_center(direction, v, curmsg, topmsg, recwinlines);
1053    break;
1054  case OWL_SCROLLMODE_PAGED:
1055    topmsg = owl_function_calculate_topmsg_paged(direction, v, curmsg, topmsg, recwinlines, 0);
1056    break;
1057  case OWL_SCROLLMODE_PAGEDCENTER:
1058    topmsg = owl_function_calculate_topmsg_paged(direction, v, curmsg, topmsg, recwinlines, 1);
1059    break;
1060  case OWL_SCROLLMODE_NORMAL:
1061  default:
1062    topmsg = owl_function_calculate_topmsg_normal(direction, v, curmsg, topmsg, recwinlines);
1063  }
1064  owl_function_debugmsg("Calculated a topmsg of %i", topmsg);
1065  owl_global_set_topmsg(&g, topmsg);
1066}
1067
1068/* Returns what the new topmsg should be. 
1069 * Passed the last direction of movement,
1070 * the current view,
1071 * the current message number in the view,
1072 * the top message currently being displayed,
1073 * and the number of lines in the recwin.
1074 */
1075int owl_function_calculate_topmsg_top(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines)
1076{
1077  return(curmsg);
1078}
1079
1080int owl_function_calculate_topmsg_neartop(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines)
1081{
1082  if (curmsg>0 
1083      && (owl_message_get_numlines(owl_view_get_element(v, curmsg-1))
1084          <  recwinlines/2)) {
1085    return(curmsg-1);
1086  } else {
1087    return(curmsg);
1088  }
1089}
1090 
1091int owl_function_calculate_topmsg_center(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines)
1092{
1093  int i, last, lines;
1094
1095  last = curmsg;
1096  lines = 0;
1097  for (i=curmsg-1; i>=0; i--) {
1098    lines += owl_message_get_numlines(owl_view_get_element(v, i));
1099    if (lines > recwinlines/2) break;
1100    last = i;
1101  }
1102  return(last);
1103}
1104 
1105int owl_function_calculate_topmsg_paged(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines, int center_on_page)
1106{
1107  int i, last, lines, savey;
1108 
1109  /* If we're off the top of the screen, scroll up such that the
1110   * curmsg is near the botton of the screen. */
1111  if (curmsg < topmsg) {
1112    last = curmsg;
1113    lines = 0;
1114    for (i=curmsg; i>=0; i--) {
1115      lines += owl_message_get_numlines(owl_view_get_element(v, i));
1116      if (lines > recwinlines) break;
1117    last = i;
1118    }
1119    if (center_on_page) {
1120      return(owl_function_calculate_topmsg_center(direction, v, curmsg, 0, recwinlines));
1121    } else {
1122      return(last);
1123    }
1124  }
1125
1126  /* Find number of lines from top to bottom of curmsg (store in savey) */
1127  savey=0;
1128  for (i=topmsg; i<=curmsg; i++) {
1129    savey+=owl_message_get_numlines(owl_view_get_element(v, i));
1130  }
1131
1132  /* if we're off the bottom of the screen, scroll down */
1133  if (savey > recwinlines) {
1134    if (center_on_page) {
1135      return(owl_function_calculate_topmsg_center(direction, v, curmsg, 0, recwinlines));
1136    } else {
1137      return(curmsg);
1138    }
1139  }
1140
1141  /* else just stay as we are... */
1142  return(topmsg);
1143}
1144
1145int owl_function_calculate_topmsg_normal(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines)
1146{
1147  int savey, i, foo, y;
1148
1149  if (curmsg<0) return(topmsg);
1150   
1151  /* If we're off the top of the screen then center */
1152  if (curmsg<topmsg) {
1153    topmsg=owl_function_calculate_topmsg_center(direction, v, curmsg, 0, recwinlines);
1154  }
1155
1156  /* If curmsg is so far past topmsg that there are more messages than
1157     lines, skip the line counting that follows because we're
1158     certainly off screen.  */
1159  savey=curmsg-topmsg;
1160  if (savey <= recwinlines) {
1161    /* Find number of lines from top to bottom of curmsg (store in savey) */
1162    savey = 0;
1163    for (i=topmsg; i<=curmsg; i++) {
1164      savey+=owl_message_get_numlines(owl_view_get_element(v, i));
1165    }
1166  }
1167
1168  /* If we're off the bottom of the screen, set the topmsg to curmsg
1169   * and scroll upwards */
1170  if (savey > recwinlines) {
1171    topmsg=curmsg;
1172    savey=owl_message_get_numlines(owl_view_get_element(v, curmsg));
1173    direction=OWL_DIRECTION_UPWARDS;
1174  }
1175 
1176  /* If our bottom line is less than 1/4 down the screen then scroll up */
1177  if (direction == OWL_DIRECTION_UPWARDS || direction == OWL_DIRECTION_NONE) {
1178    if (savey < (recwinlines / 4)) {
1179      y=0;
1180      for (i=curmsg; i>=0; i--) {
1181        foo=owl_message_get_numlines(owl_view_get_element(v, i));
1182        /* will we run the curmsg off the screen? */
1183        if ((foo+y) >= recwinlines) {
1184          i++;
1185          if (i>curmsg) i=curmsg;
1186          break;
1187        }
1188        /* have saved 1/2 the screen space? */
1189        y+=foo;
1190        if (y > (recwinlines / 2)) break;
1191      }
1192      if (i<0) i=0;
1193      return(i);
1194    }
1195  }
1196
1197  if (direction == OWL_DIRECTION_DOWNWARDS || direction == OWL_DIRECTION_NONE) {
1198    /* If curmsg bottom line is more than 3/4 down the screen then scroll down */
1199    if (savey > ((recwinlines * 3)/4)) {
1200      y=0;
1201      /* count lines from the top until we can save 1/2 the screen size */
1202      for (i=topmsg; i<curmsg; i++) {
1203        y+=owl_message_get_numlines(owl_view_get_element(v, i));
1204        if (y > (recwinlines / 2)) break;
1205      }
1206      if (i==curmsg) {
1207        i--;
1208      }
1209      return(i+1);
1210    }
1211  }
1212
1213  return(topmsg);
1214}
1215
1216void owl_function_resize(void)
1217{
1218  owl_global_set_resize_pending(&g);
1219}
1220
1221void owl_function_run_buffercommand(void)
1222{
1223  owl_editwin_do_callback(owl_global_get_typwin(&g));
1224}
1225
1226void owl_function_debugmsg(const char *fmt, ...)
1227{
1228  FILE *file;
1229  time_t now;
1230  va_list ap;
1231  va_start(ap, fmt);
1232
1233  if (!owl_global_is_debug_fast(&g))
1234    return;
1235
1236  file = fopen(owl_global_get_debug_file(&g), "a");
1237  if (!file) /* XXX should report this */
1238    return;
1239
1240  now = time(NULL);
1241
1242  fprintf(file, "[%d -  %.24s - %lds]: ",
1243          (int) getpid(), ctime(&now), now - owl_global_get_starttime(&g));
1244  vfprintf(file, fmt, ap);
1245  putc('\n', file);
1246  fclose(file);
1247
1248  va_end(ap);
1249}
1250
1251void owl_function_beep(void)
1252{
1253  if (owl_global_is_bell(&g)) {
1254    beep();
1255    owl_global_set_needrefresh(&g); /* do we really need this? */
1256  }
1257}
1258
1259int owl_function_subscribe(const char *class, const char *inst, const char *recip)
1260{
1261  int ret;
1262
1263  ret=owl_zephyr_sub(class, inst, recip);
1264  if (ret) {
1265    owl_function_error("Error subscribing.");
1266  } else {
1267    owl_function_makemsg("Subscribed.");
1268  }
1269  return(ret);
1270}
1271
1272void owl_function_unsubscribe(const char *class, const char *inst, const char *recip)
1273{
1274  int ret;
1275
1276  ret=owl_zephyr_unsub(class, inst, recip);
1277  if (ret) {
1278    owl_function_error("Error subscribing.");
1279  } else {
1280    owl_function_makemsg("Unsubscribed.");
1281  }
1282}
1283
1284void owl_function_set_cursor(WINDOW *win)
1285{
1286  wnoutrefresh(win);
1287}
1288
1289void owl_function_full_redisplay(void)
1290{
1291  redrawwin(owl_global_get_curs_recwin(&g));
1292  redrawwin(owl_global_get_curs_sepwin(&g));
1293  /* Work around curses segfualts with windows off the screen */
1294  if (g.lines >= owl_global_get_typwin_lines(&g)+2)
1295      redrawwin(owl_global_get_curs_typwin(&g));
1296  if (g.lines >= 2)
1297      redrawwin(owl_global_get_curs_msgwin(&g));
1298
1299  wnoutrefresh(owl_global_get_curs_recwin(&g));
1300  wnoutrefresh(owl_global_get_curs_sepwin(&g));
1301  wnoutrefresh(owl_global_get_curs_typwin(&g));
1302  wnoutrefresh(owl_global_get_curs_msgwin(&g));
1303
1304  if (owl_popwin_is_active(owl_global_get_popwin(&g))) {
1305    owl_popwin_refresh(owl_global_get_popwin(&g));
1306  }
1307 
1308  sepbar("");
1309  owl_function_makemsg("");
1310
1311  owl_global_set_needrefresh(&g);
1312}
1313
1314void owl_function_popless_text(const char *text)
1315{
1316  owl_popwin *pw;
1317  owl_viewwin *v;
1318
1319  pw=owl_global_get_popwin(&g);
1320  v=owl_global_get_viewwin(&g);
1321
1322  owl_popwin_up(pw);
1323  owl_viewwin_init_text(v, owl_popwin_get_curswin(pw),
1324                        owl_popwin_get_lines(pw), owl_popwin_get_cols(pw),
1325                        text);
1326  owl_popwin_refresh(pw);
1327  owl_viewwin_redisplay(v, 0);
1328  owl_global_set_needrefresh(&g);
1329}
1330
1331void owl_function_popless_fmtext(const owl_fmtext *fm)
1332{
1333  owl_popwin *pw;
1334  owl_viewwin *v;
1335
1336  pw=owl_global_get_popwin(&g);
1337  v=owl_global_get_viewwin(&g);
1338
1339  owl_popwin_up(pw);
1340  owl_viewwin_init_fmtext(v, owl_popwin_get_curswin(pw),
1341                   owl_popwin_get_lines(pw), owl_popwin_get_cols(pw),
1342                   fm);
1343  owl_popwin_refresh(pw);
1344  owl_viewwin_redisplay(v, 0);
1345  owl_global_set_needrefresh(&g);
1346}
1347
1348void owl_function_popless_file(const char *filename)
1349{
1350  owl_fmtext fm;
1351  FILE *file;
1352  char *s = NULL;
1353
1354  file=fopen(filename, "r");
1355  if (!file) {
1356    owl_function_error("Could not open file: %s", filename);
1357    return;
1358  }
1359
1360  owl_fmtext_init_null(&fm);
1361  while (owl_getline(&s, file))
1362    owl_fmtext_append_normal(&fm, s);
1363  owl_free(s);
1364
1365  owl_function_popless_fmtext(&fm);
1366  owl_fmtext_free(&fm);
1367  fclose(file);
1368}
1369
1370void owl_function_about(void)
1371{
1372  owl_function_popless_text(
1373    "This is barnowl version " OWL_VERSION_STRING ".\n\n"
1374    "barnowl is a fork of the Owl zephyr client, written and\n"
1375    "maintained by Alejandro Sedeno and Nelson Elhage at the\n"
1376    "Massachusetts Institute of Technology. \n"
1377    "\n"
1378    "Owl was written by James Kretchmar. The first version, 0.5, was\n"
1379    "released in March 2002.\n"
1380    "\n"
1381    "The name 'owl' was chosen in reference to the owls in the\n"
1382    "Harry Potter novels, who are tasked with carrying messages\n"
1383    "between Witches and Wizards. The name 'barnowl' was chosen\n"
1384    "because we feel our owls should live closer to our ponies.\n"
1385    "\n"
1386    "Copyright (c) 2006-2009 The BarnOwl Developers. All rights reserved.\n"
1387    "Copyright (c) 2004 James Kretchmar. All rights reserved.\n"
1388    "Copyright 2002 Massachusetts Institute of Technology\n"
1389    "\n"
1390    "This program is free software. You can redistribute it and/or\n"
1391    "modify under the terms of the Sleepycat License. Use the \n"
1392    "':show license' command to display the full license\n"
1393  );
1394}
1395
1396void owl_function_info(void)
1397{
1398  const owl_message *m;
1399  owl_fmtext fm, attrfm;
1400  const owl_view *v;
1401#ifdef HAVE_LIBZEPHYR
1402  const ZNotice_t *n;
1403#endif
1404
1405  owl_fmtext_init_null(&fm);
1406 
1407  v=owl_global_get_current_view(&g);
1408  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
1409  if (!m || owl_view_get_size(v)==0) {
1410    owl_function_error("No message selected\n");
1411    return;
1412  }
1413
1414  owl_fmtext_append_bold(&fm, "General Information:\n");
1415  owl_fmtext_appendf_normal(&fm, "  Msg Id    : %i\n", owl_message_get_id(m));
1416
1417  owl_fmtext_append_normal(&fm, "  Type      : ");
1418  owl_fmtext_append_bold(&fm, owl_message_get_type(m));
1419  owl_fmtext_append_normal(&fm, "\n");
1420
1421  if (owl_message_is_direction_in(m)) {
1422    owl_fmtext_append_normal(&fm, "  Direction : in\n");
1423  } else if (owl_message_is_direction_out(m)) {
1424    owl_fmtext_append_normal(&fm, "  Direction : out\n");
1425  } else if (owl_message_is_direction_none(m)) {
1426    owl_fmtext_append_normal(&fm, "  Direction : none\n");
1427  } else {
1428    owl_fmtext_append_normal(&fm, "  Direction : unknown\n");
1429  }
1430
1431  owl_fmtext_appendf_normal(&fm, "  Time      : %s\n", owl_message_get_timestr(m));
1432
1433  if (!owl_message_is_type_admin(m)) {
1434    owl_fmtext_appendf_normal(&fm, "  Sender    : %s\n", owl_message_get_sender(m));
1435    owl_fmtext_appendf_normal(&fm, "  Recipient : %s\n", owl_message_get_recipient(m));
1436  }
1437
1438  if (owl_message_is_type_zephyr(m)) {
1439    owl_fmtext_append_bold(&fm, "\nZephyr Specific Information:\n");
1440   
1441    owl_fmtext_appendf_normal(&fm, "  Class     : %s\n", owl_message_get_class(m));
1442    owl_fmtext_appendf_normal(&fm, "  Instance  : %s\n", owl_message_get_instance(m));
1443    owl_fmtext_appendf_normal(&fm, "  Opcode    : %s\n", owl_message_get_opcode(m));
1444#ifdef HAVE_LIBZEPHYR
1445    if (owl_message_is_direction_in(m)) {
1446      char *ptr, tmpbuff[1024];
1447      int i, j, fields, len;
1448
1449      n=owl_message_get_notice(m);
1450
1451      if (!owl_message_is_pseudo(m)) {
1452        owl_fmtext_append_normal(&fm, "  Kind      : ");
1453        if (n->z_kind==UNSAFE) {
1454          owl_fmtext_append_normal(&fm, "UNSAFE\n");
1455        } else if (n->z_kind==UNACKED) {
1456          owl_fmtext_append_normal(&fm, "UNACKED\n");
1457        } else if (n->z_kind==ACKED) {
1458          owl_fmtext_append_normal(&fm, "ACKED\n");
1459        } else if (n->z_kind==HMACK) {
1460          owl_fmtext_append_normal(&fm, "HMACK\n");
1461        } else if (n->z_kind==HMCTL) {
1462          owl_fmtext_append_normal(&fm, "HMCTL\n");
1463        } else if (n->z_kind==SERVACK) {
1464          owl_fmtext_append_normal(&fm, "SERVACK\n");
1465        } else if (n->z_kind==SERVNAK) {
1466          owl_fmtext_append_normal(&fm, "SERVNACK\n");
1467        } else if (n->z_kind==CLIENTACK) {
1468          owl_fmtext_append_normal(&fm, "CLIENTACK\n");
1469        } else if (n->z_kind==STAT) {
1470          owl_fmtext_append_normal(&fm, "STAT\n");
1471        } else {
1472          owl_fmtext_append_normal(&fm, "ILLEGAL VALUE\n");
1473        }
1474      }
1475      owl_fmtext_appendf_normal(&fm, "  Host      : %s\n", owl_message_get_hostname(m));
1476
1477      if (!owl_message_is_pseudo(m)) {
1478        owl_fmtext_append_normal(&fm, "\n");
1479        owl_fmtext_appendf_normal(&fm, "  Port      : %i\n", ntohs(n->z_port));
1480        owl_fmtext_appendf_normal(&fm, "  Auth      : %s\n", owl_zephyr_get_authstr(n));
1481
1482        /* FIXME make these more descriptive */
1483        owl_fmtext_appendf_normal(&fm, "  Checkd Ath: %i\n", n->z_checked_auth);
1484        owl_fmtext_appendf_normal(&fm, "  Multi notc: %s\n", n->z_multinotice);
1485        owl_fmtext_appendf_normal(&fm, "  Num other : %i\n", n->z_num_other_fields);
1486        owl_fmtext_appendf_normal(&fm, "  Msg Len   : %i\n", n->z_message_len);
1487
1488        fields=owl_zephyr_get_num_fields(n);
1489        owl_fmtext_appendf_normal(&fm, "  Fields    : %i\n", fields);
1490
1491        for (i=0; i<fields; i++) {
1492          ptr=owl_zephyr_get_field_as_utf8(n, i+1);
1493          len=strlen(ptr);
1494          if (len<30) {
1495            strncpy(tmpbuff, ptr, len);
1496            tmpbuff[len]='\0';
1497          } else {
1498            strncpy(tmpbuff, ptr, 30);
1499            tmpbuff[30]='\0';
1500            strcat(tmpbuff, "...");
1501          }
1502          owl_free(ptr);
1503
1504          for (j=0; j<strlen(tmpbuff); j++) {
1505            if (tmpbuff[j]=='\n') tmpbuff[j]='~';
1506            if (tmpbuff[j]=='\r') tmpbuff[j]='!';
1507          }
1508
1509          owl_fmtext_appendf_normal(&fm, "  Field %i   : %s\n", i+1, tmpbuff);
1510        }
1511        owl_fmtext_appendf_normal(&fm, "  Default Fm: %s\n", n->z_default_format);
1512      }
1513
1514    }
1515#endif
1516  }
1517
1518  owl_fmtext_append_bold(&fm, "\nOwl Message Attributes:\n");
1519  owl_message_attributes_tofmtext(m, &attrfm);
1520  owl_fmtext_append_fmtext(&fm, &attrfm);
1521 
1522  owl_function_popless_fmtext(&fm);
1523  owl_fmtext_free(&fm);
1524  owl_fmtext_free(&attrfm);
1525}
1526
1527/* print the current message in a popup window.
1528 * Use the 'default' style regardless of whatever
1529 * style the user may be using
1530 */
1531void owl_function_curmsg_to_popwin(void)
1532{
1533  const owl_view *v;
1534  const owl_message *m;
1535  const owl_style *s;
1536  owl_fmtext fm;
1537
1538  v=owl_global_get_current_view(&g);
1539  s=owl_global_get_style_by_name(&g, "default");
1540
1541  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
1542
1543  if (!m || owl_view_get_size(v)==0) {
1544    owl_function_error("No current message");
1545    return;
1546  }
1547
1548  owl_fmtext_init_null(&fm);
1549  owl_style_get_formattext(s, &fm, m);
1550
1551  owl_function_popless_fmtext(&fm);
1552  owl_fmtext_free(&fm);
1553}
1554
1555void owl_function_page_curmsg(int step)
1556{
1557  /* scroll down or up within the current message IF the message is truncated */
1558
1559  int offset, curmsg, lines;
1560  const owl_view *v;
1561  owl_message *m;
1562
1563  offset=owl_global_get_curmsg_vert_offset(&g);
1564  v=owl_global_get_current_view(&g);
1565  curmsg=owl_global_get_curmsg(&g);
1566  m=owl_view_get_element(v, curmsg);
1567  if (!m || owl_view_get_size(v)==0) return;
1568  lines=owl_message_get_numlines(m);
1569
1570  if (offset==0) {
1571    /* Bail if the curmsg isn't the last one displayed */
1572    if (curmsg != owl_mainwin_get_last_msg(owl_global_get_mainwin(&g))) {
1573      owl_function_makemsg("The entire message is already displayed");
1574      return;
1575    }
1576   
1577    /* Bail if we're not truncated */
1578    if (!owl_mainwin_is_curmsg_truncated(owl_global_get_mainwin(&g))) {
1579      owl_function_makemsg("The entire message is already displayed");
1580      return;
1581    }
1582  }
1583 
1584 
1585  /* don't scroll past the last line */
1586  if (step>0) {
1587    if (offset+step > lines-1) {
1588      owl_global_set_curmsg_vert_offset(&g, lines-1);
1589    } else {
1590      owl_global_set_curmsg_vert_offset(&g, offset+step);
1591    }
1592  }
1593
1594  /* would we be before the beginning of the message? */
1595  if (step<0) {
1596    if (offset+step<0) {
1597      owl_global_set_curmsg_vert_offset(&g, 0);
1598    } else {
1599      owl_global_set_curmsg_vert_offset(&g, offset+step);
1600    }
1601  }
1602 
1603  /* redisplay */
1604  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
1605  owl_global_set_needrefresh(&g);
1606}
1607
1608void owl_function_resize_typwin(int newsize)
1609{
1610  owl_global_set_typwin_lines(&g, newsize);
1611  owl_function_resize();
1612}
1613
1614void owl_function_mainwin_pagedown(void)
1615{
1616  int i;
1617
1618  i=owl_mainwin_get_last_msg(owl_global_get_mainwin(&g));
1619  if (i<0) return;
1620  if (owl_mainwin_is_last_msg_truncated(owl_global_get_mainwin(&g))
1621      && (owl_global_get_curmsg(&g) < i)
1622      && (i>0)) {
1623    i--;
1624  }
1625  owl_global_set_curmsg(&g, i);
1626  owl_function_nextmsg();
1627}
1628
1629void owl_function_mainwin_pageup(void)
1630{
1631  owl_global_set_curmsg(&g, owl_global_get_topmsg(&g));
1632  owl_function_prevmsg();
1633}
1634
1635void owl_function_getsubs(void)
1636{
1637  char *buff;
1638
1639  buff=owl_zephyr_getsubs();
1640
1641  if (buff) {
1642    owl_function_popless_text(buff);
1643  } else {
1644    owl_function_popless_text("Error getting subscriptions");
1645  }
1646           
1647  owl_free(buff);
1648}
1649
1650void owl_function_printallvars(void)
1651{
1652  const char *name;
1653  char var[LINE];
1654  owl_list varnames;
1655  int i, numvarnames;
1656  GString *str   = g_string_new("");
1657
1658  g_string_append_printf(str, "%-20s = %s\n", "VARIABLE", "VALUE");
1659  g_string_append_printf(str, "%-20s   %s\n",  "--------", "-----");
1660  owl_variable_dict_get_names(owl_global_get_vardict(&g), &varnames);
1661  numvarnames = owl_list_get_size(&varnames);
1662  for (i=0; i<numvarnames; i++) {
1663    name = owl_list_get_element(&varnames, i);
1664    if (name && name[0]!='_') {
1665      g_string_append_printf(str, "\n%-20s = ", name);
1666      owl_variable_get_tostring(owl_global_get_vardict(&g), name, var, LINE);
1667      g_string_append(str, var);
1668    }
1669  }
1670  g_string_append(str, "\n");
1671  owl_variable_dict_namelist_free(&varnames);
1672
1673  owl_function_popless_text(str->str);
1674  g_string_free(str, TRUE);
1675}
1676
1677void owl_function_show_variables(void)
1678{
1679  owl_list varnames;
1680  owl_fmtext fm; 
1681  int i, numvarnames;
1682  const char *varname;
1683
1684  owl_fmtext_init_null(&fm);
1685  owl_fmtext_append_bold(&fm, 
1686      "Variables: (use 'show variable <name>' for details)\n");
1687  owl_variable_dict_get_names(owl_global_get_vardict(&g), &varnames);
1688  numvarnames = owl_list_get_size(&varnames);
1689  for (i=0; i<numvarnames; i++) {
1690    varname = owl_list_get_element(&varnames, i);
1691    if (varname && varname[0]!='_') {
1692      owl_variable_describe(owl_global_get_vardict(&g), varname, &fm);
1693    }
1694  }
1695  owl_variable_dict_namelist_free(&varnames);
1696  owl_function_popless_fmtext(&fm);
1697  owl_fmtext_free(&fm);
1698}
1699
1700void owl_function_show_variable(const char *name)
1701{
1702  owl_fmtext fm; 
1703
1704  owl_fmtext_init_null(&fm);
1705  owl_variable_get_help(owl_global_get_vardict(&g), name, &fm);
1706  owl_function_popless_fmtext(&fm);
1707  owl_fmtext_free(&fm); 
1708}
1709
1710/* note: this applies to global message list, not to view.
1711 * If flag is 1, deletes.  If flag is 0, undeletes. */
1712void owl_function_delete_by_id(int id, int flag)
1713{
1714  const owl_messagelist *ml;
1715  owl_message *m;
1716  ml = owl_global_get_msglist(&g);
1717  m = owl_messagelist_get_by_id(ml, id);
1718  if (m) {
1719    if (flag == 1) {
1720      owl_message_mark_delete(m);
1721    } else if (flag == 0) {
1722      owl_message_unmark_delete(m);
1723    }
1724    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
1725    owl_global_set_needrefresh(&g);
1726  } else {
1727    owl_function_error("No message with id %d: unable to mark for (un)delete",id);
1728  }
1729}
1730
1731void owl_function_delete_automsgs(void)
1732{
1733  /* mark for deletion all messages in the current view that match the
1734   * 'trash' filter */
1735
1736  int i, j, count;
1737  owl_message *m;
1738  const owl_view *v;
1739  const owl_filter *f;
1740
1741  /* get the trash filter */
1742  f=owl_global_get_filter(&g, "trash");
1743  if (!f) {
1744    owl_function_error("No trash filter defined");
1745    return;
1746  }
1747
1748  v=owl_global_get_current_view(&g);
1749
1750  count=0;
1751  j=owl_view_get_size(v);
1752  for (i=0; i<j; i++) {
1753    m=owl_view_get_element(v, i);
1754    if (owl_filter_message_match(f, m)) {
1755      count++;
1756      owl_message_mark_delete(m);
1757    }
1758  }
1759  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
1760  owl_function_makemsg("%i messages marked for deletion", count);
1761  owl_global_set_needrefresh(&g);
1762}
1763
1764void owl_function_status(void)
1765{
1766  char buff[MAXPATHLEN+1];
1767  time_t start;
1768  int up, days, hours, minutes;
1769  owl_fmtext fm;
1770
1771  owl_fmtext_init_null(&fm);
1772
1773  start=owl_global_get_starttime(&g);
1774
1775  owl_fmtext_append_normal(&fm, "General Information:\n");
1776
1777  owl_fmtext_append_normal(&fm, "  Version: ");
1778  owl_fmtext_append_normal(&fm, OWL_VERSION_STRING);
1779  owl_fmtext_append_normal(&fm, "\n");
1780
1781  owl_fmtext_append_normal(&fm, "  Startup Arguments: ");
1782  owl_fmtext_append_normal(&fm, owl_global_get_startupargs(&g));
1783  owl_fmtext_append_normal(&fm, "\n");
1784
1785  owl_fmtext_append_normal(&fm, "  Current Directory: ");
1786  if(getcwd(buff, MAXPATHLEN) == NULL) {
1787    owl_fmtext_append_normal(&fm, "<Error in getcwd>");
1788  } else {
1789    owl_fmtext_append_normal(&fm, buff);
1790  }
1791  owl_fmtext_append_normal(&fm, "\n");
1792
1793  owl_fmtext_appendf_normal(&fm, "  Startup Time: %s", ctime(&start));
1794
1795  up=owl_global_get_runtime(&g);
1796  days=up/86400;
1797  up-=days*86400;
1798  hours=up/3600;
1799  up-=hours*3600;
1800  minutes=up/60;
1801  up-=minutes*60;
1802  owl_fmtext_appendf_normal(&fm, "  Run Time: %i days %2.2i:%2.2i:%2.2i\n", days, hours, minutes, up);
1803
1804  owl_fmtext_append_normal(&fm, "\nProtocol Options:\n");
1805  owl_fmtext_append_normal(&fm, "  Zephyr included    : ");
1806  if (owl_global_is_havezephyr(&g)) {
1807    owl_fmtext_append_normal(&fm, "yes\n");
1808  } else {
1809    owl_fmtext_append_normal(&fm, "no\n");
1810  }
1811  owl_fmtext_append_normal(&fm, "  AIM included       : yes\n");
1812  owl_fmtext_append_normal(&fm, "  Loopback included  : yes\n");
1813
1814
1815  owl_fmtext_append_normal(&fm, "\nBuild Options:\n");
1816  owl_fmtext_append_normal(&fm, "  Stderr redirection : ");
1817#if OWL_STDERR_REDIR
1818  owl_fmtext_append_normal(&fm, "yes\n");
1819#else
1820  owl_fmtext_append_normal(&fm, "no\n");
1821#endif
1822 
1823
1824  owl_fmtext_append_normal(&fm, "\nAIM Status:\n");
1825  owl_fmtext_append_normal(&fm, "  Logged in: ");
1826  if (owl_global_is_aimloggedin(&g)) {
1827    owl_fmtext_append_normal(&fm, owl_global_get_aim_screenname(&g));
1828    owl_fmtext_append_normal(&fm, "\n");
1829  } else {
1830    owl_fmtext_append_normal(&fm, "(not logged in)\n");
1831  }
1832
1833  owl_fmtext_append_normal(&fm, "  Processing events: ");
1834  if (owl_global_is_doaimevents(&g)) {
1835    owl_fmtext_append_normal(&fm, "yes\n");
1836  } else {
1837    owl_fmtext_append_normal(&fm, "no\n");
1838  }
1839
1840  owl_function_popless_fmtext(&fm);
1841  owl_fmtext_free(&fm);
1842}
1843
1844void owl_function_show_term(void)
1845{
1846  owl_fmtext fm;
1847
1848  owl_fmtext_init_null(&fm);
1849  owl_fmtext_appendf_normal(&fm, "Terminal Lines: %i\nTerminal Columns: %i\n",
1850          owl_global_get_lines(&g),
1851          owl_global_get_cols(&g));
1852
1853  if (owl_global_get_hascolors(&g)) {
1854    owl_fmtext_append_normal(&fm, "Color: Yes\n");
1855    owl_fmtext_appendf_normal(&fm, "Number of color pairs: %i\n", owl_global_get_colorpairs(&g));
1856    owl_fmtext_appendf_normal(&fm, "Can change colors: %s\n", can_change_color() ? "yes" : "no");
1857  } else {
1858    owl_fmtext_append_normal(&fm, "Color: No\n");
1859  }
1860
1861  owl_function_popless_fmtext(&fm);
1862  owl_fmtext_free(&fm);
1863}
1864
1865/* if type = 0 then normal reply.
1866 * if type = 1 then it's a reply to sender
1867 * if enter = 0 then allow the command to be edited
1868 * if enter = 1 then don't wait for editing
1869 */
1870void owl_function_reply(int type, int enter)
1871{
1872  char *buff=NULL;
1873  const owl_message *m;
1874  const owl_filter *f;
1875 
1876  if (owl_view_get_size(owl_global_get_current_view(&g))==0) {
1877    owl_function_error("No message selected");
1878  } else {
1879    char *cmd;
1880   
1881    m=owl_view_get_element(owl_global_get_current_view(&g), owl_global_get_curmsg(&g));
1882    if (!m) {
1883      owl_function_error("No message selected");
1884      return;
1885    }
1886
1887    /* first check if we catch the reply-lockout filter */
1888    f=owl_global_get_filter(&g, "reply-lockout");
1889    if (f) {
1890      if (owl_filter_message_match(f, m)) {
1891        owl_function_error("Sorry, replies to this message have been disabled by the reply-lockout filter");
1892        return;
1893      }
1894    }
1895
1896    /* then check if it's a question and just bring up the command prompt */
1897    if (owl_message_is_question(m)) {
1898      owl_function_start_command("");
1899      return;
1900    }
1901
1902    if((type == 0 &&
1903        (cmd=owl_perlconfig_message_call_method(m, "replycmd", 0, NULL))) ||
1904       (type == 1 &&
1905        (cmd=owl_perlconfig_message_call_method(m, "replysendercmd", 0, NULL)))) {
1906      buff = cmd;
1907    }
1908
1909    if(!buff) {
1910        owl_function_error("I don't know how to reply to that message.");
1911        return;
1912    }
1913
1914    if (enter) {
1915      owl_history *hist = owl_global_get_cmd_history(&g);
1916      owl_history_store(hist, buff);
1917      owl_history_reset(hist);
1918      owl_function_command_norv(buff);
1919    } else {
1920      owl_function_start_command(buff);
1921    }
1922    owl_free(buff);
1923  }
1924}
1925
1926void owl_function_zlocate(int argc, const char *const *argv, int auth)
1927{
1928  owl_fmtext fm;
1929  char *ptr;
1930  char *result;
1931  int i;
1932
1933  owl_fmtext_init_null(&fm);
1934
1935  for (i=0; i<argc; i++) {
1936    ptr = long_zuser(argv[i]);
1937    result = owl_zephyr_zlocate(ptr, auth);
1938    owl_fmtext_append_normal(&fm, result);
1939    owl_free(result);
1940    owl_free(ptr);
1941  }
1942
1943  owl_function_popless_fmtext(&fm);
1944  owl_fmtext_free(&fm);
1945}
1946
1947void owl_function_start_command(const char *line)
1948{
1949  owl_editwin *tw;
1950
1951  tw=owl_global_get_typwin(&g);
1952  owl_global_set_typwin_active(&g);
1953  owl_editwin_new_style(tw, OWL_EDITWIN_STYLE_ONELINE, 
1954                        owl_global_get_cmd_history(&g));
1955
1956  owl_editwin_set_locktext(tw, "command: ");
1957  owl_global_set_needrefresh(&g);
1958
1959  owl_editwin_insert_string(tw, line);
1960  owl_editwin_redisplay(tw, 0);
1961
1962  owl_context_set_editline(owl_global_get_context(&g), tw);
1963  owl_function_activate_keymap("editline");
1964}
1965
1966void owl_function_start_question(const char *line)
1967{
1968  owl_editwin *tw;
1969
1970  tw=owl_global_get_typwin(&g);
1971  owl_global_set_typwin_active(&g);
1972  owl_editwin_new_style(tw, OWL_EDITWIN_STYLE_ONELINE, owl_global_get_cmd_history(&g));
1973
1974  owl_editwin_set_locktext(tw, line);
1975  owl_global_set_needrefresh(&g);
1976
1977  owl_editwin_redisplay(tw, 0);
1978
1979  owl_context_set_editresponse(owl_global_get_context(&g), tw);
1980  owl_function_activate_keymap("editresponse");
1981}
1982
1983void owl_function_start_password(const char *line)
1984{
1985  owl_editwin *tw;
1986
1987  tw=owl_global_get_typwin(&g);
1988  owl_global_set_typwin_active(&g);
1989  owl_editwin_new_style(tw, OWL_EDITWIN_STYLE_ONELINE, owl_global_get_cmd_history(&g));
1990  owl_editwin_set_echochar(tw, '*');
1991
1992  owl_editwin_set_locktext(tw, line);
1993  owl_global_set_needrefresh(&g);
1994
1995  owl_editwin_redisplay(tw, 0);
1996
1997  owl_context_set_editresponse(owl_global_get_context(&g), tw);
1998  owl_function_activate_keymap("editresponse");
1999}
2000
2001char *owl_function_exec(int argc, const char *const *argv, const char *buff, int type)
2002{
2003  /* if type == 1 display in a popup
2004   * if type == 2 display an admin messages
2005   * if type == 0 return output
2006   * else display in a popup
2007   */
2008  const char *redirect = " 2>&1 < /dev/null";
2009  char *newbuff;
2010  char *out;
2011  FILE *p;
2012
2013#if OWL_STDERR_REDIR
2014  redirect = " < /dev/null";
2015#endif
2016
2017  if (argc<2) {
2018    owl_function_error("Wrong number of arguments to the exec command");
2019    return NULL;
2020  }
2021
2022  buff = skiptokens(buff, 1);
2023  newbuff = owl_sprintf("%s%s", buff, redirect);
2024
2025  if (type == 1) {
2026    owl_popexec_new(newbuff);
2027  } else {
2028    p = popen(newbuff, "r");
2029    out = owl_slurp(p);
2030    pclose(p);
2031   
2032    if (type==1) {
2033      owl_function_popless_text(out);
2034    } else if (type==0) {
2035      return out;
2036    } else if (type==2) {
2037      owl_function_adminmsg(buff, out);
2038    } else {
2039      owl_function_popless_text(out);
2040    }
2041    owl_free(out);
2042  }
2043  return NULL;
2044}
2045
2046char *owl_function_perl(int argc, const char *const *argv, const char *buff, int type)
2047{
2048  /* if type == 1 display in a popup
2049   * if type == 2 display an admin messages
2050   * if type == 0 return output
2051   * else display in a popup
2052   */
2053  char *perlout;
2054
2055  if (argc<2) {
2056    owl_function_error("Wrong number of arguments to perl command");
2057    return NULL;
2058  }
2059
2060  /* consume first token (argv[0]) */
2061  buff = skiptokens(buff, 1);
2062
2063  perlout = owl_perlconfig_execute(buff);
2064  if (perlout) { 
2065    if (type==1) {
2066      owl_function_popless_text(perlout);
2067    } else if (type==2) {
2068      owl_function_adminmsg(buff, perlout);
2069    } else if (type==0) {
2070      return perlout;
2071    } else {
2072      owl_function_popless_text(perlout);
2073    }
2074    owl_free(perlout);
2075  }
2076  return NULL;
2077}
2078
2079/* Change the filter associated with the current view.
2080 * This also figures out which message in the new filter
2081 * should have the pointer.
2082 */
2083void owl_function_change_currentview_filter(const char *filtname)
2084{
2085  owl_view *v;
2086  owl_filter *f;
2087  int curid=-1, newpos, curmsg;
2088  const owl_message *curm=NULL;
2089
2090  v=owl_global_get_current_view(&g);
2091
2092  curmsg=owl_global_get_curmsg(&g);
2093  if (curmsg==-1) {
2094    owl_function_debugmsg("Hit the curmsg==-1 case in change_view");
2095  } else {
2096    curm=owl_view_get_element(v, curmsg);
2097    if (curm) {
2098      curid=owl_message_get_id(curm);
2099      owl_view_save_curmsgid(v, curid);
2100    }
2101  }
2102
2103  f=owl_global_get_filter(&g, filtname);
2104  if (!f) {
2105    owl_function_error("Unknown filter %s", filtname);
2106    return;
2107  }
2108
2109  owl_view_new_filter(v, f);
2110
2111  /* Figure out what to set the current message to.
2112   * - If the view we're leaving has messages in it, go to the closest message
2113   *   to the last message pointed to in that view.
2114   * - If the view we're leaving is empty, try to restore the position
2115   *   from the last time we were in the new view.  */
2116  if (curm) {
2117    newpos = owl_view_get_nearest_to_msgid(v, curid);
2118  } else {
2119    newpos = owl_view_get_nearest_to_saved(v);
2120  }
2121
2122  owl_global_set_curmsg(&g, newpos);
2123  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
2124  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2125  owl_global_set_direction_downwards(&g);
2126}
2127
2128/* Create a new filter, or replace an existing one
2129 * with a new definition.
2130 */
2131void owl_function_create_filter(int argc, const char *const *argv)
2132{
2133  owl_filter *f;
2134  const owl_view *v;
2135  int ret, inuse=0;
2136
2137  if (argc < 2) {
2138    owl_function_error("Wrong number of arguments to filter command");
2139    return;
2140  }
2141
2142  owl_function_debugmsg("owl_function_create_filter: starting to create filter named %s", argv[1]);
2143
2144  v=owl_global_get_current_view(&g);
2145
2146  /* don't touch the all filter */
2147  if (!strcmp(argv[1], "all")) {
2148    owl_function_error("You may not change the 'all' filter.");
2149    return;
2150  }
2151
2152  /* deal with the case of trying change the filter color */
2153  if (argc==4 && !strcmp(argv[2], "-c")) {
2154    f=owl_global_get_filter(&g, argv[1]);
2155    if (!f) {
2156      owl_function_error("The filter '%s' does not exist.", argv[1]);
2157      return;
2158    }
2159    if (owl_util_string_to_color(argv[3])==OWL_COLOR_INVALID) {
2160      owl_function_error("The color '%s' is not available.", argv[3]);
2161      return;
2162    }
2163    owl_filter_set_fgcolor(f, owl_util_string_to_color(argv[3]));
2164    owl_global_set_needrefresh(&g);
2165    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2166    return;
2167  }
2168  if (argc==4 && !strcmp(argv[2], "-b")) {
2169    f=owl_global_get_filter(&g, argv[1]);
2170    if (!f) {
2171      owl_function_error("The filter '%s' does not exist.", argv[1]);
2172      return;
2173    }
2174    if (owl_util_string_to_color(argv[3])==OWL_COLOR_INVALID) {
2175      owl_function_error("The color '%s' is not available.", argv[3]);
2176      return;
2177    }
2178    owl_filter_set_bgcolor(f, owl_util_string_to_color(argv[3]));
2179    owl_global_set_needrefresh(&g);
2180    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2181    return;
2182  }
2183
2184  /* create the filter and check for errors */
2185  f=owl_malloc(sizeof(owl_filter));
2186  ret=owl_filter_init(f, argv[1], argc-2, argv+2);
2187  if (ret==-1) {
2188    owl_free(f);
2189    owl_function_error("Invalid filter");
2190    return;
2191  }
2192
2193  /* if the named filter is in use by the current view, remember it */
2194  if (!strcmp(owl_view_get_filtname(v), argv[1])) {
2195    inuse=1;
2196  }
2197
2198  /* if the named filter already exists, nuke it */
2199  if (owl_global_get_filter(&g, argv[1])) {
2200    owl_global_remove_filter(&g, argv[1]);
2201  }
2202
2203  /* add the filter */
2204  owl_global_add_filter(&g, f);
2205
2206  /* if it was in use by the current view then update */
2207  if (inuse) {
2208    owl_function_change_currentview_filter(argv[1]);
2209  }
2210  owl_global_set_needrefresh(&g);
2211  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2212}
2213
2214/* If 'filtername' does not start with 'not-' create a filter named
2215 * 'not-<filtername>' defined as "not filter <filtername>".  If the
2216 * filter 'not-<filtername>' already exists, do not overwrite it.  If
2217 * 'filtername' begins with 'not-' and a filter 'filtername' already
2218 * exists, then do nothing.  If the filter 'filtername' does not
2219 * exist, create it and define it as 'not filter <filtername>'
2220 *
2221 * Returns the name of the negated filter, which the caller must free.
2222 */
2223char *owl_function_create_negative_filter(const char *filtername)
2224{
2225  char *newname;
2226  const owl_filter *tmpfilt;
2227  const char *argv[5];
2228
2229  owl_function_debugmsg("owl_function_create_negative_filter");
2230 
2231  if (!strncmp(filtername, "not-", 4)) {
2232    newname=owl_strdup(filtername+4);
2233  } else {
2234    newname=owl_sprintf("not-%s", filtername);
2235  }
2236
2237  tmpfilt=owl_global_get_filter(&g, newname);
2238  if (!tmpfilt) {
2239    argv[0]="filter"; /* anything is fine here */
2240    argv[1]=newname;
2241    argv[2]="not";
2242    argv[3]="filter";
2243    argv[4]=filtername;
2244    owl_function_create_filter(5, argv);
2245  }
2246
2247  owl_function_debugmsg("owl_function_create_negative_filter: returning with %s", newname);
2248  return(newname);
2249}
2250
2251void owl_function_show_filters(void)
2252{
2253  const owl_list *l;
2254  const owl_filter *f;
2255  int i, j;
2256  owl_fmtext fm;
2257
2258  owl_fmtext_init_null(&fm);
2259
2260  l=owl_global_get_filterlist(&g);
2261  j=owl_list_get_size(l);
2262
2263  owl_fmtext_append_bold(&fm, "Filters:\n");
2264
2265  for (i=0; i<j; i++) {
2266    f=owl_list_get_element(l, i);
2267    owl_fmtext_append_normal(&fm, "   ");
2268    if (owl_global_get_hascolors(&g)) {
2269      owl_fmtext_append_normal_color(&fm, owl_filter_get_name(f), owl_filter_get_fgcolor(f), owl_filter_get_bgcolor(f));
2270    } else {
2271      owl_fmtext_append_normal(&fm, owl_filter_get_name(f));
2272    }
2273    owl_fmtext_append_normal(&fm, "\n");
2274  }
2275  owl_function_popless_fmtext(&fm);
2276  owl_fmtext_free(&fm);
2277}
2278
2279void owl_function_show_filter(const char *name)
2280{
2281  const owl_filter *f;
2282  char *buff, *tmp;
2283
2284  f=owl_global_get_filter(&g, name);
2285  if (!f) {
2286    owl_function_error("There is no filter named %s", name);
2287    return;
2288  }
2289  tmp = owl_filter_print(f);
2290  buff = owl_sprintf("%s: %s", owl_filter_get_name(f), tmp);
2291  owl_function_popless_text(buff);
2292  owl_free(buff);
2293  owl_free(tmp);
2294}
2295
2296void owl_function_show_zpunts(void)
2297{
2298  const owl_filter *f;
2299  const owl_list *fl;
2300  char buff[5000];
2301  char *tmp;
2302  owl_fmtext fm;
2303  int i, j;
2304
2305  owl_fmtext_init_null(&fm);
2306
2307  fl=owl_global_get_puntlist(&g);
2308  j=owl_list_get_size(fl);
2309  owl_fmtext_append_bold(&fm, "Active zpunt filters:\n");
2310
2311  for (i=0; i<j; i++) {
2312    f=owl_list_get_element(fl, i);
2313    snprintf(buff, sizeof(buff), "[% 2d] ", i+1);
2314    owl_fmtext_append_normal(&fm, buff);
2315    tmp = owl_filter_print(f);
2316    owl_fmtext_append_normal(&fm, tmp);
2317    owl_free(tmp);
2318  }
2319  owl_function_popless_fmtext(&fm);
2320  owl_fmtext_free(&fm);
2321}
2322
2323/* Create a filter for a class, instance if one doesn't exist.  If
2324 * instance is NULL then catch all messgaes in the class.  Returns the
2325 * name of the filter, which the caller must free.
2326 */
2327char *owl_function_classinstfilt(const char *c, const char *i) 
2328{
2329  owl_filter *f;
2330  char *argbuff, *filtname;
2331  char *tmpclass, *tmpinstance = NULL;
2332  char *class, *instance = NULL;
2333
2334  class = owl_util_baseclass(c);
2335  if(i) {
2336    instance = owl_util_baseclass(i);
2337  }
2338
2339  /* name for the filter */
2340  if (!instance) {
2341    filtname = owl_sprintf("class-%s", class);
2342  } else {
2343    filtname = owl_sprintf("class-%s-instance-%s", class, instance);
2344  }
2345  /* downcase it */
2346  {
2347    char *temp = g_utf8_strdown(filtname, -1);
2348    if (temp) {
2349      owl_free(filtname);
2350      filtname = temp;
2351    }
2352  }
2353  /* turn spaces, single quotes, and double quotes into dots */
2354  owl_text_tr(filtname, ' ', '.');
2355  owl_text_tr(filtname, '\'', '.');
2356  owl_text_tr(filtname, '"', '.');
2357 
2358  /* if it already exists then go with it.  This lets users override */
2359  if (owl_global_get_filter(&g, filtname)) {
2360    return(filtname);
2361  }
2362
2363  /* create the new filter */
2364  tmpclass=owl_text_quote(class, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2365  owl_text_tr(tmpclass, ' ', '.');
2366  owl_text_tr(tmpclass, '\'', '.');
2367  owl_text_tr(tmpclass, '"', '.');
2368  if (instance) {
2369    tmpinstance=owl_text_quote(instance, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2370    owl_text_tr(tmpinstance, ' ', '.');
2371    owl_text_tr(tmpinstance, '\'', '.');
2372    owl_text_tr(tmpinstance, '"', '.');
2373  }
2374
2375  argbuff = owl_sprintf("class ^(un)*%s(\\.d)*$", tmpclass);
2376  if (tmpinstance) {
2377    char *tmp = argbuff;
2378    argbuff = owl_sprintf("%s and ( instance ^(un)*%s(\\.d)*$ )", tmp, tmpinstance);
2379    owl_free(tmp);
2380  }
2381  owl_free(tmpclass);
2382  if (tmpinstance) owl_free(tmpinstance);
2383
2384  f=owl_malloc(sizeof(owl_filter));
2385  owl_filter_init_fromstring(f, filtname, argbuff);
2386
2387  /* add it to the global list */
2388  owl_global_add_filter(&g, f);
2389
2390  owl_free(argbuff);
2391  owl_free(class);
2392  if (instance) {
2393    owl_free(instance);
2394  }
2395  return(filtname);
2396}
2397
2398/* Create a filter for personal zephyrs to or from the specified
2399 * zephyr user.  Includes login/logout notifications for the user.
2400 * The name of the filter will be 'user-<user>'.  If a filter already
2401 * exists with this name, no new filter will be created.  This allows
2402 * the configuration to override this function.  Returns the name of
2403 * the filter, which the caller must free.
2404 */
2405char *owl_function_zuserfilt(const char *user)
2406{
2407  owl_filter *f;
2408  char *argbuff, *longuser, *esclonguser, *shortuser, *filtname;
2409
2410  /* stick the local realm on if it's not there */
2411  longuser=long_zuser(user);
2412  shortuser=short_zuser(user);
2413
2414  /* name for the filter */
2415  filtname=owl_sprintf("user-%s", shortuser);
2416
2417  /* if it already exists then go with it.  This lets users override */
2418  if (owl_global_get_filter(&g, filtname)) {
2419    return(owl_strdup(filtname));
2420  }
2421
2422  /* create the new-internal filter */
2423  f=owl_malloc(sizeof(owl_filter));
2424
2425  esclonguser = owl_text_quote(longuser, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2426
2427  argbuff=owl_sprintf("( type ^zephyr$ and filter personal and "
2428      "( ( direction ^in$ and sender ^%1$s$ ) or ( direction ^out$ and "
2429      "recipient ^%1$s$ ) ) ) or ( ( class ^login$ ) and ( sender ^%1$s$ ) )",
2430      esclonguser);
2431
2432  owl_filter_init_fromstring(f, filtname, argbuff);
2433
2434  /* add it to the global list */
2435  owl_global_add_filter(&g, f);
2436
2437  /* free stuff */
2438  owl_free(argbuff);
2439  owl_free(longuser);
2440  owl_free(esclonguser);
2441  owl_free(shortuser);
2442
2443  return(filtname);
2444}
2445
2446/* Create a filter for AIM IM messages to or from the specified
2447 * screenname.  The name of the filter will be 'aimuser-<user>'.  If a
2448 * filter already exists with this name, no new filter will be
2449 * created.  This allows the configuration to override this function.
2450 * Returns the name of the filter, which the caller must free.
2451 */
2452char *owl_function_aimuserfilt(const char *user)
2453{
2454  owl_filter *f;
2455  char *argbuff, *filtname;
2456  char *escuser;
2457
2458  /* name for the filter */
2459  filtname=owl_sprintf("aimuser-%s", user);
2460
2461  /* if it already exists then go with it.  This lets users override */
2462  if (owl_global_get_filter(&g, filtname)) {
2463    return(owl_strdup(filtname));
2464  }
2465
2466  /* create the new-internal filter */
2467  f=owl_malloc(sizeof(owl_filter));
2468
2469  escuser = owl_text_quote(user, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2470
2471  argbuff = owl_sprintf(
2472      "( type ^aim$ and ( ( sender ^%1$s$ and recipient ^%2$s$ ) or "
2473      "( sender ^%2$s$ and recipient ^%1$s$ ) ) )",
2474      escuser, owl_global_get_aim_screenname_for_filters(&g));
2475
2476  owl_filter_init_fromstring(f, filtname, argbuff);
2477
2478  /* add it to the global list */
2479  owl_global_add_filter(&g, f);
2480
2481  /* free stuff */
2482  owl_free(argbuff);
2483  owl_free(escuser);
2484
2485  return(filtname);
2486}
2487
2488char *owl_function_typefilt(const char *type)
2489{
2490  owl_filter *f;
2491  char *argbuff, *filtname, *esctype;
2492
2493  /* name for the filter */
2494  filtname=owl_sprintf("type-%s", type);
2495
2496  /* if it already exists then go with it.  This lets users override */
2497  if (owl_global_get_filter(&g, filtname)) {
2498    return filtname;
2499  }
2500
2501  /* create the new-internal filter */
2502  f=owl_malloc(sizeof(owl_filter));
2503
2504  esctype = owl_text_quote(type, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2505
2506  argbuff = owl_sprintf("type ^%s$", esctype);
2507
2508  owl_filter_init_fromstring(f, filtname, argbuff);
2509
2510  /* add it to the global list */
2511  owl_global_add_filter(&g, f);
2512
2513  /* free stuff */
2514  owl_free(argbuff);
2515  owl_free(esctype);
2516
2517  return filtname;
2518}
2519
2520/* If flag is 1, marks for deletion.  If flag is 0,
2521 * unmarks for deletion. */
2522void owl_function_delete_curview_msgs(int flag)
2523{
2524  const owl_view *v;
2525  int i, j;
2526
2527  v=owl_global_get_current_view(&g);
2528  j=owl_view_get_size(v);
2529  for (i=0; i<j; i++) {
2530    if (flag == 1) {
2531      owl_message_mark_delete(owl_view_get_element(v, i));
2532    } else if (flag == 0) {
2533      owl_message_unmark_delete(owl_view_get_element(v, i));
2534    }
2535  }
2536
2537  owl_function_makemsg("%i messages marked for %sdeletion", j, flag?"":"un");
2538
2539  owl_mainwin_redisplay(owl_global_get_mainwin(&g)); 
2540}
2541
2542/* Create a filter based on the current message.  Returns the name of
2543 * a filter or null.  The caller must free this name.
2544 *
2545 * if the curmsg is a personal zephyr return a filter name
2546 *    to the zephyr conversation with that user.
2547 * If the curmsg is a zephyr class message, instance foo, recip *,
2548 *    return a filter name to the class, inst.
2549 * If the curmsg is a zephyr class message and type==0 then
2550 *    return a filter name for just the class.
2551 * If the curmsg is a zephyr class message and type==1 then
2552 *    return a filter name for the class and instance.
2553 * If the curmsg is a personal AIM message returna  filter
2554 *    name to the AIM conversation with that user
2555 */
2556char *owl_function_smartfilter(int type)
2557{
2558  const owl_view *v;
2559  const owl_message *m;
2560  char *zperson, *filtname=NULL;
2561  const char *argv[1];
2562 
2563  v=owl_global_get_current_view(&g);
2564  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
2565
2566  if (!m || owl_view_get_size(v)==0) {
2567    owl_function_error("No message selected\n");
2568    return(NULL);
2569  }
2570
2571  /* very simple handling of admin messages for now */
2572  if (owl_message_is_type_admin(m)) {
2573    return(owl_function_typefilt("admin"));
2574  }
2575
2576  /* very simple handling of loopback messages for now */
2577  if (owl_message_is_type_loopback(m)) {
2578    return(owl_function_typefilt("loopback"));
2579  }
2580
2581  /* aim messages */
2582  if (owl_message_is_type_aim(m)) {
2583    if (owl_message_is_direction_in(m)) {
2584      filtname=owl_function_aimuserfilt(owl_message_get_sender(m));
2585    } else if (owl_message_is_direction_out(m)) {
2586      filtname=owl_function_aimuserfilt(owl_message_get_recipient(m));
2587    }
2588    return(filtname);
2589  }
2590
2591  /* narrow personal and login messages to the sender or recip as appropriate */
2592  if (owl_message_is_type_zephyr(m)) {
2593    if (owl_message_is_personal(m) || owl_message_is_loginout(m)) {
2594      if (owl_message_is_direction_in(m)) {
2595        zperson=short_zuser(owl_message_get_sender(m));
2596      } else {
2597        zperson=short_zuser(owl_message_get_recipient(m));
2598      }
2599      filtname=owl_function_zuserfilt(zperson);
2600      owl_free(zperson);
2601      return(filtname);
2602    }
2603
2604    /* narrow class MESSAGE, instance foo, recip * messages to class, inst */
2605    if (!strcasecmp(owl_message_get_class(m), "message")) {
2606      filtname=owl_function_classinstfilt(owl_message_get_class(m), owl_message_get_instance(m));
2607      return(filtname);
2608    }
2609
2610    /* otherwise narrow to the class */
2611    if (type==0) {
2612      filtname=owl_function_classinstfilt(owl_message_get_class(m), NULL);
2613    } else if (type==1) {
2614      filtname=owl_function_classinstfilt(owl_message_get_class(m), owl_message_get_instance(m));
2615    }
2616    return(filtname);
2617  }
2618
2619  /* pass it off to perl */
2620  if(type) {
2621    argv[0] = "-i";
2622  };
2623  return owl_perlconfig_message_call_method(m, "smartfilter", type ? 1 : 0, argv);
2624}
2625
2626void owl_function_smartzpunt(int type)
2627{
2628  /* Starts a zpunt command based on the current class,instance pair.
2629   * If type=0, uses just class.  If type=1, uses instance as well. */
2630  const owl_view *v;
2631  const owl_message *m;
2632  const char *cmdprefix, *mclass, *minst;
2633  char *cmd;
2634 
2635  v=owl_global_get_current_view(&g);
2636  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
2637
2638  if (!m || owl_view_get_size(v)==0) {
2639    owl_function_error("No message selected\n");
2640    return;
2641  }
2642
2643  /* for now we skip admin messages. */
2644  if (owl_message_is_type_admin(m)
2645      || owl_message_is_loginout(m)
2646      || !owl_message_is_type_zephyr(m)) {
2647    owl_function_error("smartzpunt doesn't support this message type.");
2648    return;
2649  }
2650
2651  mclass = owl_message_get_class(m);
2652  minst = owl_message_get_instance(m);
2653  if (!mclass || !*mclass || *mclass==' '
2654      || (!strcasecmp(mclass, "message") && !strcasecmp(minst, "personal"))
2655      || (type && (!minst || !*minst|| *minst==' '))) {
2656    owl_function_error("smartzpunt can't safely do this for <%s,%s>",
2657                         mclass, minst);
2658  } else {
2659    cmdprefix = "start-command zpunt ";
2660    cmd = owl_malloc(strlen(cmdprefix)+strlen(mclass)+strlen(minst)+10);
2661    strcpy(cmd, cmdprefix);
2662    strcat(cmd, owl_getquoting(mclass));
2663    strcat(cmd, mclass);
2664    strcat(cmd, owl_getquoting(mclass));
2665    if (type) {
2666      strcat(cmd, " ");
2667      strcat(cmd, owl_getquoting(minst));
2668      strcat(cmd, minst);
2669      strcat(cmd, owl_getquoting(minst));
2670    } else {
2671      strcat(cmd, " *");
2672    }
2673    owl_function_command(cmd);
2674    owl_free(cmd);
2675  }
2676}
2677
2678/* Set the color of the current view's filter to
2679 * be 'color'
2680 */
2681void owl_function_color_current_filter(const char *fgcolor, const char *bgcolor)
2682{
2683  const char *name;
2684
2685  name=owl_view_get_filtname(owl_global_get_current_view(&g));
2686  owl_function_color_filter(name, fgcolor, bgcolor);
2687}
2688
2689/* Set the color of the filter 'filter' to be 'color'.  If the color
2690 * name does not exist, return -1, if the filter does not exist or is
2691 * the "all" filter, return -2.  Return 0 on success
2692 */
2693int owl_function_color_filter(const char *filtname, const char *fgcolor, const char *bgcolor)
2694{
2695  owl_filter *f;
2696
2697  f=owl_global_get_filter(&g, filtname);
2698  if (!f) {
2699    owl_function_error("Unknown filter");
2700    return(-2);
2701  }
2702
2703  /* don't touch the all filter */
2704  if (!strcmp(filtname, "all")) {
2705    owl_function_error("You may not change the 'all' filter.");
2706    return(-2);
2707  }
2708
2709  if (owl_util_string_to_color(fgcolor)==OWL_COLOR_INVALID) {
2710    owl_function_error("No color named '%s' avilable.", fgcolor);
2711    return(-1);
2712  }
2713
2714
2715  if (bgcolor != NULL) {
2716    if (owl_util_string_to_color(bgcolor)==OWL_COLOR_INVALID) {
2717      owl_function_error("No color named '%s' avilable.", bgcolor);
2718      return(-1);
2719    }
2720    owl_filter_set_bgcolor(f, owl_util_string_to_color(bgcolor));
2721  }
2722  owl_filter_set_fgcolor(f, owl_util_string_to_color(fgcolor));
2723 
2724  owl_global_set_needrefresh(&g);
2725  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2726  return(0);
2727}
2728
2729void owl_function_show_colors(void)
2730{
2731  owl_fmtext fm;
2732  int i; 
2733 
2734  owl_fmtext_init_null(&fm);
2735  owl_fmtext_append_normal(&fm, "default: ");
2736  owl_fmtext_append_normal_color(&fm, "default\n", OWL_COLOR_DEFAULT, OWL_COLOR_DEFAULT);
2737
2738  owl_fmtext_append_normal(&fm,"red:      ");
2739  owl_fmtext_append_normal_color(&fm, "red\n", OWL_COLOR_RED, OWL_COLOR_DEFAULT);
2740
2741  owl_fmtext_append_normal(&fm,"green:    ");
2742  owl_fmtext_append_normal_color(&fm, "green\n", OWL_COLOR_GREEN, OWL_COLOR_DEFAULT);
2743
2744  owl_fmtext_append_normal(&fm,"yellow:   ");
2745  owl_fmtext_append_normal_color(&fm, "yellow\n", OWL_COLOR_YELLOW, OWL_COLOR_DEFAULT);
2746
2747  owl_fmtext_append_normal(&fm,"blue:     ");
2748  owl_fmtext_append_normal_color(&fm, "blue\n", OWL_COLOR_BLUE, OWL_COLOR_DEFAULT);
2749
2750  owl_fmtext_append_normal(&fm,"magenta:  ");
2751  owl_fmtext_append_normal_color(&fm, "magenta\n", OWL_COLOR_MAGENTA, OWL_COLOR_DEFAULT);
2752
2753  owl_fmtext_append_normal(&fm,"cyan:     ");
2754  owl_fmtext_append_normal_color(&fm, "cyan\n", OWL_COLOR_CYAN, OWL_COLOR_DEFAULT);
2755
2756  owl_fmtext_append_normal(&fm,"white:    ");
2757  owl_fmtext_append_normal_color(&fm, "white\n", OWL_COLOR_WHITE, OWL_COLOR_DEFAULT);
2758
2759  for(i = 8; i < COLORS; ++i) {
2760    char* str1 = owl_sprintf("%4i:     ",i);
2761    char* str2 = owl_sprintf("%i\n",i);
2762    owl_fmtext_append_normal(&fm,str1);
2763    owl_fmtext_append_normal_color(&fm, str2, i, OWL_COLOR_DEFAULT);
2764    owl_free(str1);
2765     owl_free(str2);
2766  }
2767 
2768  owl_function_popless_fmtext(&fm);
2769  owl_fmtext_free(&fm);
2770}
2771
2772/* add the given class, inst, recip to the punt list for filtering.
2773 *   if direction==0 then punt
2774 *   if direction==1 then unpunt
2775 */
2776void owl_function_zpunt(const char *class, const char *inst, const char *recip, int direction)
2777{
2778  char *puntexpr, *classexpr, *instexpr, *recipexpr;
2779  char *quoted;
2780
2781  if (!strcmp(class, "*")) {
2782    classexpr = owl_sprintf("class .*");
2783  } else {
2784    quoted=owl_text_quote(class, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2785    owl_text_tr(quoted, ' ', '.');
2786    owl_text_tr(quoted, '\'', '.');
2787    owl_text_tr(quoted, '"', '.');
2788    classexpr = owl_sprintf("class ^(un)*%s(\\.d)*$", quoted);
2789    owl_free(quoted);
2790  }
2791  if (!strcmp(inst, "*")) {
2792    instexpr = owl_sprintf(" and instance .*");
2793  } else {
2794    quoted=owl_text_quote(inst, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2795    owl_text_tr(quoted, ' ', '.');
2796    owl_text_tr(quoted, '\'', '.');
2797    owl_text_tr(quoted, '"', '.');
2798    instexpr = owl_sprintf(" and instance ^(un)*%s(\\.d)*$", quoted);
2799    owl_free(quoted);
2800  }
2801  if (!strcmp(recip, "*")) {
2802    recipexpr = owl_sprintf("");
2803  } else {
2804    if(!strcmp(recip, "%me%")) {
2805      recip = owl_zephyr_get_sender();
2806    }
2807    quoted=owl_text_quote(recip, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2808    owl_text_tr(quoted, ' ', '.');
2809    owl_text_tr(quoted, '\'', '.');
2810    owl_text_tr(quoted, '"', '.');
2811    recipexpr = owl_sprintf(" and recipient ^%s$", quoted);
2812    owl_free(quoted);
2813  }
2814
2815  puntexpr = owl_sprintf("%s %s %s", classexpr, instexpr, recipexpr);
2816  owl_function_punt(puntexpr, direction);
2817  owl_free(puntexpr);
2818  owl_free(classexpr);
2819  owl_free(instexpr);
2820  owl_free(recipexpr);
2821}
2822
2823void owl_function_punt(const char *filter, int direction)
2824{
2825  owl_filter *f;
2826  owl_list *fl;
2827  int ret, i, j;
2828  fl=owl_global_get_puntlist(&g);
2829
2830  /* first, create the filter */
2831  f=owl_malloc(sizeof(owl_filter));
2832
2833  owl_function_debugmsg("About to filter %s", filter);
2834  ret=owl_filter_init_fromstring(f, "punt-filter", filter);
2835  if (ret) {
2836    owl_function_error("Error creating filter for zpunt");
2837    owl_filter_free(f);
2838    owl_free(f);
2839    return;
2840  }
2841
2842  /* Check for an identical filter */
2843  j=owl_list_get_size(fl);
2844  for (i=0; i<j; i++) {
2845    if (owl_filter_equiv(f, owl_list_get_element(fl, i))) {
2846      owl_function_debugmsg("found an equivalent punt filter");
2847      /* if we're punting, then just silently bow out on this duplicate */
2848      if (direction==0) {
2849        owl_filter_free(f);
2850        owl_free(f);
2851        return;
2852      }
2853
2854      /* if we're unpunting, then remove this filter from the puntlist */
2855      if (direction==1) {
2856        owl_filter_free(owl_list_get_element(fl, i));
2857        owl_list_remove_element(fl, i);
2858        owl_filter_free(f);
2859        owl_free(f);
2860        return;
2861      }
2862    }
2863  }
2864
2865  owl_function_debugmsg("punting");
2866  /* If we're punting, add the filter to the global punt list */
2867  if (direction==0) {
2868    owl_list_append_element(fl, f);
2869  }
2870}
2871
2872void owl_function_activate_keymap(const char *keymap)
2873{
2874  if (!owl_keyhandler_activate(owl_global_get_keyhandler(&g), keymap)) {
2875    owl_function_error("Unable to activate keymap '%s'", keymap);
2876  }
2877}
2878
2879void owl_function_show_keymaps(void)
2880{
2881  owl_list l;
2882  owl_fmtext fm;
2883  const owl_keymap *km;
2884  const owl_keyhandler *kh;
2885  int i, numkm;
2886  const char *kmname;
2887
2888  kh = owl_global_get_keyhandler(&g);
2889  owl_fmtext_init_null(&fm);
2890  owl_fmtext_append_bold(&fm, "Keymaps:   ");
2891  owl_fmtext_append_normal(&fm, "(use 'show keymap <name>' for details)\n");
2892  owl_keyhandler_get_keymap_names(kh, &l);
2893  owl_fmtext_append_list(&fm, &l, "\n", owl_function_keymap_summary);
2894  owl_fmtext_append_normal(&fm, "\n");
2895
2896  numkm = owl_list_get_size(&l);
2897  for (i=0; i<numkm; i++) {
2898    kmname = owl_list_get_element(&l, i);
2899    km = owl_keyhandler_get_keymap(kh, kmname);
2900    owl_fmtext_append_bold(&fm, "\n\n----------------------------------------------------------------------------------------------------\n\n");
2901    owl_keymap_get_details(km, &fm);   
2902  }
2903  owl_fmtext_append_normal(&fm, "\n");
2904 
2905  owl_function_popless_fmtext(&fm);
2906  owl_keyhandler_keymap_namelist_free(&l);
2907  owl_fmtext_free(&fm);
2908}
2909
2910char *owl_function_keymap_summary(const char *name)
2911{
2912  const owl_keymap *km
2913    = owl_keyhandler_get_keymap(owl_global_get_keyhandler(&g), name);
2914  if (km) return owl_keymap_summary(km);
2915  else return(NULL);
2916}
2917
2918/* TODO: implement for real */
2919void owl_function_show_keymap(const char *name)
2920{
2921  owl_fmtext fm;
2922  const owl_keymap *km;
2923
2924  owl_fmtext_init_null(&fm);
2925  km = owl_keyhandler_get_keymap(owl_global_get_keyhandler(&g), name);
2926  if (km) {
2927    owl_keymap_get_details(km, &fm);
2928  } else {
2929    owl_fmtext_append_normal(&fm, "No such keymap...\n");
2930  } 
2931  owl_function_popless_fmtext(&fm);
2932  owl_fmtext_free(&fm);
2933}
2934
2935void owl_function_help_for_command(const char *cmdname)
2936{
2937  owl_fmtext fm;
2938
2939  owl_fmtext_init_null(&fm);
2940  owl_cmd_get_help(owl_global_get_cmddict(&g), cmdname, &fm);
2941  owl_function_popless_fmtext(&fm); 
2942  owl_fmtext_free(&fm);
2943}
2944
2945void owl_function_search_start(const char *string, int direction)
2946{
2947  /* direction is OWL_DIRECTION_DOWNWARDS or OWL_DIRECTION_UPWARDS or
2948   * OWL_DIRECTION_NONE */
2949  owl_regex re;
2950
2951  if (string && owl_regex_create_quoted(&re, string) == 0) {
2952    owl_global_set_search_re(&g, &re);
2953    owl_regex_free(&re);
2954  } else {
2955    owl_global_set_search_re(&g, NULL);
2956  }
2957
2958  if (direction == OWL_DIRECTION_NONE)
2959    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2960  else
2961    owl_function_search_helper(0, direction);
2962}
2963
2964void owl_function_search_continue(int direction)
2965{
2966  /* direction is OWL_DIRECTION_DOWNWARDS or OWL_DIRECTION_UPWARDS */
2967  owl_function_search_helper(1, direction);
2968}
2969
2970void owl_function_search_helper(int mode, int direction)
2971{
2972  /* move to a message that contains the string.  If direction is
2973   * OWL_DIRECTION_DOWNWARDS then search fowards, if direction is
2974   * OWL_DIRECTION_UPWARDS then search backwards.
2975   *
2976   * If mode==0 then it will stay on the current message if it
2977   * contains the string.
2978   */
2979
2980  const owl_view *v;
2981  int viewsize, i, curmsg, start;
2982  owl_message *m;
2983
2984  v=owl_global_get_current_view(&g);
2985  viewsize=owl_view_get_size(v);
2986  curmsg=owl_global_get_curmsg(&g);
2987 
2988  if (viewsize==0) {
2989    owl_function_error("No messages present");
2990    return;
2991  }
2992
2993  if (mode==0) {
2994    start=curmsg;
2995  } else if (direction==OWL_DIRECTION_DOWNWARDS) {
2996    start=curmsg+1;
2997  } else {
2998    start=curmsg-1;
2999  }
3000
3001  /* bounds check */
3002  if (start>=viewsize || start<0) {
3003    owl_function_error("No further matches found");
3004    return;
3005  }
3006
3007  for (i=start; i<viewsize && i>=0;) {
3008    m=owl_view_get_element(v, i);
3009    if (owl_message_search(m, owl_global_get_search_re(&g))) {
3010      owl_global_set_curmsg(&g, i);
3011      owl_function_calculate_topmsg(direction);
3012      owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3013      if (direction==OWL_DIRECTION_DOWNWARDS) {
3014        owl_global_set_direction_downwards(&g);
3015      } else {
3016        owl_global_set_direction_upwards(&g);
3017      }
3018      return;
3019    }
3020    if (direction==OWL_DIRECTION_DOWNWARDS) {
3021      i++;
3022    } else {
3023      i--;
3024    }
3025    owl_function_mask_sigint(NULL);
3026    if(owl_global_is_interrupted(&g)) {
3027      owl_global_unset_interrupted(&g);
3028      owl_function_unmask_sigint(NULL);
3029      owl_function_makemsg("Search interrupted!");
3030      owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3031      return;
3032    }
3033    owl_function_unmask_sigint(NULL);
3034  }
3035  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3036  owl_function_error("No matches found");
3037}
3038
3039/* strips formatting from ztext and returns the unformatted text.
3040 * caller is responsible for freeing. */
3041char *owl_function_ztext_stylestrip(const char *zt)
3042{
3043  owl_fmtext fm;
3044  char *plaintext;
3045
3046  owl_fmtext_init_null(&fm);
3047  owl_fmtext_append_ztext(&fm, zt);
3048  plaintext = owl_fmtext_print_plain(&fm);
3049  owl_fmtext_free(&fm);
3050  return(plaintext);
3051}
3052
3053/* Popup a buddylisting.  If filename is NULL use the default .anyone */
3054void owl_function_buddylist(int aim, int zephyr, const char *filename)
3055{
3056  int i, j, idle;
3057  int interrupted = 0;
3058  owl_fmtext fm;
3059  const owl_buddylist *bl;
3060  const owl_buddy *b;
3061  char *timestr;
3062#ifdef HAVE_LIBZEPHYR
3063  int x;
3064  owl_list anyone;
3065  const char *user;
3066  char *tmp;
3067  ZLocations_t location[200];
3068  int numlocs, ret;
3069#endif
3070
3071  owl_fmtext_init_null(&fm);
3072
3073  /* AIM first */
3074  if (aim && owl_global_is_aimloggedin(&g)) {
3075    bl=owl_global_get_buddylist(&g);
3076
3077    owl_fmtext_append_bold(&fm, "AIM users logged in:\n");
3078    /* we're assuming AIM for now */
3079    j=owl_buddylist_get_size(bl);
3080    for (i=0; i<j; i++) {
3081      b=owl_buddylist_get_buddy_n(bl, i);
3082      idle=owl_buddy_get_idle_time(b);
3083      if (idle!=0) {
3084        timestr=owl_util_minutes_to_timestr(idle);
3085      } else {
3086        timestr=owl_strdup("");
3087      }
3088      owl_fmtext_appendf_normal(&fm, "  %-20.20s %-12.12s\n", owl_buddy_get_name(b), timestr);
3089      owl_free(timestr);
3090    }
3091  }
3092
3093#ifdef HAVE_LIBZEPHYR
3094  if (zephyr) {
3095    if(!owl_global_is_havezephyr(&g)) {
3096      owl_function_error("Zephyr currently not available.");
3097    } else {
3098      owl_fmtext_append_bold(&fm, "Zephyr users logged in:\n");
3099      owl_list_create(&anyone);
3100      ret=owl_zephyr_get_anyone_list(&anyone, filename);
3101      if (ret) {
3102        if (errno == ENOENT) {
3103          owl_fmtext_append_normal(&fm, " You have not added any zephyr buddies.  Use the\n");
3104          owl_fmtext_append_normal(&fm, " command ':addbuddy zephyr ");
3105          owl_fmtext_append_bold(  &fm, "<username>");
3106          owl_fmtext_append_normal(&fm, "'.\n");
3107        } else {
3108          owl_fmtext_append_normal(&fm, " Could not read zephyr buddies from the .anyone file.\n");
3109        }
3110      } else {
3111        j=owl_list_get_size(&anyone);
3112        for (i=0; i<j; i++) {
3113          user=owl_list_get_element(&anyone, i);
3114          ret=ZLocateUser(zstr(user), &numlocs, ZAUTH);
3115
3116          owl_function_mask_sigint(NULL);
3117          if(owl_global_is_interrupted(&g)) {
3118            interrupted = 1;
3119            owl_global_unset_interrupted(&g);
3120            owl_function_unmask_sigint(NULL);
3121            owl_function_makemsg("Interrupted!");
3122            break;
3123          }
3124
3125          owl_function_unmask_sigint(NULL);
3126
3127          if (ret!=ZERR_NONE) {
3128            owl_function_error("Error getting location for %s", user);
3129            continue;
3130          }
3131
3132          numlocs=200;
3133          ret=ZGetLocations(location, &numlocs);
3134          if (ret==0) {
3135            for (x=0; x<numlocs; x++) {
3136              tmp=short_zuser(user);
3137              owl_fmtext_appendf_normal(&fm, "  %-10.10s %-24.24s %-12.12s  %20.20s\n",
3138                                        tmp,
3139                                        location[x].host,
3140                                        location[x].tty,
3141                                        location[x].time);
3142              owl_free(tmp);
3143            }
3144            if (numlocs>=200) {
3145              owl_fmtext_append_normal(&fm, "  Too many locations found for this user, truncating.\n");
3146            }
3147          }
3148        }
3149      }
3150      owl_list_free_all(&anyone, owl_free);
3151    }
3152  }
3153#endif
3154
3155  if(aim && zephyr) {
3156      if(owl_perlconfig_is_function("BarnOwl::Hooks::_get_blist")) {
3157          char * perlblist = owl_perlconfig_execute("BarnOwl::Hooks::_get_blist()");
3158          if(perlblist) {
3159              owl_fmtext_append_ztext(&fm, perlblist);
3160              owl_free(perlblist);
3161          }
3162      }
3163  }
3164
3165  if(!interrupted) {
3166    owl_function_popless_fmtext(&fm);
3167  }
3168  owl_fmtext_free(&fm);
3169}
3170
3171/* Dump messages in the current view to the file 'filename'. */
3172void owl_function_dump(const char *filename) 
3173{
3174  int i, j;
3175  owl_message *m;
3176  const owl_view *v;
3177  FILE *file;
3178  char *plaintext;
3179
3180  v=owl_global_get_current_view(&g);
3181
3182  /* in the future make it ask yes/no */
3183  /*
3184  ret=stat(filename, &sbuf);
3185  if (!ret) {
3186    ret=owl_function_askyesno("File exists, continue? [Y/n]");
3187    if (!ret) return;
3188  }
3189  */
3190
3191  file=fopen(filename, "w");
3192  if (!file) {
3193    owl_function_error("Error opening file");
3194    return;
3195  }
3196
3197  j=owl_view_get_size(v);
3198  for (i=0; i<j; i++) {
3199    m=owl_view_get_element(v, i);
3200    plaintext = owl_strip_format_chars(owl_message_get_text(m));
3201    if (plaintext) {
3202      fputs(plaintext, file);
3203      owl_free(plaintext);
3204    }
3205  }
3206  fclose(file);
3207  owl_function_makemsg("Messages dumped to %s", filename);
3208}
3209
3210void owl_function_do_newmsgproc(void)
3211{
3212  if (owl_global_get_newmsgproc(&g) && strcmp(owl_global_get_newmsgproc(&g), "")) {
3213    /* if there's a process out there, we need to check on it */
3214    if (owl_global_get_newmsgproc_pid(&g)) {
3215      owl_function_debugmsg("Checking on newmsgproc pid==%i", owl_global_get_newmsgproc_pid(&g));
3216      owl_function_debugmsg("Waitpid return is %i", waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG));
3217      waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG);
3218      if (waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG)==-1) {
3219        /* it exited */
3220        owl_global_set_newmsgproc_pid(&g, 0);
3221        owl_function_debugmsg("newmsgproc exited");
3222      } else {
3223        owl_function_debugmsg("newmsgproc did not exit");
3224      }
3225    }
3226   
3227    /* if it exited, fork & exec a new one */
3228    if (owl_global_get_newmsgproc_pid(&g)==0) {
3229      pid_t i;
3230      int myargc;
3231      i=fork();
3232      if (i) {
3233        /* parent set the child's pid */
3234        owl_global_set_newmsgproc_pid(&g, i);
3235        owl_function_debugmsg("I'm the parent and I started a new newmsgproc with pid %i", i);
3236      } else {
3237        /* child exec's the program */
3238        char **parsed;
3239        parsed=owl_parseline(owl_global_get_newmsgproc(&g), &myargc);
3240        if (myargc < 0) {
3241          owl_function_debugmsg("Could not parse newmsgproc '%s': unbalanced quotes?", owl_global_get_newmsgproc(&g));
3242        }
3243        if (myargc <= 0) {
3244          _exit(127);
3245        }
3246        parsed=owl_realloc(parsed, sizeof(*parsed) * (myargc+1));
3247        parsed[myargc] = NULL;
3248       
3249        owl_function_debugmsg("About to exec \"%s\" with %d arguments", parsed[0], myargc);
3250       
3251        execvp(parsed[0], parsed);
3252       
3253       
3254        /* was there an error exec'ing? */
3255        owl_function_debugmsg("Cannot run newmsgproc '%s': cannot exec '%s': %s", 
3256                              owl_global_get_newmsgproc(&g), parsed[0], strerror(errno));
3257        _exit(127);
3258      }
3259    }
3260  }
3261}
3262
3263/* print the xterm escape sequence to raise the window */
3264void owl_function_xterm_raise(void)
3265{
3266  printf("\033[5t");
3267}
3268
3269/* print the xterm escape sequence to deiconify the window */
3270void owl_function_xterm_deiconify(void)
3271{
3272  printf("\033[1t");
3273}
3274
3275/* Add the specified command to the startup file.  Eventually this
3276 * should be clever, and rewriting settings that will obviosly
3277 * override earlier settings with 'set' 'bindkey' and 'alias'
3278 * commands.  For now though we just remove any line that would
3279 * duplicate this one and then append this line to the end of
3280 * startupfile.
3281 */
3282void owl_function_addstartup(const char *buff)
3283{
3284  FILE *file;
3285  const char *filename;
3286
3287  filename=owl_global_get_startupfile(&g);
3288  file=fopen(filename, "a");
3289  if (!file) {
3290    owl_function_error("Error opening startupfile for new command");
3291    return;
3292  }
3293
3294  /* delete earlier copies */
3295  owl_util_file_deleteline(filename, buff, 1);
3296
3297  /* add this line */
3298  fprintf(file, "%s\n", buff);
3299
3300  fclose(file);
3301}
3302
3303/* Remove the specified command from the startup file. */
3304void owl_function_delstartup(const char *buff)
3305{
3306  const char *filename;
3307  filename=owl_global_get_startupfile(&g);
3308  owl_util_file_deleteline(filename, buff, 1);
3309}
3310
3311/* Execute owl commands from the given filename.  If the filename
3312 * is NULL, use the default owl startup commands file.
3313 */
3314void owl_function_source(const char *filename)
3315{
3316  char *path;
3317  FILE *file;
3318  char *s = NULL;
3319  int fail_silent = 0;
3320
3321  if (!filename) {
3322    fail_silent = 1;
3323    path = owl_strdup(owl_global_get_startupfile(&g));
3324  } else {
3325    path = owl_util_makepath(filename);
3326  }
3327  file = fopen(path, "r");
3328  owl_free(path);
3329  if (!file) {
3330    if (!fail_silent) {
3331      owl_function_error("Error opening file: %s", filename);
3332    }
3333    return;
3334  }
3335  while (owl_getline_chomp(&s, file)) {
3336    if (s[0] == '\0' || s[0] == '#')
3337      continue;
3338    owl_function_command(s);
3339  }
3340
3341  owl_free(s);
3342  fclose(file);
3343}
3344
3345void owl_function_change_style(owl_view *v, const char *stylename)
3346{
3347  const owl_style *s;
3348
3349  s=owl_global_get_style_by_name(&g, stylename);
3350  if (!s) {
3351    owl_function_error("No style named %s", stylename);
3352    return;
3353  }
3354  owl_view_set_style(v, s);
3355  owl_messagelist_invalidate_formats(owl_global_get_msglist(&g));
3356  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
3357  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3358}
3359
3360void owl_function_toggleoneline(void)
3361{
3362  owl_view *v;
3363  const owl_style *s;
3364
3365  v=owl_global_get_current_view(&g);
3366  s=owl_view_get_style(v);
3367
3368  if (!owl_style_matches_name(s, "oneline")) {
3369    owl_function_change_style(v, "oneline");
3370  } else {
3371    owl_function_change_style(v, owl_global_get_default_style(&g));
3372  }
3373
3374  owl_messagelist_invalidate_formats(owl_global_get_msglist(&g));
3375  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
3376  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3377}
3378
3379void owl_function_error(const char *fmt, ...)
3380{
3381  static int in_error = 0;
3382  va_list ap;
3383  char *buff;
3384  const char *nl;
3385
3386  if (++in_error > 2) {
3387    /* More than two nested errors, bail immediately. */
3388    in_error--;
3389    return;
3390  }
3391
3392  va_start(ap, fmt);
3393  buff = g_strdup_vprintf(fmt, ap);
3394  va_end(ap);
3395
3396  owl_function_debugmsg("ERROR: %s", buff);
3397  owl_function_log_err(buff);
3398
3399  nl = strchr(buff, '\n');
3400
3401  /*
3402    Showing admin messages triggers a lot of code. If we have a
3403    recursive error call, that's the most likely candidate, so
3404    suppress the call in that case, to try to avoid infinite looping.
3405  */
3406
3407  if(nl && *(nl + 1) && in_error == 1) {
3408    /* Multiline error */
3409    owl_function_adminmsg("ERROR", buff);
3410  } else {
3411    owl_function_makemsg("[Error] %s", buff);
3412  }
3413
3414  owl_free(buff);
3415
3416  in_error--;
3417}
3418
3419void owl_function_log_err(const char *string)
3420{
3421  char *date;
3422  time_t now;
3423  char *buff;
3424
3425  now=time(NULL);
3426  date=owl_strdup(ctime(&now));
3427  date[strlen(date)-1]='\0';
3428
3429  buff = owl_sprintf("%s %s", date, string);
3430
3431  owl_errqueue_append_err(owl_global_get_errqueue(&g), buff);
3432
3433  owl_free(buff);
3434  owl_free(date);
3435}
3436
3437void owl_function_showerrs(void)
3438{
3439  owl_fmtext fm;
3440
3441  owl_fmtext_init_null(&fm);
3442  owl_fmtext_append_normal(&fm, "Errors:\n\n");
3443  owl_errqueue_to_fmtext(owl_global_get_errqueue(&g), &fm);
3444  owl_function_popless_fmtext(&fm);
3445}
3446
3447void owl_function_makemsg(const char *fmt, ...)
3448{
3449  va_list ap;
3450  char buff[2048];
3451
3452  if (!owl_global_get_curs_msgwin(&g)) return;
3453
3454  va_start(ap, fmt);
3455  werase(owl_global_get_curs_msgwin(&g));
3456 
3457  vsnprintf(buff, 2048, fmt, ap);
3458  owl_function_debugmsg("makemsg: %s", buff);
3459  waddstr(owl_global_get_curs_msgwin(&g), buff); 
3460  wnoutrefresh(owl_global_get_curs_msgwin(&g));
3461  owl_global_set_needrefresh(&g);
3462  va_end(ap);
3463}
3464
3465/* get locations for everyone in .anyone.  If 'notify' is '1' then
3466 * send a pseudo login or logout message for everyone not in sync with
3467 * the global zephyr buddy list.  The list is updated regardless of
3468 * the status of 'notify'.
3469 */
3470void owl_function_zephyr_buddy_check(int notify)
3471{
3472#ifdef HAVE_LIBZEPHYR
3473  int i, j;
3474  owl_list anyone;
3475  owl_message *m;
3476  owl_zbuddylist *zbl;
3477  const char *user;
3478  ZLocations_t location[200];
3479  int numlocs, ret;
3480
3481  if (!owl_global_is_havezephyr(&g)) return;
3482
3483  zbl=owl_global_get_zephyr_buddylist(&g);
3484
3485  owl_list_create(&anyone);
3486  ret=owl_zephyr_get_anyone_list(&anyone, NULL);
3487
3488  j=owl_list_get_size(&anyone);
3489  for (i=0; i<j; i++) {
3490    user=owl_list_get_element(&anyone, i);
3491    ret=ZLocateUser(zstr(user), &numlocs, ZAUTH);
3492    if (ret!=ZERR_NONE) {
3493      owl_function_error("Error getting location for %s", user);
3494      continue;
3495    }
3496    numlocs=200;
3497    ret=ZGetLocations(location, &numlocs);
3498    if (ret==0) {
3499      if ((numlocs>0) && !owl_zbuddylist_contains_user(zbl, user)) {
3500        /* Send a PSEUDO LOGIN! */
3501        if (notify) {
3502          m=owl_malloc(sizeof(owl_message));
3503          owl_message_create_pseudo_zlogin(m, 0, user, location[0].host, location[0].time, location[0].tty);
3504          owl_global_messagequeue_addmsg(&g, m);
3505        }
3506        owl_zbuddylist_adduser(zbl, user);
3507        owl_function_debugmsg("owl_function_zephyr_buddy_check: login for %s ", user);
3508      } else if ((numlocs==0) && owl_zbuddylist_contains_user(zbl, user)) {
3509        /* I don't think this ever happens (if there are 0 locations we should get an error from
3510         * ZGetLocations)
3511         */
3512        owl_function_error("owl_function_zephyr_buddy_check: exceptional case logout for %s ",user);
3513      }
3514    } else if ((ret==ZERR_NOLOCATIONS) && owl_zbuddylist_contains_user(zbl, user)) {
3515      /* Send a PSEUDO LOGOUT! */
3516      if (notify) {
3517        m=owl_malloc(sizeof(owl_message));
3518        owl_message_create_pseudo_zlogin(m, 1, user, "", "", "");
3519        owl_global_messagequeue_addmsg(&g, m);
3520      }
3521      owl_zbuddylist_deluser(zbl, user);
3522      owl_function_debugmsg("owl_function_zephyr_buddy_check: logout for %s ",user);
3523    }
3524  }
3525
3526  owl_list_free_all(&anyone, owl_free);
3527#endif
3528}
3529
3530void owl_function_aimsearch_results(const char *email, owl_list *namelist)
3531{
3532  owl_fmtext fm;
3533  int i, j;
3534
3535  owl_fmtext_init_null(&fm);
3536  owl_fmtext_append_normal(&fm, "AIM screennames associated with ");
3537  owl_fmtext_append_normal(&fm, email);
3538  owl_fmtext_append_normal(&fm, ":\n");
3539
3540  j=owl_list_get_size(namelist);
3541  for (i=0; i<j; i++) {
3542    owl_fmtext_append_normal(&fm, "  ");
3543    owl_fmtext_append_normal(&fm, owl_list_get_element(namelist, i));
3544    owl_fmtext_append_normal(&fm, "\n");
3545  }
3546
3547  owl_function_popless_fmtext(&fm);
3548  owl_fmtext_free(&fm);
3549}
3550
3551int owl_function_get_color_count(void)
3552{
3553     return COLORS;
3554}
3555
3556void owl_function_mask_sigint(sigset_t *oldmask) {
3557  sigset_t intr;
3558
3559  sigemptyset(&intr);
3560  sigaddset(&intr, SIGINT);
3561  sigprocmask(SIG_BLOCK, &intr, oldmask);
3562}
3563
3564void owl_function_unmask_sigint(sigset_t *oldmask) {
3565  sigset_t intr;
3566
3567  sigemptyset(&intr);
3568  sigaddset(&intr, SIGINT);
3569  sigprocmask(SIG_UNBLOCK, &intr, oldmask);
3570}
3571
3572void _owl_function_mark_message(const owl_message *m)
3573{
3574  if (m)
3575    owl_global_set_markedmsgid(&g, owl_message_get_id(m));
3576}
3577
3578void owl_function_mark_message(void)
3579{
3580  const owl_message *m;
3581  const owl_view *v;
3582
3583  v=owl_global_get_current_view(&g);
3584
3585  /* bail if there's no current message */
3586  if (owl_view_get_size(v) < 1) {
3587    owl_function_error("No messages to mark");
3588    return;
3589  }
3590
3591  /* mark the message */
3592  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
3593  _owl_function_mark_message(m);
3594  owl_function_makemsg("Mark set");
3595}
3596
3597void owl_function_swap_cur_marked(void)
3598{
3599  int marked_id;
3600  const owl_message *m;
3601  const owl_view *v;
3602
3603  marked_id=owl_global_get_markedmsgid(&g);
3604  if (marked_id == -1) {
3605    owl_function_error("Mark not set.");
3606    return;
3607  }
3608
3609  v=owl_global_get_current_view(&g);
3610  /* bail if there's no current message */
3611  if (owl_view_get_size(v) < 1) {
3612    return;
3613  }
3614
3615  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
3616  _owl_function_mark_message(m);
3617  owl_global_set_curmsg(&g, owl_view_get_nearest_to_msgid(v, marked_id));
3618  owl_function_calculate_topmsg(OWL_DIRECTION_NONE);
3619  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3620  owl_global_set_direction_downwards(&g);
3621}
Note: See TracBrowser for help on using the repository browser.