source: functions.c @ 94ef58c

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