source: functions.c @ 7483942

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