source: perlwrap.pm @ d73e3af

release-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since d73e3af was dfaa47d, checked in by Geoffrey Thomas <geofft@mit.edu>, 15 years ago
Display context for personals, so as to make <message,*,%me> usable. Signed-off-by: Geoffrey Thomas <geofft@mit.edu>
  • Property mode set to 100644
File size: 31.9 KB
RevLine 
[f1e629d]1# $Id$
2#
3# This is all linked into the binary and evaluated when perl starts up...
4#
5#####################################################################
6#####################################################################
[b6c067a]7# XXX NOTE: This file is sourced before almost any barnowl
8# architecture is loaded. This means, for example, that it cannot
[0337203]9# execute any owl commands. Any code that needs to do so should live
10# in BarnOwl::Hooks::_startup
[f1e629d]11
[c681337]12use strict;
13use warnings;
14
[8203afd]15package BarnOwl;
[f1e629d]16
[74fc22a]17=head1 NAME
18
19BarnOwl
20
21=head1 DESCRIPTION
22
23The BarnOwl module contains the core of BarnOwl's perl
24bindings. Source in this module is also run at startup to bootstrap
25barnowl by defining things like the default style.
26
27=for NOTE
28These following functions are defined in perlglue.xs. Keep the
29documentation here in sync with the user-visible commands defined
30there!
31
32=head2 command STRING
33
34Executes a BarnOwl command in the same manner as if the user had
35executed it at the BarnOwl command prompt. If the command returns a
36value, return it as a string, otherwise return undef.
37
38=head2 getcurmsg
39
40Returns the current message as a C<BarnOwl::Message> subclass, or
41undef if there is no message selected
42
43=head2 getnumcols
44
45Returns the width of the display window BarnOwl is currently using
46
47=head2 getidletime
48
49Returns the length of time since the user has pressed a key, in
50seconds.
51
52=head2 zephyr_getrealm
53
54Returns the zephyr realm barnowl is running in
55
56=head2 zephyr_getsender
57
58Returns the fully-qualified name of the zephyr sender barnowl is
59running as, e.g. C<nelhage@ATHENA.MIT.EDU>
60
61=head2 zephyr_zwrite COMMAND MESSAGE
62
63Sends a zephyr programmatically. C<COMMAND> should be a C<zwrite>
64command line, and C<MESSAGE> is the zephyr body to send.
65
66=head2 ztext_stylestrip STRING
67
68Strips zephyr formatting from a string and returns the result
69
[acb13bb]70=head2 zephyr_getsubs
71
72Returns the list of subscription triples <class,instance,recipient>,
73separated by newlines.
74
[74fc22a]75=head2 queue_message MESSAGE
76
77Enqueue a message in the BarnOwl message list, logging it and
78processing it appropriately. C<MESSAGE> should be an instance of
79BarnOwl::Message or a subclass.
80
81=head2 admin_message HEADER BODY
82
83Display a BarnOwl B<Admin> message, with the given header and body.
84
85=head2 start_question PROMPT CALLBACK
86
87Displays C<PROMPT> on the screen and lets the user enter a line of
88text, and calls C<CALLBACK>, which must be a perl subroutine
89reference, with the text the user entered
90
91=head2 start_password PROMPT CALLBACK
92
93Like C<start_question>, but echoes the user's input as C<*>s when they
94input.
95
[9815e2e]96=head2 start_edit_win PROMPT CALLBACK
[74fc22a]97
98Like C<start_question>, but displays C<PROMPT> on a line of its own
99and opens the editwin. If the user cancels the edit win, C<CALLBACK>
100is not invoked.
101
102=head2 get_data_dir
103
104Returns the BarnOwl system data directory, where system libraries and
105modules are stored
106
107=head2 get_config_dir
108
109Returns the BarnOwl user configuration directory, where user modules
110and configuration are stored (by default, C<$HOME/.owl>)
111
112=head2 popless_text TEXT
113
114Show a popup window containing the given C<TEXT>
115
116=head2 popless_ztext TEXT
117
118Show a popup window containing the provided zephyr-formatted C<TEXT>
119
120=head2 error STRING
121
122Reports an error and log it in `show errors'. Note that in any
123callback or hook called in perl code from BarnOwl, a C<die> will be
124caught and passed to C<error>.
125
126=head2 getnumcolors
127
128Returns the number of colors this BarnOwl is capable of displaying
129
[b07d8c8]130=head2 add_dispatch FD CALLBACK
131
132Adds a file descriptor to C<BarnOwl>'s internal C<select()>
133loop. C<CALLBACK> will be invoked whenever data is available to be
134read from C<FD>.
135
136=head2 remove_dispatch FD
137
138Remove a file descriptor previously registered via C<add_dispatch>
139
[0eaa488]140=head2 create_style NAME OBJECT
141
142Creates a new barnowl style with the given NAME defined by the given
143object. The object must have a C<description> method which returns a
144string description of the style, and a and C<format_message> method
145which accepts a C<BarnOwl::Message> object and returns a string that
146is the result of formatting the message for display.
147
[74fc22a]148=cut
149
150
[8862725]151BEGIN {
[f1e629d]152# bootstrap in C bindings and glue
[8203afd]153    *owl:: = \*BarnOwl::;
154    bootstrap BarnOwl 1.2;
[8862725]155};
156
[b363d83]157use lib(get_data_dir() . "/lib");
158use lib(get_config_dir() . "/lib");
[8862725]159
[b363d83]160# perlconfig.c will set this to the value of the -c command-line
161# switch, if present.
[00f9a7d]162our $configfile;
163
[2e3b9c2]164if(!$configfile && -f $ENV{HOME} . "/.barnowlconf") {
165    $configfile = $ENV{HOME} . "/.barnowlconf";
166}
167$configfile ||= $ENV{HOME}."/.owlconf";
[d03091c]168
[186cdc4]169# populate global variable space for legacy owlconf files
[f1e629d]170sub _receive_msg_legacy_wrap {
171    my ($m) = @_;
172    $m->legacy_populate_global();
[0337203]173    return &BarnOwl::Hooks::_receive_msg($m);
[f1e629d]174}
175
[74fc22a]176=head2 AUTOLOAD
177
178BarnOwl.pm has a C<AUTOLOAD> method that translates unused names in
179the BarnOwl:: namespace to a call to BarnOwl::command() with that
180command. Underscores are also translated to C<->s, so you can do
181e.g. C<BarnOwl::start_command()> and it will be translated into
182C<start-command>.
183
184So, if you're looking for functionality that you can't find in the
185perl interface, check C<:show commands> or C<commands.c> in the
186BarnOwl source tree -- there's a good chance it exists as a BarnOwl
187command.
188
189=head3 BUGS
190
191There are horrible quoting issues here. The AUTOLOAD simple joins your
192commands with spaces and passes them unmodified to C<::command>
193
194=cut
195
[8203afd]196# make BarnOwl::<command>("foo") be aliases to BarnOwl::command("<command> foo");
[f1e629d]197sub AUTOLOAD {
[c681337]198    our $AUTOLOAD;
[f1e629d]199    my $called = $AUTOLOAD;
200    $called =~ s/.*:://;
[e7ac2b6]201    $called =~ s/_/-/g;
[8203afd]202    return &BarnOwl::command("$called ".join(" ",@_));
[f1e629d]203}
204
[6922edd]205=head2 new_command NAME FUNC [{ARGS}]
206
207Add a new owl command. When owl executes the command NAME, FUNC will
208be called with the arguments passed to the command, with NAME as the
209first argument.
210
211ARGS should be a hashref containing any or all of C<summary>,
[74fc22a]212C<usage>, or C<description> keys:
213
214=over 4
215
216=item summary
217
218A one-line summary of the purpose of the command
219
220=item usage
221
222A one-line usage synopsis, showing available options and syntax
223
224=item description
225
226A longer description of the syntax and semantics of the command,
227explaining usage and options
228
229=back
[6922edd]230
231=cut
232
233sub new_command {
234    my $name = shift;
235    my $func = shift;
236    my $args = shift || {};
237    my %args = (
[8757122]238        summary     => "",
239        usage       => "",
240        description => "",
[6922edd]241        %{$args}
242    );
243
[25cccdc]244    BarnOwl::Internal::new_command($name, $func, $args{summary}, $args{usage}, $args{description});
[6922edd]245}
246
[cd57601]247=head2 new_variable_int NAME [{ARGS}]
248
249=head2 new_variable_bool NAME [{ARGS}]
250
251=head2 new_variable_string NAME [{ARGS}]
252
253Add a new owl variable, either an int, a bool, or a string, with the
254specified name.
255
256ARGS can optionally contain the following keys:
257
258=over 4
259
260=item default
261
262The default and initial value for the variable
263
264=item summary
265
266A one-line summary of the variable's purpose
267
268=item description
269
270A longer description of the function of the variable
271
272=back
273
274=cut
275
[a695a68]276sub new_variable_int {
[25cccdc]277    unshift @_, \&BarnOwl::Internal::new_variable_int, 0;
[a695a68]278    goto \&_new_variable;
279}
280
281sub new_variable_bool {
[25cccdc]282    unshift @_, \&BarnOwl::Internal::new_variable_bool, 0;
[a695a68]283    goto \&_new_variable;
284}
285
286sub new_variable_string {
[25cccdc]287    unshift @_, \&BarnOwl::Internal::new_variable_string, "";
[a695a68]288    goto \&_new_variable;
289}
290
291sub _new_variable {
292    my $func = shift;
293    my $default_default = shift;
294    my $name = shift;
295    my $args = shift || {};
296    my %args = (
297        summary     => "",
298        description => "",
299        default     => $default_default,
300        %{$args});
301    $func->($name, $args{default}, $args{summary}, $args{description});
302}
303
[5b75e8b]304=head2 quote STRING
305
306Return a version of STRING fully quoted to survive processing by
307BarnOwl's command parser.
308
309=cut
310
311sub quote {
312    my $str = shift;
[740d5f7]313    return "''" if $str eq '';
314    if ($str !~ /['" ]/) {
[5b75e8b]315        return "$str";
316    }
317    if ($str !~ /'/) {
318        return "'$str'";
319    }
320    $str =~ s/"/"'"'"/g;
321    return '"' . $str . '"';
322}
323
[f1e629d]324#####################################################################
325#####################################################################
326
[8203afd]327package BarnOwl::Message;
[f1e629d]328
[dd16bdd]329sub new {
330    my $class = shift;
331    my %args = (@_);
332    if($class eq __PACKAGE__ && $args{type}) {
[8203afd]333        $class = "BarnOwl::Message::" . ucfirst $args{type};
[dd16bdd]334    }
335    return bless {%args}, $class;
336}
337
[f1e629d]338sub type        { return shift->{"type"}; }
339sub direction   { return shift->{"direction"}; }
340sub time        { return shift->{"time"}; }
341sub id          { return shift->{"id"}; }
342sub body        { return shift->{"body"}; }
343sub sender      { return shift->{"sender"}; }
344sub recipient   { return shift->{"recipient"}; }
345sub login       { return shift->{"login"}; }
[216c734]346sub is_private  { return shift->{"private"}; }
[f1e629d]347
348sub is_login    { return shift->login eq "login"; }
349sub is_logout   { return shift->login eq "logout"; }
350sub is_loginout { my $m=shift; return ($m->is_login or $m->is_logout); }
351sub is_incoming { return (shift->{"direction"} eq "in"); }
352sub is_outgoing { return (shift->{"direction"} eq "out"); }
353
354sub is_deleted  { return shift->{"deleted"}; }
355
356sub is_admin    { return (shift->{"type"} eq "admin"); }
357sub is_generic  { return (shift->{"type"} eq "generic"); }
[421c8ef7]358sub is_zephyr   { return (shift->{"type"} eq "zephyr"); }
[467aa16]359sub is_aim      { return (shift->{"type"} eq "AIM"); }
[dd16bdd]360sub is_jabber   { return (shift->{"type"} eq "jabber"); }
[421c8ef7]361sub is_icq      { return (shift->{"type"} eq "icq"); }
362sub is_yahoo    { return (shift->{"type"} eq "yahoo"); }
363sub is_msn      { return (shift->{"type"} eq "msn"); }
364sub is_loopback { return (shift->{"type"} eq "loopback"); }
[f1e629d]365
366# These are overridden by appropriate message types
367sub is_ping     { return 0; }
368sub is_mail     { return 0; }
[3c9012b]369sub is_personal { return shift->is_private; }
[f1e629d]370sub class       { return undef; }
371sub instance    { return undef; }
372sub realm       { return undef; }
373sub opcode      { return undef; }
374sub header      { return undef; }
375sub host        { return undef; }
376sub hostname    { return undef; }
377sub auth        { return undef; }
378sub fields      { return undef; }
379sub zsig        { return undef; }
380sub zwriteline  { return undef; }
[87c6ef1]381sub login_host  { return undef; }
382sub login_tty   { return undef; }
[f1e629d]383
[57cf4f9]384# This is for back-compat with old messages that set these properties
385# New protocol implementations are encourages to user override these
386# methods.
387sub replycmd         { return shift->{replycmd}};
388sub replysendercmd   { return shift->{replysendercmd}};
389
[ae47efb]390sub pretty_sender    { return shift->sender; }
391sub pretty_recipient { return shift->recipient; }
[f1e629d]392
[dfaa47d]393# Override if you want a context (instance, network, etc.) on personals
394sub personal_context { return ""; }
395
[f1e629d]396sub delete {
397    my ($m) = @_;
[8203afd]398    &BarnOwl::command("delete --id ".$m->id);
[f1e629d]399}
400
401sub undelete {
402    my ($m) = @_;
[8203afd]403    &BarnOwl::command("undelete --id ".$m->id);
[f1e629d]404}
405
406# Serializes the message into something similar to the zwgc->vt format
407sub serialize {
408    my ($this) = @_;
409    my $s;
410    for my $f (keys %$this) {
411        my $val = $this->{$f};
412        if (ref($val) eq "ARRAY") {
413            for my $i (0..@$val-1) {
414                my $aval;
415                $aval = $val->[$i];
416                $aval =~ s/\n/\n$f.$i: /g;
[186cdc4]417                $s .= "$f.$i: $aval\n";
[f1e629d]418            }
419        } else {
420            $val =~ s/\n/\n$f: /g;
421            $s .= "$f: $val\n";
422        }
423    }
424    return $s;
425}
426
427# Populate the annoying legacy global variables
428sub legacy_populate_global {
429    my ($m) = @_;
[8203afd]430    $BarnOwl::direction  = $m->direction ;
431    $BarnOwl::type       = $m->type      ;
432    $BarnOwl::id         = $m->id        ;
433    $BarnOwl::class      = $m->class     ;
434    $BarnOwl::instance   = $m->instance  ;
435    $BarnOwl::recipient  = $m->recipient ;
436    $BarnOwl::sender     = $m->sender    ;
437    $BarnOwl::realm      = $m->realm     ;
438    $BarnOwl::opcode     = $m->opcode    ;
439    $BarnOwl::zsig       = $m->zsig      ;
440    $BarnOwl::msg        = $m->body      ;
441    $BarnOwl::time       = $m->time      ;
442    $BarnOwl::host       = $m->host      ;
443    $BarnOwl::login      = $m->login     ;
444    $BarnOwl::auth       = $m->auth      ;
[f1e629d]445    if ($m->fields) {
[8203afd]446        @BarnOwl::fields = @{$m->fields};
[f1e629d]447        @main::fields = @{$m->fields};
448    } else {
[8203afd]449        @BarnOwl::fields = undef;
[f1e629d]450        @main::fields = undef;
451    }
452}
453
[25729b2]454sub smartfilter {
[0337203]455    die("smartfilter not supported for this message\n");
[25729b2]456}
457
[6e6ded7]458# Display fields -- overridden by subclasses when needed
459sub login_type {""}
460sub login_extra {""}
461sub long_sender {""}
462
463# The context in which a non-personal message was sent, e.g. a chat or
464# class
465sub context {""}
466
467# Some indicator of context *within* $self->context. e.g. the zephyr
468# instance
469sub subcontext {""}
470
[f1e629d]471#####################################################################
472#####################################################################
473
[8203afd]474package BarnOwl::Message::Admin;
[f1e629d]475
[8203afd]476use base qw( BarnOwl::Message );
[f1e629d]477
478sub header       { return shift->{"header"}; }
479
480#####################################################################
481#####################################################################
482
[8203afd]483package BarnOwl::Message::Generic;
[f1e629d]484
[8203afd]485use base qw( BarnOwl::Message );
[f1e629d]486
487#####################################################################
488#####################################################################
489
[186cdc4]490package BarnOwl::Message::Loopback;
491
492use base qw( BarnOwl::Message );
493
[cb06a43]494# all loopback messages are private
495sub is_private {
[186cdc4]496  return 1;
497}
498
[740d5f7]499sub replycmd {return 'loopwrite';}
500sub replysendercmd {return 'loopwrite';}
501
[186cdc4]502#####################################################################
503#####################################################################
504
[8203afd]505package BarnOwl::Message::AIM;
[f1e629d]506
[8203afd]507use base qw( BarnOwl::Message );
[f1e629d]508
[cb06a43]509# all non-loginout AIM messages are private for now...
510sub is_private {
[f1e629d]511    return !(shift->is_loginout);
512}
513
[740d5f7]514sub replycmd {
515    my $self = shift;
516    if ($self->is_incoming) {
517        return "aimwrite " . BarnOwl::quote($self->sender);
518    } else {
519        return "aimwrite " . BarnOwl::quote($self->recipient);
520    }
521}
522
523sub replysendercmd {
524    return shift->replycmd;
525}
526
[f1e629d]527#####################################################################
528#####################################################################
529
[8203afd]530package BarnOwl::Message::Zephyr;
[f1e629d]531
[740d5f7]532use constant WEBZEPHYR_PRINCIPAL => "daemon.webzephyr";
533use constant WEBZEPHYR_CLASS     => "webzephyr";
534use constant WEBZEPHYR_OPCODE    => "webzephyr";
535
[8203afd]536use base qw( BarnOwl::Message );
[f1e629d]537
[740d5f7]538sub strip_realm {
539    my $sender = shift;
540    my $realm = BarnOwl::zephyr_getrealm();
541    $sender =~ s/\@$realm$//;
542    return $sender;
543}
544
[6e6ded7]545sub login_type {
546    return (shift->zsig eq "") ? "(PSEUDO)" : "";
547}
548
549sub login_extra {
550    my $m = shift;
551    return undef if (!$m->is_loginout);
552    my $s = lc($m->host);
553    $s .= " " . $m->login_tty if defined $m->login_tty;
554    return $s;
555}
556
557sub long_sender {
558    my $m = shift;
559    return $m->zsig;
560}
561
562sub context {
563    return shift->class;
564}
565
566sub subcontext {
567    return shift->instance;
568}
569
[186cdc4]570sub login_tty {
[f1e629d]571    my ($m) = @_;
572    return undef if (!$m->is_loginout);
573    return $m->fields->[2];
574}
575
[186cdc4]576sub login_host {
[f1e629d]577    my ($m) = @_;
578    return undef if (!$m->is_loginout);
579    return $m->fields->[0];
580}
581
582sub zwriteline  { return shift->{"zwriteline"}; }
583
584sub is_ping     { return (lc(shift->opcode) eq "ping"); }
585
[186cdc4]586sub is_personal {
[f1e629d]587    my ($m) = @_;
588    return ((lc($m->class) eq "message")
589            && $m->is_private);
590}
591
[186cdc4]592sub is_mail {
[f1e629d]593    my ($m) = @_;
594    return ((lc($m->class) eq "mail") && $m->is_private);
595}
596
597sub pretty_sender {
598    my ($m) = @_;
[740d5f7]599    return strip_realm($m->sender);
[f1e629d]600}
601
[ae47efb]602sub pretty_recipient {
603    my ($m) = @_;
[740d5f7]604    return strip_realm($m->recipient);
[ae47efb]605}
606
[dfaa47d]607sub personal_context {
608    my ($m) = @_;
609    if (lc($m->instance) eq "personal") {
610        return "";
611    } else {
612        return "-i " . $m->instance;
613    }
614}
615
[f1e629d]616# These are arguably zephyr-specific
617sub class       { return shift->{"class"}; }
618sub instance    { return shift->{"instance"}; }
619sub realm       { return shift->{"realm"}; }
620sub opcode      { return shift->{"opcode"}; }
621sub host        { return shift->{"hostname"}; }
622sub hostname    { return shift->{"hostname"}; }
623sub header      { return shift->{"header"}; }
624sub auth        { return shift->{"auth"}; }
625sub fields      { return shift->{"fields"}; }
626sub zsig        { return shift->{"zsig"}; }
627
[740d5f7]628sub zephyr_cc {
629    my $self = shift;
630    return $1 if $self->body =~ /^\s*cc:\s+([^\n]+)/i;
631    return undef;
632}
633
634sub replycmd {
635    my $self = shift;
636    my $sender = shift;
637    $sender = 0 unless defined $sender;
638    my ($class, $instance, $to, $cc);
639    if($self->is_outgoing) {
640        return $self->{zwriteline};
641    }
642
643    if($sender && $self->opcode eq WEBZEPHYR_OPCODE) {
644        $class = WEBZEPHYR_CLASS;
[ca53b77]645        $instance = $self->pretty_sender;
[2b6de9d]646        $instance =~ s/-webzephyr$//;
[740d5f7]647        $to = WEBZEPHYR_PRINCIPAL;
648    } elsif($self->class eq WEBZEPHYR_CLASS
649            && $self->is_loginout) {
650        $class = WEBZEPHYR_CLASS;
651        $instance = $self->instance;
652        $to = WEBZEPHYR_PRINCIPAL;
653    } elsif($self->is_loginout || $sender) {
654        $class = 'MESSAGE';
655        $instance = 'PERSONAL';
656        $to = $self->sender;
657    } else {
658        $class = $self->class;
659        $instance = $self->instance;
660        $to = $self->recipient;
661        $cc = $self->zephyr_cc();
662        if($to eq '*' || $to eq '') {
663            $to = '';
664        } elsif($to !~ /^@/) {
665            $to = $self->sender;
666        }
667    }
668
669    my $cmd;
670    if(lc $self->opcode eq 'crypt') {
671        $cmd = 'zcrypt';
672    } else {
673        $cmd = 'zwrite';
674    }
675
676    if (lc $class ne 'message') {
[ca53b77]677        $cmd .= " -c " . BarnOwl::quote($class);
[740d5f7]678    }
679    if (lc $instance ne 'personal') {
[ca53b77]680        $cmd .= " -i " . BarnOwl::quote($instance);
[740d5f7]681    }
682    if ($to ne '') {
683        $to = strip_realm($to);
684        if (defined $cc) {
685            my @cc = grep /^[^-]/, ($to, split /\s+/, $cc);
686            my %cc = map {$_ => 1} @cc;
687            delete $cc{strip_realm(BarnOwl::zephyr_getsender())};
688            @cc = keys %cc;
689            $cmd .= " -C " . join(" ", @cc);
690        } else {
691            if(BarnOwl::getvar('smartstrip') eq 'on') {
692                $to = BarnOwl::zephyr_smartstrip_user($to);
693            }
694            $cmd .= " $to";
695        }
696    }
697    return $cmd;
698}
699
700sub replysendercmd {
701    my $self = shift;
702    return $self->replycmd(1);
703}
704
705#####################################################################
[f1e629d]706#####################################################################
707#####################################################################
[7e470da]708
[0337203]709package BarnOwl::Hook;
[7e470da]710
[1a64de6]711=head1 BarnOwl::Hook
712
713=head1 DESCRIPTION
714
715A C<BarnOwl::Hook> represents a list of functions to be triggered on
716some event. C<BarnOwl> exports a default set of these (see
717C<BarnOwl::Hooks>), but can also be created and used by module code.
718
719=head2 new
720
721Creates a new Hook object
722
723=cut
724
[0337203]725sub new {
726    my $class = shift;
727    return bless [], $class;
728}
[7e470da]729
[1a64de6]730=head2 run [ARGS]
731
732Calls each of the functions registered with this hook with the given
733arguments.
734
735=cut
736
[0337203]737sub run {
738    my $self = shift;
739    my @args = @_;
[167044b]740    return map {$self->_run($_,@args)} @$self;
741}
742
743sub _run {
744    my $self = shift;
745    my $fn = shift;
746    my @args = @_;
747    no strict 'refs';
748    return $fn->(@args);
[7e470da]749}
[0337203]750
[1a64de6]751=head2 add SUBREF
752
753Registers a given subroutine with this hook
754
755=cut
756
[0337203]757sub add {
758    my $self = shift;
759    my $func = shift;
[167044b]760    die("Not a coderef!") unless ref($func) eq 'CODE' || !ref($func);
761    return if grep {$_ eq $func} @$self;
[0337203]762    push @$self, $func;
[7e470da]763}
764
[1a64de6]765=head2 clear
766
767Remove all functions registered with this hook.
768
769=cut
770
[0337203]771sub clear {
772    my $self = shift;
773    @$self = ();
[7e470da]774}
775
[0337203]776package BarnOwl::Hooks;
[7e470da]777
[1a64de6]778=head1 BarnOwl::Hooks
779
780=head1 DESCRIPTION
781
782C<BarnOwl::Hooks> exports a set of C<BarnOwl::Hook> objects made
783available by BarnOwl internally.
784
785=head2 USAGE
786
787Modules wishing to respond to events in BarnOwl should register
788functions with these hooks.
789
790=head2 EXPORTS
791
792None by default. Either import the hooks you need explicitly, or refer
793to them with fully-qualified names. Available hooks are:
794
795=over 4
796
797=item $startup
798
799Called on BarnOwl startup, and whenever modules are
800reloaded. Functions registered with the C<$startup> hook get a true
801argument if this is a reload, and false if this is a true startup
802
803=item $shutdown
804
805Called before BarnOwl shutdown
806
807=item $receiveMessage
808
[e9708d2]809Called with a C<BarnOwl::Message> object every time BarnOwl receives a
810new incoming message.
811
812=item $newMessage
813
814Called with a C<BarnOwl::Message> object every time BarnOwl appends
815I<any> new message to the message list.
[1a64de6]816
817=item $mainLoop
818
[b07d8c8]819Called on every pass through the C<BarnOwl> main loop. This is
820guaranteed to be called at least once/sec and may be called more
821frequently.
[1a64de6]822
823=item $getBuddyList
824
825Called to display buddy lists for all protocol handlers. The result
826from every function registered with this hook will be appended and
827displayed in a popup window, with zephyr formatting parsed.
828
[799b60e]829=item $getQuickstart
830
831Called by :show quickstart to display 2-5 lines of help on how to
832start using the protocol. The result from every function registered
833with this hook will be appended and displayed in an admin message,
834with zephyr formatting parsed. The format should be
835"@b(Protocol:)\nSome text.\nMore text.\n"
836
[1a64de6]837=back
838
839=cut
840
[0337203]841use Exporter;
842
843our @EXPORT_OK = qw($startup $shutdown
[0f9eca7]844                    $receiveMessage $newMessage
[799b60e]845                    $mainLoop $getBuddyList
846                    $getQuickstart);
[0337203]847
848our %EXPORT_TAGS = (all => [@EXPORT_OK]);
849
850our $startup = BarnOwl::Hook->new;
851our $shutdown = BarnOwl::Hook->new;
852our $receiveMessage = BarnOwl::Hook->new;
[0f9eca7]853our $newMessage = BarnOwl::Hook->new;
[0337203]854our $mainLoop = BarnOwl::Hook->new;
855our $getBuddyList = BarnOwl::Hook->new;
[799b60e]856our $getQuickstart = BarnOwl::Hook->new;
[0337203]857
858# Internal startup/shutdown routines called by the C code
[7e470da]859
[2650a10]860sub _load_perl_commands {
861    # Load builtin perl commands
862    BarnOwl::new_command(style => \&BarnOwl::Style::style_command,
863                       {
864                           summary => "creates a new style",
865                           usage   => "style <name> perl <function_name>",
866                           description =>
867                           "A style named <name> will be created that will\n" .
868                           "format messages using the perl function <function_name>.\n\n" .
869                           "SEE ALSO: show styles, view -s, filter -s\n\n" .
870                           "DEPRECATED in favor of BarnOwl::create_style(NAME, OBJECT)",
871                          });
872}
873
[b6c067a]874sub _load_owlconf {
875    # load the config  file
876    if ( -r $BarnOwl::configfile ) {
877        undef $@;
[e8bc8ac]878        package main;
[b6c067a]879        do $BarnOwl::configfile;
[e2257be]880        if($@) {
881            BarnOwl::error("In startup: $@\n");
882            return;
883        }
[e8bc8ac]884        package BarnOwl;
[39dc159]885        if(*BarnOwl::format_msg{CODE}) {
886            # if the config defines a legacy formatting function, add 'perl' as a style
[b67ab6b]887            BarnOwl::create_style("perl", BarnOwl::Style::Legacy->new(
888                "BarnOwl::format_msg",
889                "User-defined perl style that calls BarnOwl::format_msg"
890                . " with legacy global variable support",
891                1));
892             BarnOwl::set("-q default_style perl");
[39dc159]893        }
[b6c067a]894    }
895}
896
[b0c8011]897# These are the internal hooks called by the barnowl C code, which
898# take care of dispatching to the appropriate perl hooks, and deal
899# with compatibility by calling the old, fixed-name hooks.
900
[0337203]901sub _startup {
[2650a10]902    _load_perl_commands();
[0337203]903    _load_owlconf();
[8203afd]904
[0337203]905    if(eval {require BarnOwl::ModuleLoader}) {
906        eval {
907            BarnOwl::ModuleLoader->load_all;
908        };
[f6b319c]909        BarnOwl::error("$@") if $@;
910
[0337203]911    } else {
912        BarnOwl::error("Can't load BarnOwl::ModuleLoader, loadable module support disabled:\n$@");
913    }
914   
[836e6263]915    $startup->run(0);
[8203afd]916    BarnOwl::startup() if *BarnOwl::startup{CODE};
917}
918
[0337203]919sub _shutdown {
920    $shutdown->run;
921   
[8203afd]922    BarnOwl::shutdown() if *BarnOwl::shutdown{CODE};
923}
924
[0337203]925sub _receive_msg {
[7e470da]926    my $m = shift;
[0337203]927
928    $receiveMessage->run($m);
929   
[8203afd]930    BarnOwl::receive_msg($m) if *BarnOwl::receive_msg{CODE};
[7e470da]931}
932
[0f9eca7]933sub _new_msg {
934    my $m = shift;
935
936    $newMessage->run($m);
937   
938    BarnOwl::new_msg($m) if *BarnOwl::new_msg{CODE};
939}
940
[0337203]941sub _mainloop_hook {
942    $mainLoop->run;
943    BarnOwl::mainloop_hook() if *BarnOwl::mainloop_hook{CODE};
944}
[7e470da]945
[0337203]946sub _get_blist {
947    return join("\n", $getBuddyList->run);
[7e470da]948}
[dd16bdd]949
[799b60e]950sub _get_quickstart {
951    return join("\n", $getQuickstart->run);
952}
953
[b6c067a]954################################################################################
955# Built-in perl styles
956################################################################################
957package BarnOwl::Style::Default;
958################################################################################
959# Branching point for various formatting functions in this style.
960################################################################################
[426735d]961sub format_message
[b6c067a]962{
[864ed35]963    my $self = shift;
[811ad93]964    my $m    = shift;
965    my $fmt;
[b6c067a]966
[6e6ded7]967    if ( $m->is_loginout) {
[811ad93]968        $fmt = $self->format_login($m);
[18fb3d4f]969    } elsif($m->is_ping && $m->is_personal) {
[811ad93]970        $fmt = $self->format_ping($m);
[6e6ded7]971    } elsif($m->is_admin) {
[811ad93]972        $fmt = $self->format_admin($m);
[6e6ded7]973    } else {
[811ad93]974        $fmt = $self->format_chat($m);
[b6c067a]975    }
[811ad93]976    $fmt = BarnOwl::Style::boldify($fmt) if $self->should_bold($m);
977    return $fmt;
978}
979
980sub should_bold {
981    my $self = shift;
982    my $m = shift;
983    return $m->is_personal && $m->direction eq "in";
[b6c067a]984}
985
[864ed35]986sub description {"Default style";}
987
[b67ab6b]988BarnOwl::create_style("default", "BarnOwl::Style::Default");
[b6c067a]989
990################################################################################
991
[426735d]992sub format_time {
[6b3878b]993    my $self = shift;
[6e6ded7]994    my $m = shift;
[b6c067a]995    my ($time) = $m->time =~ /(\d\d:\d\d)/;
[6e6ded7]996    return $time;
[b6c067a]997}
998
[426735d]999sub format_login {
[864ed35]1000    my $self = shift;
[b6c067a]1001    my $m = shift;
[6e6ded7]1002    return sprintf(
1003        '@b<%s%s> for @b(%s) (%s) %s',
1004        uc( $m->login ),
1005        $m->login_type,
1006        $m->pretty_sender,
1007        $m->login_extra,
[426735d]1008        $self->format_time($m)
[6e6ded7]1009       );
[b6c067a]1010}
1011
[864ed35]1012sub format_ping {
1013    my $self = shift;
1014    my $m = shift;
[2017d07]1015    return "\@b(PING) from \@b(" . $m->pretty_sender . ")";
[864ed35]1016}
1017
1018sub format_admin {
1019    my $self = shift;
1020    my $m = shift;
[811ad93]1021    return "\@bold(OWL ADMIN)\n" . $self->indent_body($m);
[864ed35]1022}
1023
[426735d]1024sub format_chat {
[864ed35]1025    my $self = shift;
[b6c067a]1026    my $m = shift;
[811ad93]1027    my $header = $self->chat_header($m);
1028    return $header . "\n". $self->indent_body($m);
1029}
1030
1031sub chat_header {
1032    my $self = shift;
1033    my $m = shift;
[6e6ded7]1034    my $header;
1035    if ( $m->is_personal ) {
[dfaa47d]1036        my $personal_context = $m->personal_context;
1037        $personal_context = ' [' . $personal_context . ']' if $personal_context;
1038
[6e6ded7]1039        if ( $m->direction eq "out" ) {
[dfaa47d]1040            $header = ucfirst $m->type . $personal_context . " sent to " . $m->pretty_recipient;
[6e6ded7]1041        } else {
[dfaa47d]1042            $header = ucfirst $m->type . $personal_context . " from " . $m->pretty_sender;
[6e6ded7]1043        }
1044    } else {
1045        $header = $m->context;
[37dd88c]1046        if(defined $m->subcontext) {
[c39999f]1047            $header .= ' / ' . $m->subcontext;
[6e6ded7]1048        }
[c39999f]1049        $header .= ' / @b{' . $m->pretty_sender . '}';
[6e6ded7]1050    }
[b6c067a]1051
[b51d257]1052    if($m->opcode) {
1053        $header .= " [" . $m->opcode . "]";
1054    }
[426735d]1055    $header .= "  " . $self->format_time($m);
[811ad93]1056    $header .= $self->format_sender($m);
1057    return $header;
1058}
1059
1060sub format_sender {
1061    my $self = shift;
1062    my $m = shift;
[0449730]1063    my $sender = $m->long_sender;
1064    $sender =~ s/\n.*$//s;
[19aeff4]1065    if (BarnOwl::getvar('colorztext') eq 'on') {
1066      return "  (" . $sender . '@color[default]' . ")";
1067    } else {
1068      return "  ($sender)";
1069    }
[b6c067a]1070}
1071
[426735d]1072sub indent_body
[b6c067a]1073{
[811ad93]1074    my $self = shift;
[b6c067a]1075    my $m = shift;
[186cdc4]1076
[b6c067a]1077    my $body = $m->body;
[f6b319c]1078    if ($m->{should_wordwrap}) {
[7743955]1079      $body = BarnOwl::wordwrap($body, BarnOwl::getnumcols()-9);
[f6b319c]1080    }
[186cdc4]1081    # replace newline followed by anything with
[b6c067a]1082    # newline plus four spaces and that thing.
1083    $body =~ s/\n(.)/\n    $1/g;
[f2d72128]1084    # Trim trailing newlines.
1085    $body =~ s/\n*$//;
[b6c067a]1086    return "    ".$body;
1087}
1088
[864ed35]1089package BarnOwl::Style::Basic;
1090our @ISA=qw(BarnOwl::Style::Default);
1091
1092sub description {"Compatability alias for the default style";}
1093
[b67ab6b]1094BarnOwl::create_style("basic", "BarnOwl::Style::Basic");
[864ed35]1095
[f2d72128]1096package BarnOwl::Style::OneLine;
[811ad93]1097# Inherit format_message to dispatch
1098our @ISA = qw(BarnOwl::Style::Default);
[f2d72128]1099
[811ad93]1100use constant BASE_FORMAT => '%s %-13.13s %-11.11s %-12.12s ';
[f2d72128]1101
[864ed35]1102sub description {"Formats for one-line-per-message"}
1103
[b67ab6b]1104BarnOwl::create_style("oneline", "BarnOwl::Style::OneLine");
[f2d72128]1105
1106################################################################################
1107
[5008e51]1108sub maybe {
1109    my $thing = shift;
1110    return defined($thing) ? $thing : "";
1111}
1112
[426735d]1113sub format_login {
[864ed35]1114  my $self = shift;
[f2d72128]1115  my $m = shift;
1116  return sprintf(
1117    BASE_FORMAT,
1118    '<',
1119    $m->type,
1120    uc( $m->login ),
1121    $m->pretty_sender)
1122    . ($m->login_extra ? "at ".$m->login_extra : '');
1123}
1124
[426735d]1125sub format_ping {
[2017d07]1126  my $self = shift;
[f2d72128]1127  my $m = shift;
1128  return sprintf(
1129    BASE_FORMAT,
1130    '<',
1131    $m->type,
1132    'PING',
1133    $m->pretty_sender)
1134}
1135
[426735d]1136sub format_chat
[f2d72128]1137{
[864ed35]1138  my $self = shift;
[f2d72128]1139  my $m = shift;
1140  my $dir = lc($m->{direction});
1141  my $dirsym = '-';
1142  if ($dir eq 'in') {
1143    $dirsym = '<';
1144  }
1145  elsif ($dir eq 'out') {
1146    $dirsym = '>';
1147  }
1148
1149  my $line;
1150  if ($m->is_personal) {
1151    $line= sprintf(BASE_FORMAT,
[811ad93]1152                   $dirsym,
1153                   $m->type,
1154                   '',
1155                   ($dir eq 'out'
1156                    ? $m->pretty_recipient
1157                    : $m->pretty_sender));
[f2d72128]1158  }
1159  else {
1160    $line = sprintf(BASE_FORMAT,
[811ad93]1161                    $dirsym,
[5008e51]1162                    maybe($m->context),
1163                    maybe($m->subcontext),
[811ad93]1164                    ($dir eq 'out'
1165                     ? $m->pretty_recipient
1166                     : $m->pretty_sender));
[f2d72128]1167  }
1168
1169  my $body = $m->{body};
1170  $body =~ tr/\n/ /;
1171  $line .= $body;
1172  return $line;
1173}
1174
[811ad93]1175# Format owl admin messages
[426735d]1176sub format_admin
[f2d72128]1177{
[864ed35]1178  my $self = shift;
[f2d72128]1179  my $m = shift;
[811ad93]1180  my $line = sprintf(BASE_FORMAT, '<', 'ADMIN', '', '');
[f2d72128]1181  my $body = $m->{body};
1182  $body =~ tr/\n/ /;
1183  return $line.$body;
1184}
[b6c067a]1185
1186package BarnOwl::Style;
1187
1188# This takes a zephyr to be displayed and modifies it to be displayed
1189# entirely in bold.
[426735d]1190sub boldify
[b6c067a]1191{
1192    local $_ = shift;
1193    if ( !(/\)/) ) {
1194        return '@b(' . $_ . ')';
1195    } elsif ( !(/\>/) ) {
1196        return '@b<' . $_ . '>';
1197    } elsif ( !(/\}/) ) {
1198        return '@b{' . $_ . '}';
1199    } elsif ( !(/\]/) ) {
1200        return '@b[' . $_ . ']';
1201    } else {
1202        my $txt = "\@b($_";
1203        $txt =~ s/\)/\)\@b\[\)\]\@b\(/g;
1204        return $txt . ')';
1205    }
1206}
1207
[2650a10]1208sub style_command {
1209    my $command = shift;
1210    if(scalar @_ != 3 || $_[1] ne 'perl') {
1211        die("Usage: style <name> perl <function>\n");
1212    }
1213    my $name = shift;
1214    my $perl = shift;
1215    my $fn   = shift;
1216    {
[b441079]1217        # For historical reasons, assume unqualified references are
1218        # in main::
1219        package main;
[2650a10]1220        no strict 'refs';
1221        unless(*{$fn}{CODE}) {
1222            die("Unable to create style '$name': no perl function '$fn'\n");
1223        }
1224    }
1225    BarnOwl::create_style($name, BarnOwl::Style::Legacy->new($fn));
1226}
1227
[b67ab6b]1228package BarnOwl::Style::Legacy;
1229
1230sub new {
1231    my $class = shift;
1232    my $func  = shift;
1233    my $desc  = shift;
1234    my $useglobals = shift;
1235    $useglobals = 0 unless defined($useglobals);
1236    return bless {function    => $func,
1237                  description => $desc,
1238                  useglobals  => $useglobals}, $class;
1239}
1240
[2650a10]1241sub description {
1242    my $self = shift;
1243    return $self->{description} ||
1244    ("User-defined perl style that calls " . $self->{function});
1245};
[b67ab6b]1246
1247sub format_message {
1248    my $self = shift;
1249    if($self->{useglobals}) {
1250        $_[0]->legacy_populate_global();
1251    }
[b441079]1252    {
1253      package main;
1254      no strict 'refs';
1255      goto \&{$self->{function}};
1256    }
[b67ab6b]1257}
1258
[1631825]1259package BarnOwl::Timer;
1260
1261sub new {
1262    my $class = shift;
1263    my $args = shift;
1264
1265    my $cb = $args->{cb};
1266    die("Invalid callback pased to BarnOwl::Timer\n") unless ref($cb) eq 'CODE';
1267
1268    my $self = {cb => $cb};
1269
1270    bless($self, $class);
1271
1272    $self->{timer} = BarnOwl::Internal::add_timer($args->{after} || 0,
1273                                                  $args->{interval} || 0,
1274                                                  $self);
1275    return $self;
1276}
1277
1278sub do_callback {
1279    my $self = shift;
1280    $self->{cb}->($self);
1281}
1282
1283sub DESTROY {
1284    my $self = shift;
1285    if(defined($self->{timer})) {
1286        BarnOwl::Internal::remove_timer($self->{timer});
1287    }
1288}
1289
[b6c067a]1290
[f1e629d]1291# switch to package main when we're done
1292package main;
[0337203]1293
1294# Shove a bunch of fake entries into @INC so modules can use or
1295# require them without choking
1296$::INC{$_} = 1 for (qw(BarnOwl.pm BarnOwl/Hooks.pm
1297                       BarnOwl/Message.pm BarnOwl/Style.pm));
[f1e629d]1298
12991;
[0337203]1300
Note: See TracBrowser for help on using the repository browser.