source: perlwrap.pm @ 167044b

debianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 167044b was 167044b, checked in by Nelson Elhage <nelhage@mit.edu>, 16 years ago
Support string hook entries. perlwrap.pm: Support calling and adding string hook entries in BarnOwl::Hook IRC.pm: Switch our hooks to use string entries Jabber.pm: Switch our hooks to use string entries ModuleLoader.pm: No longer clear all hooks on reload This should have the net effect that we can safely reload single modules.
  • Property mode set to 100644
File size: 27.1 KB
Line 
1# $Id$
2#
3# This is all linked into the binary and evaluated when perl starts up...
4#
5#####################################################################
6#####################################################################
7# XXX NOTE: This file is sourced before almost any barnowl
8# architecture is loaded. This means, for example, that it cannot
9# execute any owl commands. Any code that needs to do so should live
10# in BarnOwl::Hooks::_startup
11
12use strict;
13use warnings;
14
15package BarnOwl;
16
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
70=head2 zephyr_getsubs
71
72Returns the list of subscription triples <class,instance,recipient>,
73separated by newlines.
74
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
96=head2 start_edit_win PROMPT CALLBACK
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
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
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
148=cut
149
150
151BEGIN {
152# bootstrap in C bindings and glue
153    *owl:: = \*BarnOwl::;
154    bootstrap BarnOwl 1.2;
155};
156
157use lib(get_data_dir() . "/lib");
158use lib(get_config_dir() . "/lib");
159
160# perlconfig.c will set this to the value of the -c command-line
161# switch, if present.
162our $configfile;
163
164if(!$configfile && -f $ENV{HOME} . "/.barnowlconf") {
165    $configfile = $ENV{HOME} . "/.barnowlconf";
166}
167$configfile ||= $ENV{HOME}."/.owlconf";
168
169# populate global variable space for legacy owlconf files
170sub _receive_msg_legacy_wrap {
171    my ($m) = @_;
172    $m->legacy_populate_global();
173    return &BarnOwl::Hooks::_receive_msg($m);
174}
175
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
196# make BarnOwl::<command>("foo") be aliases to BarnOwl::command("<command> foo");
197sub AUTOLOAD {
198    our $AUTOLOAD;
199    my $called = $AUTOLOAD;
200    $called =~ s/.*:://;
201    $called =~ s/_/-/g;
202    return &BarnOwl::command("$called ".join(" ",@_));
203}
204
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>,
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
230
231=cut
232
233sub new_command {
234    my $name = shift;
235    my $func = shift;
236    my $args = shift || {};
237    my %args = (
238        summary     => "",
239        usage       => "",
240        description => "",
241        %{$args}
242    );
243
244    BarnOwl::new_command_internal($name, $func, $args{summary}, $args{usage}, $args{description});
245}
246
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
276sub new_variable_int {
277    unshift @_, \&BarnOwl::new_variable_int_internal, 0;
278    goto \&_new_variable;
279}
280
281sub new_variable_bool {
282    unshift @_, \&BarnOwl::new_variable_bool_internal, 0;
283    goto \&_new_variable;
284}
285
286sub new_variable_string {
287    unshift @_, \&BarnOwl::new_variable_string_internal, "";
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
304#####################################################################
305#####################################################################
306
307package BarnOwl::Message;
308
309sub new {
310    my $class = shift;
311    my %args = (@_);
312    if($class eq __PACKAGE__ && $args{type}) {
313        $class = "BarnOwl::Message::" . ucfirst $args{type};
314    }
315    return bless {%args}, $class;
316}
317
318sub type        { return shift->{"type"}; }
319sub direction   { return shift->{"direction"}; }
320sub time        { return shift->{"time"}; }
321sub id          { return shift->{"id"}; }
322sub body        { return shift->{"body"}; }
323sub sender      { return shift->{"sender"}; }
324sub recipient   { return shift->{"recipient"}; }
325sub login       { return shift->{"login"}; }
326sub is_private  { return shift->{"private"}; }
327
328sub is_login    { return shift->login eq "login"; }
329sub is_logout   { return shift->login eq "logout"; }
330sub is_loginout { my $m=shift; return ($m->is_login or $m->is_logout); }
331sub is_incoming { return (shift->{"direction"} eq "in"); }
332sub is_outgoing { return (shift->{"direction"} eq "out"); }
333
334sub is_deleted  { return shift->{"deleted"}; }
335
336sub is_admin    { return (shift->{"type"} eq "admin"); }
337sub is_generic  { return (shift->{"type"} eq "generic"); }
338sub is_zephyr   { return (shift->{"type"} eq "zephyr"); }
339sub is_aim      { return (shift->{"type"} eq "AIM"); }
340sub is_jabber   { return (shift->{"type"} eq "jabber"); }
341sub is_icq      { return (shift->{"type"} eq "icq"); }
342sub is_yahoo    { return (shift->{"type"} eq "yahoo"); }
343sub is_msn      { return (shift->{"type"} eq "msn"); }
344sub is_loopback { return (shift->{"type"} eq "loopback"); }
345
346# These are overridden by appropriate message types
347sub is_ping     { return 0; }
348sub is_mail     { return 0; }
349sub is_personal { return shift->is_private; }
350sub class       { return undef; }
351sub instance    { return undef; }
352sub realm       { return undef; }
353sub opcode      { return undef; }
354sub header      { return undef; }
355sub host        { return undef; }
356sub hostname    { return undef; }
357sub auth        { return undef; }
358sub fields      { return undef; }
359sub zsig        { return undef; }
360sub zwriteline  { return undef; }
361sub login_host  { return undef; }
362sub login_tty   { return undef; }
363
364sub pretty_sender    { return shift->sender; }
365sub pretty_recipient { return shift->recipient; }
366
367sub delete {
368    my ($m) = @_;
369    &BarnOwl::command("delete --id ".$m->id);
370}
371
372sub undelete {
373    my ($m) = @_;
374    &BarnOwl::command("undelete --id ".$m->id);
375}
376
377# Serializes the message into something similar to the zwgc->vt format
378sub serialize {
379    my ($this) = @_;
380    my $s;
381    for my $f (keys %$this) {
382        my $val = $this->{$f};
383        if (ref($val) eq "ARRAY") {
384            for my $i (0..@$val-1) {
385                my $aval;
386                $aval = $val->[$i];
387                $aval =~ s/\n/\n$f.$i: /g;
388                $s .= "$f.$i: $aval\n";
389            }
390        } else {
391            $val =~ s/\n/\n$f: /g;
392            $s .= "$f: $val\n";
393        }
394    }
395    return $s;
396}
397
398# Populate the annoying legacy global variables
399sub legacy_populate_global {
400    my ($m) = @_;
401    $BarnOwl::direction  = $m->direction ;
402    $BarnOwl::type       = $m->type      ;
403    $BarnOwl::id         = $m->id        ;
404    $BarnOwl::class      = $m->class     ;
405    $BarnOwl::instance   = $m->instance  ;
406    $BarnOwl::recipient  = $m->recipient ;
407    $BarnOwl::sender     = $m->sender    ;
408    $BarnOwl::realm      = $m->realm     ;
409    $BarnOwl::opcode     = $m->opcode    ;
410    $BarnOwl::zsig       = $m->zsig      ;
411    $BarnOwl::msg        = $m->body      ;
412    $BarnOwl::time       = $m->time      ;
413    $BarnOwl::host       = $m->host      ;
414    $BarnOwl::login      = $m->login     ;
415    $BarnOwl::auth       = $m->auth      ;
416    if ($m->fields) {
417        @BarnOwl::fields = @{$m->fields};
418        @main::fields = @{$m->fields};
419    } else {
420        @BarnOwl::fields = undef;
421        @main::fields = undef;
422    }
423}
424
425sub smartfilter {
426    die("smartfilter not supported for this message\n");
427}
428
429# Display fields -- overridden by subclasses when needed
430sub login_type {""}
431sub login_extra {""}
432sub long_sender {""}
433
434# The context in which a non-personal message was sent, e.g. a chat or
435# class
436sub context {""}
437
438# Some indicator of context *within* $self->context. e.g. the zephyr
439# instance
440sub subcontext {""}
441
442#####################################################################
443#####################################################################
444
445package BarnOwl::Message::Admin;
446
447use base qw( BarnOwl::Message );
448
449sub header       { return shift->{"header"}; }
450
451#####################################################################
452#####################################################################
453
454package BarnOwl::Message::Generic;
455
456use base qw( BarnOwl::Message );
457
458#####################################################################
459#####################################################################
460
461package BarnOwl::Message::Loopback;
462
463use base qw( BarnOwl::Message );
464
465# all loopback messages are private
466sub is_private {
467  return 1;
468}
469
470#####################################################################
471#####################################################################
472
473package BarnOwl::Message::AIM;
474
475use base qw( BarnOwl::Message );
476
477# all non-loginout AIM messages are private for now...
478sub is_private {
479    return !(shift->is_loginout);
480}
481
482#####################################################################
483#####################################################################
484
485package BarnOwl::Message::Zephyr;
486
487use base qw( BarnOwl::Message );
488
489sub login_type {
490    return (shift->zsig eq "") ? "(PSEUDO)" : "";
491}
492
493sub login_extra {
494    my $m = shift;
495    return undef if (!$m->is_loginout);
496    my $s = lc($m->host);
497    $s .= " " . $m->login_tty if defined $m->login_tty;
498    return $s;
499}
500
501sub long_sender {
502    my $m = shift;
503    return $m->zsig;
504}
505
506sub context {
507    return shift->class;
508}
509
510sub subcontext {
511    return shift->instance;
512}
513
514sub login_tty {
515    my ($m) = @_;
516    return undef if (!$m->is_loginout);
517    return $m->fields->[2];
518}
519
520sub login_host {
521    my ($m) = @_;
522    return undef if (!$m->is_loginout);
523    return $m->fields->[0];
524}
525
526sub zwriteline  { return shift->{"zwriteline"}; }
527
528sub is_ping     { return (lc(shift->opcode) eq "ping"); }
529
530sub is_personal {
531    my ($m) = @_;
532    return ((lc($m->class) eq "message")
533            && (lc($m->instance) eq "personal")
534            && $m->is_private);
535}
536
537sub is_mail {
538    my ($m) = @_;
539    return ((lc($m->class) eq "mail") && $m->is_private);
540}
541
542sub pretty_sender {
543    my ($m) = @_;
544    my $sender = $m->sender;
545    my $realm = BarnOwl::zephyr_getrealm();
546    $sender =~ s/\@$realm$//;
547    return $sender;
548}
549
550sub pretty_recipient {
551    my ($m) = @_;
552    my $recip = $m->recipient;
553    my $realm = BarnOwl::zephyr_getrealm();
554    $recip =~ s/\@$realm$//;
555    return $recip;
556}
557
558# These are arguably zephyr-specific
559sub class       { return shift->{"class"}; }
560sub instance    { return shift->{"instance"}; }
561sub realm       { return shift->{"realm"}; }
562sub opcode      { return shift->{"opcode"}; }
563sub host        { return shift->{"hostname"}; }
564sub hostname    { return shift->{"hostname"}; }
565sub header      { return shift->{"header"}; }
566sub auth        { return shift->{"auth"}; }
567sub fields      { return shift->{"fields"}; }
568sub zsig        { return shift->{"zsig"}; }
569
570#####################################################################
571#####################################################################
572################################################################################
573
574package BarnOwl::Hook;
575
576=head1 BarnOwl::Hook
577
578=head1 DESCRIPTION
579
580A C<BarnOwl::Hook> represents a list of functions to be triggered on
581some event. C<BarnOwl> exports a default set of these (see
582C<BarnOwl::Hooks>), but can also be created and used by module code.
583
584=head2 new
585
586Creates a new Hook object
587
588=cut
589
590sub new {
591    my $class = shift;
592    return bless [], $class;
593}
594
595=head2 run [ARGS]
596
597Calls each of the functions registered with this hook with the given
598arguments.
599
600=cut
601
602sub run {
603    my $self = shift;
604    my @args = @_;
605    return map {$self->_run($_,@args)} @$self;
606}
607
608sub _run {
609    my $self = shift;
610    my $fn = shift;
611    my @args = @_;
612    no strict 'refs';
613    return $fn->(@args);
614}
615
616=head2 add SUBREF
617
618Registers a given subroutine with this hook
619
620=cut
621
622sub add {
623    my $self = shift;
624    my $func = shift;
625    die("Not a coderef!") unless ref($func) eq 'CODE' || !ref($func);
626    return if grep {$_ eq $func} @$self;
627    push @$self, $func;
628}
629
630=head2 clear
631
632Remove all functions registered with this hook.
633
634=cut
635
636sub clear {
637    my $self = shift;
638    @$self = ();
639}
640
641package BarnOwl::Hooks;
642
643=head1 BarnOwl::Hooks
644
645=head1 DESCRIPTION
646
647C<BarnOwl::Hooks> exports a set of C<BarnOwl::Hook> objects made
648available by BarnOwl internally.
649
650=head2 USAGE
651
652Modules wishing to respond to events in BarnOwl should register
653functions with these hooks.
654
655=head2 EXPORTS
656
657None by default. Either import the hooks you need explicitly, or refer
658to them with fully-qualified names. Available hooks are:
659
660=over 4
661
662=item $startup
663
664Called on BarnOwl startup, and whenever modules are
665reloaded. Functions registered with the C<$startup> hook get a true
666argument if this is a reload, and false if this is a true startup
667
668=item $shutdown
669
670Called before BarnOwl shutdown
671
672=item $receiveMessage
673
674Called with a C<BarnOwl::Message> object every time BarnOwl appends a
675new message to its message list
676
677=item $mainLoop
678
679Called on every pass through the C<BarnOwl> main loop. This is
680guaranteed to be called at least once/sec and may be called more
681frequently.
682
683=item $getBuddyList
684
685Called to display buddy lists for all protocol handlers. The result
686from every function registered with this hook will be appended and
687displayed in a popup window, with zephyr formatting parsed.
688
689=back
690
691=cut
692
693use Exporter;
694
695our @EXPORT_OK = qw($startup $shutdown
696                    $receiveMessage $newMessage
697                    $mainLoop $getBuddyList);
698
699our %EXPORT_TAGS = (all => [@EXPORT_OK]);
700
701our $startup = BarnOwl::Hook->new;
702our $shutdown = BarnOwl::Hook->new;
703our $receiveMessage = BarnOwl::Hook->new;
704our $newMessage = BarnOwl::Hook->new;
705our $mainLoop = BarnOwl::Hook->new;
706our $getBuddyList = BarnOwl::Hook->new;
707
708# Internal startup/shutdown routines called by the C code
709
710sub _load_perl_commands {
711    # Load builtin perl commands
712    BarnOwl::new_command(style => \&BarnOwl::Style::style_command,
713                       {
714                           summary => "creates a new style",
715                           usage   => "style <name> perl <function_name>",
716                           description =>
717                           "A style named <name> will be created that will\n" .
718                           "format messages using the perl function <function_name>.\n\n" .
719                           "SEE ALSO: show styles, view -s, filter -s\n\n" .
720                           "DEPRECATED in favor of BarnOwl::create_style(NAME, OBJECT)",
721                          });
722}
723
724sub _load_owlconf {
725    # load the config  file
726    if ( -r $BarnOwl::configfile ) {
727        undef $@;
728        package main;
729        do $BarnOwl::configfile;
730        if($@) {
731            BarnOwl::error("In startup: $@\n");
732            return;
733        }
734        package BarnOwl;
735        if(*BarnOwl::format_msg{CODE}) {
736            # if the config defines a legacy formatting function, add 'perl' as a style
737            BarnOwl::create_style("perl", BarnOwl::Style::Legacy->new(
738                "BarnOwl::format_msg",
739                "User-defined perl style that calls BarnOwl::format_msg"
740                . " with legacy global variable support",
741                1));
742             BarnOwl::set("-q default_style perl");
743        }
744    }
745}
746
747# These are the internal hooks called by the barnowl C code, which
748# take care of dispatching to the appropriate perl hooks, and deal
749# with compatibility by calling the old, fixed-name hooks.
750
751sub _startup {
752    _load_perl_commands();
753    _load_owlconf();
754
755    if(eval {require BarnOwl::ModuleLoader}) {
756        eval {
757            BarnOwl::ModuleLoader->load_all;
758        };
759        BarnOwl::error("$@") if $@;
760
761    } else {
762        BarnOwl::error("Can't load BarnOwl::ModuleLoader, loadable module support disabled:\n$@");
763    }
764   
765    $startup->run(0);
766    BarnOwl::startup() if *BarnOwl::startup{CODE};
767}
768
769sub _shutdown {
770    $shutdown->run;
771   
772    BarnOwl::shutdown() if *BarnOwl::shutdown{CODE};
773}
774
775sub _receive_msg {
776    my $m = shift;
777
778    $receiveMessage->run($m);
779   
780    BarnOwl::receive_msg($m) if *BarnOwl::receive_msg{CODE};
781}
782
783sub _new_msg {
784    my $m = shift;
785
786    $newMessage->run($m);
787   
788    BarnOwl::new_msg($m) if *BarnOwl::new_msg{CODE};
789}
790
791sub _mainloop_hook {
792    $mainLoop->run;
793    BarnOwl::mainloop_hook() if *BarnOwl::mainloop_hook{CODE};
794}
795
796sub _get_blist {
797    return join("\n", $getBuddyList->run);
798}
799
800################################################################################
801# Built-in perl styles
802################################################################################
803package BarnOwl::Style::Default;
804################################################################################
805# Branching point for various formatting functions in this style.
806################################################################################
807sub format_message
808{
809    my $self = shift;
810    my $m    = shift;
811    my $fmt;
812
813    if ( $m->is_loginout) {
814        $fmt = $self->format_login($m);
815    } elsif($m->is_ping && $m->is_personal) {
816        $fmt = $self->format_ping($m);
817    } elsif($m->is_admin) {
818        $fmt = $self->format_admin($m);
819    } else {
820        $fmt = $self->format_chat($m);
821    }
822    $fmt = BarnOwl::Style::boldify($fmt) if $self->should_bold($m);
823    return $fmt;
824}
825
826sub should_bold {
827    my $self = shift;
828    my $m = shift;
829    return $m->is_personal && $m->direction eq "in";
830}
831
832sub description {"Default style";}
833
834BarnOwl::create_style("default", "BarnOwl::Style::Default");
835
836################################################################################
837
838sub format_time {
839    my $self = shift;
840    my $m = shift;
841    my ($time) = $m->time =~ /(\d\d:\d\d)/;
842    return $time;
843}
844
845sub format_login {
846    my $self = shift;
847    my $m = shift;
848    return sprintf(
849        '@b<%s%s> for @b(%s) (%s) %s',
850        uc( $m->login ),
851        $m->login_type,
852        $m->pretty_sender,
853        $m->login_extra,
854        $self->format_time($m)
855       );
856}
857
858sub format_ping {
859    my $self = shift;
860    my $m = shift;
861    return "\@b(PING) from \@b(" . $m->pretty_sender . ")";
862}
863
864sub format_admin {
865    my $self = shift;
866    my $m = shift;
867    return "\@bold(OWL ADMIN)\n" . $self->indent_body($m);
868}
869
870sub format_chat {
871    my $self = shift;
872    my $m = shift;
873    my $header = $self->chat_header($m);
874    return $header . "\n". $self->indent_body($m);
875}
876
877sub chat_header {
878    my $self = shift;
879    my $m = shift;
880    my $header;
881    if ( $m->is_personal ) {
882        if ( $m->direction eq "out" ) {
883            $header = ucfirst $m->type . " sent to " . $m->pretty_recipient;
884        } else {
885            $header = ucfirst $m->type . " from " . $m->pretty_sender;
886        }
887    } else {
888        $header = $m->context;
889        if(defined $m->subcontext) {
890            $header .= ' / ' . $m->subcontext;
891        }
892        $header .= ' / @b{' . $m->pretty_sender . '}';
893    }
894
895    if($m->opcode) {
896        $header .= " [" . $m->opcode . "]";
897    }
898    $header .= "  " . $self->format_time($m);
899    $header .= $self->format_sender($m);
900    return $header;
901}
902
903sub format_sender {
904    my $self = shift;
905    my $m = shift;
906    my $sender = $m->long_sender;
907    $sender =~ s/\n.*$//s;
908    return "  (" . $sender . '@color[default]' . ")";
909}
910
911sub indent_body
912{
913    my $self = shift;
914    my $m = shift;
915
916    my $body = $m->body;
917    if ($m->{should_wordwrap}) {
918      $body = BarnOwl::wordwrap($body, BarnOwl::getnumcols()-8);
919    }
920    # replace newline followed by anything with
921    # newline plus four spaces and that thing.
922    $body =~ s/\n(.)/\n    $1/g;
923    # Trim trailing newlines.
924    $body =~ s/\n*$//;
925    return "    ".$body;
926}
927
928package BarnOwl::Style::Basic;
929our @ISA=qw(BarnOwl::Style::Default);
930
931sub description {"Compatability alias for the default style";}
932
933BarnOwl::create_style("basic", "BarnOwl::Style::Basic");
934
935package BarnOwl::Style::OneLine;
936# Inherit format_message to dispatch
937our @ISA = qw(BarnOwl::Style::Default);
938
939use constant BASE_FORMAT => '%s %-13.13s %-11.11s %-12.12s ';
940
941sub description {"Formats for one-line-per-message"}
942
943BarnOwl::create_style("oneline", "BarnOwl::Style::OneLine");
944
945################################################################################
946
947sub format_login {
948  my $self = shift;
949  my $m = shift;
950  return sprintf(
951    BASE_FORMAT,
952    '<',
953    $m->type,
954    uc( $m->login ),
955    $m->pretty_sender)
956    . ($m->login_extra ? "at ".$m->login_extra : '');
957}
958
959sub format_ping {
960  my $self = shift;
961  my $m = shift;
962  return sprintf(
963    BASE_FORMAT,
964    '<',
965    $m->type,
966    'PING',
967    $m->pretty_sender)
968}
969
970sub format_chat
971{
972  my $self = shift;
973  my $m = shift;
974  my $dir = lc($m->{direction});
975  my $dirsym = '-';
976  if ($dir eq 'in') {
977    $dirsym = '<';
978  }
979  elsif ($dir eq 'out') {
980    $dirsym = '>';
981  }
982
983  my $line;
984  if ($m->is_personal) {
985    $line= sprintf(BASE_FORMAT,
986                   $dirsym,
987                   $m->type,
988                   '',
989                   ($dir eq 'out'
990                    ? $m->pretty_recipient
991                    : $m->pretty_sender));
992  }
993  else {
994    $line = sprintf(BASE_FORMAT,
995                    $dirsym,
996                    $m->context,
997                    $m->subcontext,
998                    ($dir eq 'out'
999                     ? $m->pretty_recipient
1000                     : $m->pretty_sender));
1001  }
1002
1003  my $body = $m->{body};
1004  $body =~ tr/\n/ /;
1005  $line .= $body;
1006  return $line;
1007}
1008
1009# Format owl admin messages
1010sub format_admin
1011{
1012  my $self = shift;
1013  my $m = shift;
1014  my $line = sprintf(BASE_FORMAT, '<', 'ADMIN', '', '');
1015  my $body = $m->{body};
1016  $body =~ tr/\n/ /;
1017  return $line.$body;
1018}
1019
1020package BarnOwl::Style;
1021
1022# This takes a zephyr to be displayed and modifies it to be displayed
1023# entirely in bold.
1024sub boldify
1025{
1026    local $_ = shift;
1027    if ( !(/\)/) ) {
1028        return '@b(' . $_ . ')';
1029    } elsif ( !(/\>/) ) {
1030        return '@b<' . $_ . '>';
1031    } elsif ( !(/\}/) ) {
1032        return '@b{' . $_ . '}';
1033    } elsif ( !(/\]/) ) {
1034        return '@b[' . $_ . ']';
1035    } else {
1036        my $txt = "\@b($_";
1037        $txt =~ s/\)/\)\@b\[\)\]\@b\(/g;
1038        return $txt . ')';
1039    }
1040}
1041
1042sub style_command {
1043    my $command = shift;
1044    if(scalar @_ != 3 || $_[1] ne 'perl') {
1045        die("Usage: style <name> perl <function>\n");
1046    }
1047    my $name = shift;
1048    my $perl = shift;
1049    my $fn   = shift;
1050    {
1051        # For historical reasons, assume unqualified references are
1052        # in main::
1053        package main;
1054        no strict 'refs';
1055        unless(*{$fn}{CODE}) {
1056            die("Unable to create style '$name': no perl function '$fn'\n");
1057        }
1058    }
1059    BarnOwl::create_style($name, BarnOwl::Style::Legacy->new($fn));
1060}
1061
1062package BarnOwl::Style::Legacy;
1063
1064sub new {
1065    my $class = shift;
1066    my $func  = shift;
1067    my $desc  = shift;
1068    my $useglobals = shift;
1069    $useglobals = 0 unless defined($useglobals);
1070    return bless {function    => $func,
1071                  description => $desc,
1072                  useglobals  => $useglobals}, $class;
1073}
1074
1075sub description {
1076    my $self = shift;
1077    return $self->{description} ||
1078    ("User-defined perl style that calls " . $self->{function});
1079};
1080
1081sub format_message {
1082    my $self = shift;
1083    if($self->{useglobals}) {
1084        $_[0]->legacy_populate_global();
1085    }
1086    {
1087      package main;
1088      no strict 'refs';
1089      goto \&{$self->{function}};
1090    }
1091}
1092
1093
1094# switch to package main when we're done
1095package main;
1096
1097# Shove a bunch of fake entries into @INC so modules can use or
1098# require them without choking
1099$::INC{$_} = 1 for (qw(BarnOwl.pm BarnOwl/Hooks.pm
1100                       BarnOwl/Message.pm BarnOwl/Style.pm));
1101
11021;
1103
Note: See TracBrowser for help on using the repository browser.