AAC-Pvoice

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

Revision history for Perl module AAC::Pvoice

0.1 First version

0.2 0.1 didn't arrive on PAUSE correctly

0.3 minor documentation update in AAC::Pvoice::Bitmap

0.4 correction in AAC::Pvoice::Input to read individual bits
    instead of the whole statusbyte from the parallel port

0.5 AAC::Pvoice::Input now no longer uses Win32::API. Now it uses
    Device::ParallelPort, so it should be able to run on Linux now too.

0.6 AAC::Pvoice::Bitmap now returns a wxNullBitmap if the resize-factor
    is 0 to prevent 'illegal division by zero'
    AAC::Pvoice::EditableRow now has some sensible defaults to prevent
    'Use of uninitialized value' warnings
    AAC::Pvoice::Input can now handle one button input

0.7 AAC::Pvoice::Input
        * now allows keyboard input
        * now allows direct mouseclicks on the buttons
    AAC::Pvoice::Panel
        * now uses a round cornered background and
        * no longer simply sets the background for the normal and
          selected state, but draws a round cornered border around
          the rows and buttons that are selected
        * finally got the screensizing correctly...no more weird
          calculating stuff...
    AAC::Pvoice::Bitmap
        * now produces round cornered bitmaps
    AAC::Pvoice::Row
        * no longer uses too large images (screensizing update)
    AAC::Pvoice::EditableRow
        * no longer uses too large images (screensizing update)

0.8 AAC::Pvoice::Input
        * when keystrokes are used, alpha keys are now case-insensitive
    Several bugfixes and therefore needed new methods (for most of you
    probably not that important)

0.9 AAC::Pvoice::Bitmap
        * We now use Image::Magick to create the bitmaps. It's a change to
          the internals, so the methods and their parameters stay the same.
        * Returned images are cached first (using File::Cache). If an image
          has been processed before, it will be retrieved from the cache.
          The cache never expires, but every combination of parameters
          results in a new cached image (and of course the file modificationtime
          of the image is also taken into account.
    AAC::Pvoice::Dialog
        * This is a newly added class. It's a subclass of Wx::Dialog and
          allows you to create dialog boxes, using an AAC::Pvoice::Panel
    AAC::Pvoice
        * This module now provides the AAC::Pvoice::MessageBox function,
          similar to Wx::MessageBox.
0.91 AAC::Pvoice
        * Made a little more space between the text and the buttons in the MessageBox
          function
     AAC::Pvoice::Bitmap
        * Minor changes
     AAC::Pvoice::Panel
        * ability to return the array of added texts from RetrieveText and SpeechRetrieveText
        and made accompanying changes in other methods.

LICENSE  view on Meta::CPAN

Terms of Perl itself

a) the GNU General Public License as published by the Free
   Software Foundation; either version 1, or (at your option) any
   later version, or
b) the "Artistic License"

---------------------------------------------------------------------------

The General Public License (GPL)
Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave,
Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute
verbatim copies of this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away your freedom to share
and change it. By contrast, the GNU General Public License is intended to
guarantee your freedom to share and change free software--to make sure the
software is free for all its users. This General Public License applies to most of
the Free Software Foundation's software and to any other program whose
authors commit to using it. (Some other Free Software Foundation software is
covered by the GNU Library General Public License instead.) You can apply it to
your programs, too.

When we speak of free software, we are referring to freedom, not price. Our
General Public Licenses are designed to make sure that you have the freedom
to distribute copies of free software (and charge for this service if you wish), that
you receive source code or can get it if you want it, that you can change the
software or use pieces of it in new free programs; and that you know you can do
these things.

To protect your rights, we need to make restrictions that forbid anyone to deny
you these rights or to ask you to surrender the rights. These restrictions
translate to certain responsibilities for you if you distribute copies of the
software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a
fee, you must give the recipients all the rights that you have. You must make
sure that they, too, receive or can get the source code. And you must show
them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer
you this license which gives you legal permission to copy, distribute and/or
modify the software.

Also, for each author's protection and ours, we want to make certain that
everyone understands that there is no warranty for this free software. If the
software is modified by someone else and passed on, we want its recipients to
know that what they have is not the original, so that any problems introduced by
others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish
to avoid the danger that redistributors of a free program will individually obtain
patent licenses, in effect making the program proprietary. To prevent this, we
have made it clear that any patent must be licensed for everyone's free use or
not licensed at all.

The precise terms and conditions for copying, distribution and modification
follow.

GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND
MODIFICATION

0. This License applies to any program or other work which contains a notice
placed by the copyright holder saying it may be distributed under the terms of
this General Public License. The "Program", below, refers to any such program
or work, and a "work based on the Program" means either the Program or any
derivative work under copyright law: that is to say, a work containing the
Program or a portion of it, either verbatim or with modifications and/or translated
into another language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not covered by
this License; they are outside its scope. The act of running the Program is not
restricted, and the output from the Program is covered only if its contents
constitute a work based on the Program (independent of having been made by
running the Program). Whether that is true depends on what the Program does.

1. You may copy and distribute verbatim copies of the Program's source code as
you receive it, in any medium, provided that you conspicuously and appropriately
publish on each copy an appropriate copyright notice and disclaimer of warranty;
keep intact all the notices that refer to this License and to the absence of any
warranty; and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and you may at
your option offer warranty protection in exchange for a fee.

2. You may modify your copy or copies of the Program or any portion of it, thus
forming a work based on the Program, and copy and distribute such
modifications or work under the terms of Section 1 above, provided that you also
meet all of these conditions:

a) You must cause the modified files to carry prominent notices stating that you
changed the files and the date of any change.

b) You must cause any work that you distribute or publish, that in whole or in
part contains or is derived from the Program or any part thereof, to be licensed
as a whole at no charge to all third parties under the terms of this License.

c) If the modified program normally reads commands interactively when run, you
must cause it, when started running for such interactive use in the most ordinary
way, to print or display an announcement including an appropriate copyright
notice and a notice that there is no warranty (or else, saying that you provide a
warranty) and that users may redistribute the program under these conditions,
and telling the user how to view a copy of this License. (Exception: if the
Program itself is interactive but does not normally print such an announcement,
your work based on the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole. If identifiable
sections of that work are not derived from the Program, and can be reasonably
considered independent and separate works in themselves, then this License,
and its terms, do not apply to those sections when you distribute them as
separate works. But when you distribute the same sections as part of a whole
which is a work based on the Program, the distribution of the whole must be on
the terms of this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest your rights to
work written entirely by you; rather, the intent is to exercise the right to control
the distribution of derivative or collective works based on the Program.

In addition, mere aggregation of another work not based on the Program with the
Program (or with a work based on the Program) on a volume of a storage or
distribution medium does not bring the other work under the scope of this
License.

3. You may copy and distribute the Program (or a work based on it, under
Section 2) in object code or executable form under the terms of Sections 1 and 2
above provided that you also do one of the following:

a) Accompany it with the complete corresponding machine-readable source
code, which must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange; or,

b) Accompany it with a written offer, valid for at least three years, to give any
third party, for a charge no more than your cost of physically performing source
distribution, a complete machine-readable copy of the corresponding source
code, to be distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,

c) Accompany it with the information you received as to the offer to distribute
corresponding source code. (This alternative is allowed only for noncommercial
distribution and only if you received the program in object code or executable
form with such an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for making
modifications to it. For an executable work, complete source code means all the
source code for all modules it contains, plus any associated interface definition
files, plus the scripts used to control compilation and installation of the
executable. However, as a special exception, the source code distributed need
not include anything that is normally distributed (in either source or binary form)
with the major components (compiler, kernel, and so on) of the operating system
on which the executable runs, unless that component itself accompanies the
executable.

If distribution of executable or object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the source
code from the same place counts as distribution of the source code, even though
third parties are not compelled to copy the source along with the object code.

4. You may not copy, modify, sublicense, or distribute the Program except as
expressly provided under this License. Any attempt otherwise to copy, modify,
sublicense or distribute the Program is void, and will automatically terminate
your rights under this License. However, parties who have received copies, or
rights, from you under this License will not have their licenses terminated so long
as such parties remain in full compliance.

5. You are not required to accept this License, since you have not signed it.
However, nothing else grants you permission to modify or distribute the Program
or its derivative works. These actions are prohibited by law if you do not accept
this License. Therefore, by modifying or distributing the Program (or any work
based on the Program), you indicate your acceptance of this License to do so,
and all its terms and conditions for copying, distributing or modifying the
Program or works based on it.

6. Each time you redistribute the Program (or any work based on the Program),
the recipient automatically receives a license from the original licensor to copy,
distribute or modify the Program subject to these terms and conditions. You
may not impose any further restrictions on the recipients' exercise of the rights
granted herein. You are not responsible for enforcing compliance by third parties
to this License.

7. If, as a consequence of a court judgment or allegation of patent infringement
or for any other reason (not limited to patent issues), conditions are imposed on
you (whether by court order, agreement or otherwise) that contradict the
conditions of this License, they do not excuse you from the conditions of this
License. If you cannot distribute so as to satisfy simultaneously your obligations
under this License and any other pertinent obligations, then as a consequence
you may not distribute the Program at all. For example, if a patent license would
not permit royalty-free redistribution of the Program by all those who receive
copies directly or indirectly through you, then the only way you could satisfy
both it and this License would be to refrain entirely from distribution of the
Program.

If any portion of this section is held invalid or unenforceable under any particular
circumstance, the balance of the section is intended to apply and the section as
a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any patents or other
property right claims or to contest validity of any such claims; this section has
the sole purpose of protecting the integrity of the free software distribution
system, which is implemented by public license practices. Many people have
made generous contributions to the wide range of software distributed through
that system in reliance on consistent application of that system; it is up to the
author/donor to decide if he or she is willing to distribute software through any
other system and a licensee cannot impose that choice.

This section is intended to make thoroughly clear what is believed to be a
consequence of the rest of this License.

8. If the distribution and/or use of the Program is restricted in certain countries
either by patents or by copyrighted interfaces, the original copyright holder who
places the Program under this License may add an explicit geographical
distribution limitation excluding those countries, so that distribution is permitted
only in or among countries not thus excluded. In such case, this License
incorporates the limitation as if written in the body of this License.

9. The Free Software Foundation may publish revised and/or new versions of the
General Public License from time to time. Such new versions will be similar in
spirit to the present version, but may differ in detail to address new problems or
concerns.

Each version is given a distinguishing version number. If the Program specifies a
version number of this License which applies to it and "any later version", you
have the option of following the terms and conditions either of that version or of
any later version published by the Free Software Foundation. If the Program does
not specify a version number of this License, you may choose any version ever
published by the Free Software Foundation.

10. If you wish to incorporate parts of the Program into other free programs
whose distribution conditions are different, write to the author to ask for
permission. For software which is copyrighted by the Free Software Foundation,
write to the Free Software Foundation; we sometimes make exceptions for this.
Our decision will be guided by the two goals of preserving the free status of all
derivatives of our free software and of promoting the sharing and reuse of
software generally.

NO WARRANTY

11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS
NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE
COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM
"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE,
YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED
TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY
WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS


---------------------------------------------------------------------------

The Artistic License

Preamble

The intent of this document is to state the conditions under which a Package
may be copied, such that the Copyright Holder maintains some semblance of
artistic control over the development of the package, while giving the users of the
package the right to use and distribute the Package in a more-or-less customary
fashion, plus the right to make reasonable modifications.

Definitions:

-    "Package" refers to the collection of files distributed by the Copyright
     Holder, and derivatives of that collection of files created through textual
     modification. 
-    "Standard Version" refers to such a Package if it has not been modified,
     or has been modified in accordance with the wishes of the Copyright
     Holder. 
-    "Copyright Holder" is whoever is named in the copyright or copyrights for
     the package. 
-    "You" is you, if you're thinking about copying or distributing this Package.
-    "Reasonable copying fee" is whatever you can justify on the basis of
     media cost, duplication charges, time of people involved, and so on. (You
     will not be required to justify it to the Copyright Holder, but only to the
     computing community at large as a market that must bear the fee.) 
-    "Freely Available" means that no fee is charged for the item itself, though
     there may be fees involved in handling the item. It also means that
     recipients of the item may redistribute it under the same conditions they
     received it. 

1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you duplicate
all of the original copyright notices and associated disclaimers.

2. You may apply bug fixes, portability fixes and other modifications derived from
the Public Domain or from the Copyright Holder. A Package modified in such a
way shall still be considered the Standard Version.

3. You may otherwise modify your copy of this Package in any way, provided
that you insert a prominent notice in each changed file stating how and when
you changed that file, and provided that you do at least ONE of the following:

     a) place your modifications in the Public Domain or otherwise
     make them Freely Available, such as by posting said modifications
     to Usenet or an equivalent medium, or placing the modifications on
     a major archive site such as ftp.uu.net, or by allowing the
     Copyright Holder to include your modifications in the Standard
     Version of the Package.

     b) use the modified Package only within your corporation or
     organization.

     c) rename any non-standard executables so the names do not
     conflict with standard executables, which must also be provided,
     and provide a separate manual page for each non-standard
     executable that clearly documents how it differs from the Standard
     Version.

     d) make other distribution arrangements with the Copyright Holder.

4. You may distribute the programs of this Package in object code or executable
form, provided that you do at least ONE of the following:

     a) distribute a Standard Version of the executables and library
     files, together with instructions (in the manual page or equivalent)
     on where to get the Standard Version.

     b) accompany the distribution with the machine-readable source of
     the Package with your modifications.

     c) accompany any non-standard executables with their
     corresponding Standard Version executables, giving the
     non-standard executables non-standard names, and clearly
     documenting the differences in manual pages (or equivalent),
     together with instructions on where to get the Standard Version.

     d) make other distribution arrangements with the Copyright Holder.

5. You may charge a reasonable copying fee for any distribution of this Package.
You may charge any fee you choose for support of this Package. You may not
charge a fee for this Package itself. However, you may distribute this Package in
aggregate with other (possibly commercial) programs as part of a larger
(possibly commercial) software distribution provided that you do not advertise
this Package as a product of your own.

6. The scripts and library files supplied as input to or produced as output from
the programs of this Package do not automatically fall under the copyright of this
Package, but belong to whomever generated them, and may be sold
commercially, and may be aggregated with this Package.

7. C or perl subroutines supplied by you and linked into this Package shall not
be considered part of this Package.

8. Aggregation of this Package with a commercial distribution is always permitted
provided that the use of this Package is embedded; that is, when no overt attempt
is made to make this Package's interfaces visible to the end user of the
commercial distribution. Such use shall not be construed as a distribution of
this Package.

9. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.

10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
PURPOSE.

The End


MANIFEST  view on Meta::CPAN

MANIFEST
LICENSE
README
Todo
Changes
lib/AAC/Pvoice.pm
lib/AAC/Pvoice/Bitmap.pm
lib/AAC/Pvoice/Input.pm
lib/AAC/Pvoice/Panel.pm
lib/AAC/Pvoice/Row.pm
lib/AAC/Pvoice/EditableRow.pm
lib/AAC/Pvoice/Dialog.pm
t/001_load.t
Makefile.PL
META.yml

META.yml  view on Meta::CPAN

# http://module-build.sourceforge.net/META-spec.html
#XXXXXXX This is a prototype!!!  It will change in the future!!! XXXXX#
name:         AAC-Pvoice
version:      0.91
version_from: lib/AAC/Pvoice.pm
installdirs:  site
requires:
    Device::ParallelPort:          0
    Device::ParallelPort::drv::win32: 0
    File::Cache:                   0
    File::stat:                    0
    File::Temp:                    0
    Image::Magick:                 6
    IO::Scalar:                    0
    Text::Wrap:                    0
    Wx:                            0.15

distribution_type: module
generated_by: ExtUtils::MakeMaker version 6.17

Makefile.PL  view on Meta::CPAN

use ExtUtils::MakeMaker;

my $pdrv;

if ($^O eq 'MSWin32')
{
    $pdrv = Device::ParallelPort::drv::win32;
}
else
{
    $pdrv = Device::ParallelPort::drv::parport;
}

WriteMakefile(
    NAME         => 'AAC::Pvoice',
    VERSION_FROM => 'lib/AAC/Pvoice.pm', # finds $VERSION
    AUTHOR       => 'Jouke Visser <jouke@cpan.org>',
    ABSTRACT_FROM=> 'lib/AAC/Pvoice.pm',
    PREREQ_PM    => {   Wx                      => 0.15,
                        Image::Magick           => 6.0,
                        Device::ParallelPort    => 0,
                        $pdrv                   => 0,
                        IO::Scalar              => 0,
                        File::Cache             => 0,
                        File::stat              => 0,
                        File::Temp              => 0,
                        Text::Wrap              => 0,
                        }
);

README  view on Meta::CPAN

AAC::Pvoice README

As of version 0.5, these modules should be able to run on all platforms
supported by Device::ParallelPort. This dependency has to do with AAC::Pvoice::Input, which
needs to be able to poll the parallel port in case it needs to communicate
with the 'Adremo' electrical wheelchair. For this I'm  using
Device::ParallelPort, which has drivers for Linux and Win32.

As of version 0.6 the modules allow you to use your application in
One or Two-button mode. See the documentation of AAC::Pvoice::Input for details.

As of version 0.9 you need Image::Magick.

At the very least you should be able to use this set of instructions
to install the module...

perl Makefile.PL
make
make test
make install

If you are on a windows box you should use 'nmake' rather than 'make'.

Todo  view on Meta::CPAN

TODO list for Perl module AAC::Pvoice

- More testing
- AAC::Pvoice::Input needs to be rewritten into smaller chunks for
  each device

lib/AAC/Pvoice.pm  view on Meta::CPAN

package AAC::Pvoice;

use strict;
use warnings;

use Wx qw(:everything);
use Wx::Perl::Carp;
use AAC::Pvoice::Bitmap;
use AAC::Pvoice::Input;
use AAC::Pvoice::Row;
use AAC::Pvoice::EditableRow;
use AAC::Pvoice::Panel;
use AAC::Pvoice::Dialog;
use Text::Wrap qw(wrap);

BEGIN {
	use Exporter ();
	use vars qw ($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
	$VERSION     = 0.91;
	@ISA         = qw (Exporter);
	@EXPORT      = qw (MessageBox);
	@EXPORT_OK   = qw ();
	%EXPORT_TAGS = ();
}

sub MessageBox
{
	my ($message, $caption, $style, $parent, $x, $y) = @_;
    $caption ||= 'Message';
	$style   ||= wxOK;
	$x       ||= -1;
	$y       ||= -1;

	$Text::Wrap::columns = 25;
	$message = wrap('','',$message)."\n";
	
    my $width = 0;
    $width = 25 if $style & wxOK;
    $width = 30 if $style & wxYES_NO;
    $width = 60 if $style & wxCANCEL;

	my $p = Wx::Frame->new(undef, -1, 'tmp');
	my $m = Wx::StaticText->new($p, -1, $message, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE);
	$m->SetFont(Wx::Font->new(  10,                 # font size
                                wxDECORATIVE,       # font family
                                wxNORMAL,           # style
                                wxNORMAL,           # weight
                                0,                  
                                'Comic Sans MS',    # face name
                                wxFONTENCODING_SYSTEM));

	my $h = $m->GetSize->GetHeight;
	$p->Destroy;

	my $d = AAC::Pvoice::Dialog->new(undef, -1, $caption, [$x,$y], [310,100+$h]);
	
	my $messagectrl = Wx::StaticText->new($d->{panel},
                                          -1,
                                          $message,
                                          wxDefaultPosition,
                                          wxDefaultSize,
                                          wxALIGN_CENTRE);
	$messagectrl->SetBackgroundColour($d->{backgroundcolour});
	$messagectrl->SetFont(Wx::Font->new(10,                 # font size
                                        wxDECORATIVE,       # font family
                                        wxNORMAL,           # style
                                        wxNORMAL,           # weight
                                        0,                  
                                        'Comic Sans MS',    # face name
                                        wxFONTENCODING_SYSTEM));

	$d->Append($messagectrl,1);
    my $ok     = [Wx::NewId,AAC::Pvoice::Bitmap->new('',50,25,'OK',    Wx::Colour->new(255, 230, 230)),sub{$d->SetReturnCode(wxOK);    $d->Close()}];
    my $yes    = [Wx::NewId,AAC::Pvoice::Bitmap->new('',50,30,'Yes',   Wx::Colour->new(255, 230, 230)),sub{$d->SetReturnCode(wxYES);   $d->Close()}];
    my $no     = [Wx::NewId,AAC::Pvoice::Bitmap->new('',50,25,'No',    Wx::Colour->new(255, 230, 230)),sub{$d->SetReturnCode(wxNO);    $d->Close()}];
    my $cancel = [Wx::NewId,AAC::Pvoice::Bitmap->new('',50,60,'Cancel',Wx::Colour->new(255, 230, 230)),sub{$d->SetReturnCode(wxCANCEL);$d->Close()}];
    my $items = [];
    push @$items, $ok     if $style & wxOK;
    push @$items, $yes    if $style & wxYES_NO;
    push @$items, $no     if $style & wxYES_NO;
    push @$items, $cancel if $style & wxCANCEL;
	$d->Append(AAC::Pvoice::Row->new($d->{panel},          # parent
                                     scalar(@$items),      # max
                                     $items,               # items
                                     wxDefaultPosition,    # pos
                                     wxDefaultSize,
                                     $width,
                                     25,
                                     $d->{ITEMSPACING},
                                     $d->{backgroundcolour}),
                0); #selectable
	return $d->ShowModal();
}

=pod

=head1 NAME

AAC::Pvoice - Create GUI software for disabled people

=head1 SYNOPSIS

  use AAC::Pvoice
  # this includes all AAC::Pvoice modules


=head1 DESCRIPTION

AAC::Pvoice is a set of modules to create software for people who can't
use a normal mouse and/or keyboard. To see an application that uses this
set of modules, take a look at pVoice (http://www.pvoice.org, or the
sources on http://opensource.pvoice.org). 

AAC::Pvoice is in fact a wrapper around many wxPerl classes, to make it
easier to create applications like pVoice.


=head1 USAGE

=head2 AAC::Pvoice::MessageBox(message, caption, style, parent, x, y)

This function is similar to Wx::MessageBox. It uses the same parameters as
Wx::MessageBox does. Currently the style parameter doesn't support the
icons that can be set on Wx::MessageBox.

See the individual module's documentation

=head1 BUGS

probably a lot, patches welcome!


=head1 AUTHOR

	Jouke Visser
	jouke@pvoice.org
	http://jouke.pvoice.org

=head1 COPYRIGHT

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.


=head1 SEE ALSO

perl(1), Wx, AAC::Pvoice::Panel, AAC::Pvoice::Bitmap, AAC::Pvoice::Row
AAC::Pvoice::EditableRow, AAC::Pvoice::Input

=cut


1; 
__END__

lib/AAC/Pvoice/Bitmap.pm  view on Meta::CPAN

package AAC::Pvoice::Bitmap;

use strict;
use warnings;
use Wx qw(:everything);
use Wx::Perl::Carp;
use Image::Magick;
use IO::Scalar;
use File::Cache;
use File::stat;
use File::Temp qw( :POSIX );

our $VERSION     = sprintf("%d.%02d", q$Revision: 1.12 $=~/(\d+)\.(\d+)/);

use base qw(Wx::Bitmap);
our $cache;
BEGIN
{
    Wx::InitAllImageHandlers;
    $cache = File::Cache->new({namespace => 'images'});
}

#----------------------------------------------------------------------
sub new
{
    my $class = shift;
    my ($file, $MAX_X, $MAX_Y, $caption, $background, $blowup, $parent_background) = @_;
    $caption||='';
    $parent_background=Wx::Colour->new(220,220,220) if not defined $parent_background;
    my $config = Wx::ConfigBase::Get;
    $caption = $config->ReadInt('Caption')?$caption:'';
#    return ReadImage($file, $MAX_X, $MAX_Y, $caption, $background, $blowup, $parent_background) if $file;
    return ReadImageMagick($file, $MAX_X, $MAX_Y, $caption, $background, $blowup, $parent_background) if $file;
    return DrawCaption($MAX_X, $MAX_Y, $caption, $background, $parent_background);
}


sub ReadImage
{
    my $file = shift;
    my ($x, $y, $caption, $background, $blowup, $parent_background) = @_;
    return DrawCaption($x, $y, '?', $background, $parent_background) unless -r $file;
    confess "MaxX and MaxY should be positive" if $x < 1 || $y < 1;
    my $newbmp;
    
    $caption ||='';
    $blowup ||=0;
    $background = $parent_background unless defined $background;

    my $ibg = wxColor2hex($background) if (ref($background) eq 'Wx::Colour');
    my $pbg = wxColor2hex($parent_background) if (ref($parent_background) eq 'Wx::Colour');

    my $stat = stat($file);
    my $mtime = $stat->mtime();
    my $image = $cache->get("$file-$x-$y-$caption-$ibg-$blowup-$pbg-$mtime");
    if (!$image)
    {
        my $capdc = Wx::MemoryDC->new();
        my $cpt = 10;
        my ($cfont, $cw, $ch) = (wxNullFont, 0, 0);
        if ($caption)
        {
            do
            {
                $cfont = Wx::Font->new( $cpt,               # font size
                                        wxSWISS,            # font family
                                        wxNORMAL,           # style
                                        wxNORMAL,           # weight
                                        0,                  
                                        'Comic Sans MS',    # face name
                                        wxFONTENCODING_SYSTEM);
                ($cw, $ch, undef, undef) = $capdc->GetTextExtent($caption, $cfont);
                $cpt--;
            } until ($cw<$x);
        }
        my $img = Wx::Image->new($x, $y-$ch);
        $img->SetOption('quality', 100);
        my $rc = $img->LoadFile($file, wxBITMAP_TYPE_ANY);
        return wxNullBitmap if not $rc;
        my ($w,$h) = ($img->GetWidth, $img->GetHeight);
        if (($w > $x) || ($h > ($y-$ch)))
        {
            my ($newx, $newy) = ($w, $h);
            if ($w > $x)
            {
                my $factor = $w/$x;
                return wxNullBitmap if not $factor;
                $newy = int($h/$factor);
                ($w,$h) = ($x, $newy);
            }
            if ($h > ($y-$ch))
            {
                my $factor = $h/($y-$ch);
                return wxNullBitmap if not $factor;
                ($w, $h) = (int($w/$factor),$y-$ch);
            }
            $img = $img->Scale($w, $h);
        }
        elsif ($blowup)
        {
            # Do we really want to blow up images that are too small??
            my $factor = $w/$x;
            return wxNullBitmap if not $factor;
            my $newy = int($h/$factor);
            ($w,$h) = ($x, $newy);
            if ($h > ($y-$ch))
            {
                my $factor = $h/($y-$ch);
                return wxNullBitmap if not $factor;
                ($w, $h) = (int($w/$factor),$y-$ch);
            }
            $img = $img->Scale($w, $h);
        }
        my $bmp = Wx::Bitmap->new($img);
        my $newbmp = Wx::Bitmap->new($x, $y);
        my $tmpdc = Wx::MemoryDC->new();
        $tmpdc->SelectObject($newbmp);
    
        my $bgbr = Wx::Brush->new($parent_background, wxSOLID);
        $tmpdc->SetBrush($bgbr); 
        $tmpdc->SetBackground($bgbr);
        $tmpdc->Clear();
    
        my $bg = $parent_background;
        if (defined $background)
        {
            if (ref($background)=~/ARRAY/)
            {
                $bg = Wx::Colour->new(@$background);
            }
            else
            {
                $bg = $background;
            }
            my $br = Wx::Brush->new($bg, wxSOLID);
            my $pen = Wx::Pen->new($bg, 1, wxSOLID);
            $tmpdc->SetBrush($br);
            $tmpdc->SetPen($pen);
            $tmpdc->DrawRoundedRectangle(1,1,$x-1,$y-1, 10);
        }
    
        my $msk = Wx::Mask->new($bmp, Wx::Colour->new(255,255,255));
        $bmp->SetMask($msk);
        $tmpdc->DrawBitmap($bmp, int(($x - $bmp->GetWidth())/2), int(($y-$ch-$bmp->GetHeight())/2), 1);
    
        if ($caption)
        {
            $tmpdc->SetTextBackground($bg);
            $tmpdc->SetTextForeground(wxBLACK);
            $tmpdc->SetFont($cfont);
            $tmpdc->DrawText($caption, int(($x-$cw)/2),$y-$ch);
        }
        my $tmpfile = File::Temp::tmpnam();
    	$newbmp->SaveFile($tmpfile, wxBITMAP_TYPE_PNG);
        local $/ = undef;
        open(my $fh, "<$tmpfile");
        binmode($fh);
        my $image = <$fh>;
        close($fh);
    	$cache->set("$file-$x-$y-$caption-$ibg-$blowup-$pbg-$mtime", $image);	
    }
    
    my $fh = IO::Scalar->new(\$image); 	 

    my $contenttype = 'image/png'; 
    return Wx::Bitmap->new(Wx::Image->newStreamMIME($fh,  $contenttype)) 
}

sub wxColor2hex
{
    my $color = shift;
    my $red   = $color->Red();
    my $green = $color->Green();
    my $blue  = $color->Blue();
    return sprintf("#%0x%0x%0x", $red,$green,$blue);
}

sub ReadImageMagick
{
    my $file = shift;
    my ($x, $y, $caption, $bgcolor, $blowup, $parent_background) = @_;
    confess "MaxX and MaxY should be positive" if $x < 1 || $y < 1;
    return DrawCaption($x, $y, '?', $bgcolor, $parent_background) unless -r $file;

    $caption ||='';
    $blowup ||=0;
    $bgcolor = $parent_background unless defined $bgcolor;

    my $ibg = wxColor2hex($bgcolor) if (ref($bgcolor) eq 'Wx::Colour');
    my $pbg = wxColor2hex($parent_background) if (ref($parent_background) eq 'Wx::Colour');

    my $stat = stat($file);
    my $mtime = $stat->mtime();
    my $image = $cache->get("$file-$x-$y-$caption-$ibg-$blowup-$pbg-$mtime");
    if (!$image)
    {
    	my $radius = 10;
    	my $svg = <<SVG;
<svg width="$x" height="$y" viewBox="0 0 $x $y">
   <rect x="0" y="0" width="$x" height="$y" ry="$radius"
       style="stroke: none; fill: $ibg;"/>
</svg>
SVG
    	my $background=Image::Magick->new(magick => 'svg');
    	$background->Set('background' => $pbg);
    	$background->blobtoimage($svg);
        
    	my ($textheight, $textwidth) = (0,0);
    	if ($caption)
    	{
    	    my $pt = 20;
    	    do {
    		(undef, undef, undef, undef, $textwidth, $textheight, undef) =
    		    $background->QueryFontMetrics(text => $caption, font => 'Comic-Sans-MS', pointsize => $pt, gravity => 'South');
    		    $pt--;
    		} until ($textwidth < $x) && ($textheight < $y/5);
    	    $background->Annotate(text => $caption, font => 'Comic-Sans-MS', pointsize => $pt, gravity => 'South');
    	}
        
    	# Read the actual image
    	my $img = Image::Magick->new;
        
    	my $rc = $img->Read($file);
    	carp "Can't read $file: $rc" if $rc;
        # wmf files have a white background color by default
        # if we can't get the matte color for the image, we assume
        # that white can be used as the transparent color...
    	$img->Transparent(color => 'white') if (!$img->Get('matte') || $file =~ /wmf$/i);
    	my $w = $img->Get('width');
    	my $h = $img->Get('height');
    	my $ch = $textheight;
    	if (($w > $x) || ($h > ($y-$ch)))
    	{
    	    my ($newx, $newy) = ($w, $h);
    	    if ($w > $x)
    	    {
    		my $factor = $w/$x;
    		return wxNullBitmap if not $factor;
    		$newy = int($h/$factor);
    		($w,$h) = ($x, $newy);
    	    }
    	    if ($h > ($y-$ch))
    	    {
    		my $factor = $h/($y-$ch);
    		return wxNullBitmap if not $factor;
    		($w, $h) = (int($w/$factor),$y-$ch);
    	    }
    	    $img->Thumbnail(height => $h, width =>$w );
    	}
    	elsif ($blowup)
    	{
    	    # Do we really want to blow up images that are too small??
    	    my $factor = $w/$x;
    	    return wxNullBitmap if not $factor;
    	    my $newy = int($h/$factor);
    	    ($w,$h) = ($x, $newy);
    	    if ($h > ($y-$ch))
    	    {
    		my $factor = $h/($y-$ch);
    		return wxNullBitmap if not $factor;
    		($w, $h) = (int($w/$factor),$y-$ch);
    	    }
    	    $img->Resize(height => $h, width =>$w );
    	}
        
    	$img->Border(width  => int(($x - $img->Get('width'))/2) - $radius/2,
    		      height => int((($y-$textheight) - $img->Get('height'))/2) - $radius/2,
    		      fill   => $ibg);
    	
    	# Call the Composite method of the background image, with the logo image as an argument.
    	$background->Composite(image=>$img,compose=>'over', gravity => 'North');
    	$background->Set(quality=>100);
    	$background->Set(magick => 'png');
    	$image = $background->imagetoblob();
    	$cache->set("$file-$x-$y-$caption-$ibg-$blowup-$pbg-$mtime", $image);	
    	undef $background;
    	undef $img;
    }
    
    my $fh = IO::Scalar->new(\$image); 	 

    my $contenttype = 'image/png'; 
    return Wx::Bitmap->new(Wx::Image->newStreamMIME($fh,  $contenttype)) 
}

END
{
    undef $cache;
}

sub DrawCaption
{
    my ($x, $y, $caption, $background, $parent_background) = @_;

    confess "MaxX and MaxY should be positive" if $x < 1 || $y < 1;
    
    my $newbmp = Wx::Bitmap->new($x, $y);
    my $tmpdc = Wx::MemoryDC->new();
    $tmpdc->SelectObject($newbmp);

    my $bgbr = Wx::Brush->new($parent_background, wxSOLID);
    $tmpdc->SetBrush($bgbr); 
    $tmpdc->SetBackground($bgbr);
    $tmpdc->Clear();

    my $bg = $parent_background;
    if (defined $background)
    {
        if (ref($background)=~/ARRAY/)
        {
            $bg = Wx::Colour->new(@$background);
        }
        else
        {
            $bg = $background;
        }
        my $br = Wx::Brush->new($bg, wxSOLID);
        my $pen = Wx::Pen->new($bg, 1, wxSOLID);
        $tmpdc->SetBrush($br);
	$tmpdc->SetPen($pen);
	$tmpdc->DrawRoundedRectangle(1,1,$x-1,$y-1, 10);
    }

    my $pt = 72;
    my ($font, $w, $h);
    do
    {
	$font = Wx::Font->new(  $pt,                # font size
				wxSWISS,            # font family
				wxNORMAL,           # style
				wxNORMAL,           # weight
				0,                  
				'Comic Sans MS');   # face name
	($w, $h, undef, undef) = $tmpdc->GetTextExtent($caption, $font);
	$pt= $pt > 24 ? $pt - 4 : $pt-1;
    } until (($w<$x) && ($h<$y) || $pt < 5);
    $tmpdc->SetTextForeground(wxBLACK);
    $tmpdc->SetTextBackground($bg);
    $tmpdc->SetFont($font);
    $tmpdc->DrawText($caption, int(($x-$w)/2), int(($y-$h)/2));

    return $newbmp;
}

1;

__END__

=pod

=head1 NAME

AAC::Pvoice::Bitmap - Easily create resized bitmaps with options

=head1 SYNOPSIS

  use AAC::Pvoice::Bitmap;
  my $bitmap = AAC::Pvoice::Bitmap->new('image.jpg',        #image
                                        100,                #maxX
					100,                #maxY
					'This is my image', #caption
					wxWHITE,            #background
					1);                 #blowup?

=head1 DESCRIPTION

This module is a simpler interface to the Wx::Bitmap to do things with
images that I tend to do with almost every image I use in pVoice applications.

It's a subclass of Wx::Bitmap, so you can call any method that a Wx::Bitmap
can handle on the resulting AAC::Pvoice::Bitmap.

=head1 USAGE

=head2 new(image, maxX, maxY, caption, background, blowup, parentbackground)

This constructor returns a bitmap (useable as a normal Wx::Bitmap), that
has a size of maxX x maxY, the image drawn into it as large as possible.
If blowup has a true value, it will enlarge the image to try and match
the maxX and maxY. Any space not filled by the image will be the
specified background colour. A caption can be specified to draw under the
image.

If the image doesn't exist, it will draw a large questionmark and warn
the user.

=over 4

=item image

This is the path to the image you want to have.

=item maxX, maxY

These are the maximum X and Y size of the resulting image. If the original
image is larger, it will be resized (maintaining the aspect ratio) to
match these values as closely as possible. If the 'blowup' parameter is
set to a true value, it will also enlarge images that are smaller than
maxX and maxY to get the largest possible image within these maximum values.

=item caption

This is an optional caption below the image. The caption's font is Comic Sans MS
and will have a pointsize that will make the caption fit within the maxX
of the image. The resulting height of the caption is subtracted from the
maxY

=item background

This is the background of the image, specified as either a constant
(i.e. wxWHITE) or as an arrayref of RGB colours (like [128,150,201] ).

=item blowup

This boolean parameter determines whether or not images that are smaller
than maxX and maxY should be blown up to be as large as possible within
the given maxX and maxY.

=item parentbackground

This is the background of the parent of this bitmap, which is the colour to
be used outside of the round cornered background.

=back

=head1 BUGS

probably a lot, patches welcome!


=head1 AUTHOR

	Jouke Visser
	jouke@pvoice.org
	http://jouke.pvoice.org

=head1 COPYRIGHT

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.


=head1 SEE ALSO

perl(1), Wx

=cut

lib/AAC/Pvoice/Dialog.pm  view on Meta::CPAN

package AAC::Pvoice::Dialog;
use strict;
use warnings;

our $VERSION     = sprintf("%d.%02d", q$Revision: 1.1 $=~/(\d+)\.(\d+)/);

use Wx qw(:everything);
use Wx::Event qw(EVT_CLOSE);

use base 'Wx::Dialog';

sub new
{
    my $class = shift;
    my $self = $class->SUPER::new(@_);
    my ($x, $y) = ($self->GetClientSize->GetWidth,
                   $self->GetClientSize->GetHeight);

    $self->{margin}           = 10;
    $self->{ITEMSPACING}      = 4;
    $self->{selectionborder}  = 3;
    $self->{backgroundcolour} = Wx::Colour->new(220,220,220);
    $self->SetBackgroundColour(wxWHITE);

    $self->{panel} = AAC::Pvoice::Panel->new(   $self,                 # parent
                                                -1,                    # id
                                                [$self->{margin},
                                                 $self->{margin}],     # position
                                                [$x-2*$self->{margin},
                                                 $y-2*$self->{margin}],# size
                                                wxNO_3D|wxWANTS_CHARS,               # style
                                                1,                     # disabletextrow 
                                                $self->{ITEMSPACING},  # rowspacing
                                                $self->{selectionborder}, # selectionborderwidth
                                                1);                     # disabletitle
    
    $self->{panel}->BackgroundColour($self->{backgroundcolour});
    $self->WarpPointer($self->{margin}+1,$self->{margin}+1);
    $self->SetFocus();
    EVT_CLOSE($self, \&OnClose);
    return $self;
}

sub Append
{
    my $self = shift;
    $self->{panel}->Append(@_);
}

sub OnClose
{
    my $self = shift;
    $self->Destroy();
}

sub Show
{
    my $self = shift;
    my $bool = shift;
    $self->{panel}->Finalize();
    $self->SUPER::Show($bool);    
}

sub ShowModal
{
    my $self = shift;
    $self->{panel}->Finalize();
    $self->SUPER::ShowModal();
}

1;

__END__


=pod

=head1 NAME

AAC::Pvoice::Dialog - A class similar to Wx::Dialog, with added accessibility

=head1 SYNOPSIS

  use AAC::Pvoice::Dialog;

=head1 DESCRIPTION

This subclass of Wx::Dialog knows all of Wx::Dialog's methods. Therefore
only two methods are described below. The constructor (which is also similar
to the Wx::Dialog constructor) and the (added) Append method.

=head1 USAGE

=head2 new(parent, id, caption, [x,y], [w,h])

This is the constructor for a new AAC::Pvoice::Dialog. It is similar to calling
the constructor of a Wx::Dialog.

=head2 Append

This method is similar to AAC::Pvoice::Panel's Append method and allows you
to append a 'row' (or any Wx::Window subclass) to the Dialog.

=head1 BUGS

probably a lot, patches welcome!


=head1 AUTHOR

	Jouke Visser
	jouke@pvoice.org
	http://jouke.pvoice.org

=head1 COPYRIGHT

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.


=head1 SEE ALSO

perl(1), Wx

=cut

lib/AAC/Pvoice/EditableRow.pm  view on Meta::CPAN

package AAC::Pvoice::EditableRow;
use strict;
use warnings;

use Wx qw(:everything);
use Wx::Perl::Carp;
use Wx::Event qw(   EVT_BUTTON );
use AAC::Pvoice::Bitmap;
use base qw(Wx::Panel);

our $VERSION     = sprintf("%d.%02d", q$Revision: 1.4 $=~/(\d+)\.(\d+)/);

#----------------------------------------------------------------------
sub new
{
    my $class = shift;
    my ($parent,$maxitems,$items,$wxPos,$wxSize, $itemmaxX, $itemmaxY, $itemspacing, $background, $style,$name) = @_;
    $wxPos ||= wxDefaultPosition;
    $wxSize ||= wxDefaultSize;
    $style ||= 0;
    $name ||= '';
    my $self = $class->SUPER::new($parent, -1, $wxPos, $wxSize, $style, $name);

    $self->{maxitems} = $maxitems;
    $self->{itemspacing}=$itemspacing;

    # Create a new panel
    my $sizer = Wx::GridSizer->new(1,0);
    $self->{items} = [];
    $self->{actions} = [];

    my ($maxX, $maxY) = ($itemmaxX, $itemmaxY);

    # Add the defined keys for this row
    for (@$items)
    {
        my ($id, $img, $sub) = @$_;
        my $button = Wx::BitmapButton->new
                                    ($self,             # parent
                                     $id,               # id
                                     $img,              # image
                                     wxDefaultPosition, # position
                                     [$maxX+3, $maxY+3],     	# size
                                     wxBU_AUTODRAW);  # style
        $button->SetBackgroundColour($background);
        $sizer->Add($button, 0, wxALIGN_CENTRE|wxALL, $self->{itemspacing});
        push @{$self->{items}}, $button;
	EVT_BUTTON($self, $id, $sub);
    }
    my $totalitems = scalar(@$items);
    $self->{totalitems} = scalar(@{$self->{items}});
    $self->SetBackgroundColour($background);
    $self->SetSizer($sizer);
#    $self->SetAutoLayout(1);
    $sizer->Fit($self);
    return $self;
}

1;

__END__

=head1 NAME

AAC::Pvoice::EditableRow - Draw a pVoice row where items can be edited directly

=head1 SYNOPSIS

  use AAC::Pvoice::EditableRow


=head1 DESCRIPTION

This module is currently only useful for the pVoice application. It needs
to be refactored, maybe it'll disappear completely

=head1 USAGE

(todo)

=head1 BUGS

probably a lot, patches welcome!


=head1 AUTHOR

	Jouke Visser
	jouke@pvoice.org
	http://jouke.pvoice.org

=head1 COPYRIGHT

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.


=head1 SEE ALSO

perl(1), Wx

lib/AAC/Pvoice/Input.pm  view on Meta::CPAN

package AAC::Pvoice::Input;
use strict;
use warnings;

use Wx qw(:everything);
use Wx::Perl::Carp;
BEGIN
{
    use Device::ParallelPort;
    if ($^O eq 'MSWin32')
    {
        require Device::ParallelPort::drv::win32;
    }
    else
    {
        require Device::ParallelPort::drv::parport;
    }
}
use Wx::Event qw(   EVT_TIMER
                    EVT_CHAR
                    EVT_MOUSE_EVENTS);
our $VERSION     = sprintf("%d.%02d", q$Revision: 1.12 $=~/(\d+)\.(\d+)/);

sub new
{
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};
    bless $self, $class;
    $self->{window} = shift;

    # We get the configuration from the Windows registry
    # If it's not initialized, we provide some defaults
    $self->{window}->{config} = Wx::ConfigBase::Get || croak "Can't get Config";

    # Get the input-device
    # icon   = mouse left/right buttons
    # adremo = electric wheelchair adremo
    # keys   = keystrokes
    $self->{window}->{Device} = $self->{window}->{config}->Read('Device',    'icon');

    $self->{window}->{Interval}          = $self->{window}->{config}->ReadInt('Interval', 10);
    $self->{window}->{Buttons}           = $self->{window}->{config}->ReadInt('Buttons',   2);
    $self->{window}->{OneButtonInterval} = $self->{window}->{config}->ReadInt('OneButtonInterval',    2000);

    $self->_initmonitor if $self->{window}->{Device} eq 'adremo';
    $self->_initautoscan if $self->{window}->{config}->ReadInt('Buttons') == 1;
    $self->_initkeys;
    $self->_initicon;

    $self->StartMonitor if $self->{window}->{Device} eq 'adremo';
    $self->StartAutoscan if $self->{window}->{config}->ReadInt('Buttons') == 1;

    return $self;
}

sub newchild
{
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};
    bless $self, $class;
    $self->{window} = shift;

    # We get the configuration from the Windows registry
    # If it's not initialized, we provide some defaults
    $self->{window}->{config} = Wx::ConfigBase::Get || croak "Can't get Config";

    # Get the input-device
    # icon   = mouse left/right buttons
    # adremo = electric wheelchair adremo
    # keys   = keystrokes
    $self->{window}->{Device} = $self->{window}->{config}->Read('Device',    'icon');

    $self->_initkeys;
    $self->_initicon;

    return $self;
}

sub _initkeys
{
    my $self = shift;
    EVT_CHAR($self->{window}, \&_keycontrol)
        if $self->{window}->{config}->Read('Device') eq 'keys';
}

sub _initicon
{
    my $self = shift;
    EVT_MOUSE_EVENTS($self->{window}, \&_iconcontrol)
        if $self->{window}->{config}->Read('Device') eq 'icon';
}

sub _initmonitor
{
    my $self = shift;
    # The event for the adremo device
    $self->{window}->{adremotimer} = Wx::Timer->new($self->{window},my $tid = Wx::NewId());
    EVT_TIMER($self->{window}, $tid, \&_monitorport);
}

sub _initautoscan
{
    my $self = shift;
    $self->{window}->{onebuttontimer} = Wx::Timer->new($self->{window},my $obtid = Wx::NewId());
    EVT_TIMER($self->{window}, $obtid, sub{my $self = shift; $self->{input}->{next}->() if $self->{input}->{next}});
}

sub StartMonitor
{
    my $self = shift;
    $self->{window}->{adremotimer}->Start($self->{window}->{Interval}, 0) # 0 is continuous
                                                if $self->{window}->{adremotimer};
}

sub QuitMonitor
{
    my $self = shift;
    # stop the timer for the port monitor
    $self->{window}->{adremotimer}->Stop() if  $self->{window}->{adremotimer} && $self->{window}->{adremotimer}->IsRunning;
}

sub StartAutoscan
{
    my $self = shift;
    $self->{window}->{onebuttontimer}->Start($self->{window}->{OneButtonInterval}, 0)  # 0 is continuous
                                                if $self->{window}->{onebuttontimer};
}

sub QuitAutoscan
{
    my $self = shift;
    $self->{window}->{onebuttontimer}->Stop() if  $self->{window}->{onebuttontimer} && $self->{window}->{onebuttontimer}->IsRunning;
}

sub PauseMonitor
{
    my $self = shift;
    my $bool = shift;
    return unless $self->{window}->{config}->Read('Device') eq 'adremo';
    $self->QuitMonitor if $bool;
    $self->StartMonitor unless $bool;
}

sub PauseAutoscan
{
    my $self = shift;
    my $bool = shift;
    return unless $self->{window}->{config}->ReadInt('Buttons') == 1;
    $self->QuitAutoscan if $bool;
    $self->StartAutoscan unless $bool;
}

sub Pause
{
    my $self = shift;
    $self->{pause} = shift;
}

sub GetDevice
{
    my $self = shift;
    return $self->{window}->{config}->Read('Device');
}

sub SetupMouse
{
    my $self = shift;
    my ($window, $subgetfocus, $subup, $sublosefocus) = @_;

    if ($self->{window}->{config}->Read('Device') eq 'mouse')
    {
        EVT_MOUSE_EVENTS($window, sub { my ($self, $event) = @_;
                                        &$subup         if $event->LeftUp;
                                        &$sublosefocus  if $event->Leaving;
                                        &$subgetfocus   if $event->Entering;
                                      });
    }


}

sub Next
{
    my $self = shift;
    my $sub = shift;
    $self->{next} = $sub;
}

sub Select
{
    my $self = shift;
    my $sub = shift;
    $self->{select} = $sub;
}

sub _keycontrol
{
    # BEWARE: $self is the window object this event belongs to
    my ($self, $event) = @_;
    return if $self->{pause};
    $self->{input}->{select}->() if ($event->GetKeyCode == $self->{config}->ReadInt('SelectKey', WXK_RETURN)) || (uc(chr($event->GetKeyCode)) eq uc(chr($self->{config}->ReadInt('SelectKey'))));
    $self->{input}->{next}->()   if (( ($event->GetKeyCode == $self->{config}->ReadInt('NextKey', WXK_SPACE)) ||
                                       (uc(chr($event->GetKeyCode)) eq uc(chr($self->{config}->ReadInt('NextKey'))))) and
                                     (not $self->{config}->ReadInt('Buttons') == 1));
}

sub _iconcontrol
{
    # BEWARE: $self is the window object this event belongs to
    my ($self, $event) = @_;
    return if $self->{pause};
    $self->{input}->{select}->() if $event->LeftUp;
    $self->{input}->{next}->()   if $event->RightUp &&
                                    not $self->{config}->ReadInt('Buttons') == 1;
}

#----------------------------------------------------------------------
# This sub is used to monitor the parallel port for the adremo device
sub _monitorport
{
    # BEWARE: $self is the wxWindow subclass the timer
    # belongs to!
    my ($self, $event) = @_;
    # do nothing if the device is not adremo or
    # if we're already running
    return if ($self->{monitorrun}                           || 
               (not $self->{input}->{next})                  || 
               (not $self->{input}->{select})                ||
               $self->{pause});
    # set the flag that we're checking the port
    $self->{monitorrun} = 1;
    $self->{pp} = Device::ParallelPort->new() if not $self->{pp};
    my $curvalue = $self->{pp}->get_status();
    if (not defined $curvalue)
    {
        # clear the flag that we're checking the port and return
        $self->{monitorrun} = 0;
        return
    }
    $self->{lastvalue} = 0 if not exists $self->{lastvalue};
    # if we detect a change...
    if ($curvalue != $self->{lastvalue})
    {
        unless ($curvalue & 0x40)
        {
            # if bit 6 is off it's a headmove to the right
            # which will indicate a Next() event unless we're in
            # one button mode
            $self->{input}->{next}->() unless $self->{config}->ReadInt('Buttons') == 1;
        }
        if ($curvalue & 0x80)
        {
            # if bit 7 is on (this bit is inverted), it's a headmove to the left
            # which will indicate a Select() event.
            $self->{input}->{select}->();
        }
    }
    # the current value becomes the last value
    $self->{lastvalue} = $curvalue if $curvalue;

    # clear the flag that we're checking the port
    $self->{monitorrun} = 0;
}


1;

__END__

=head1 NAME

AAC::Pvoice::Input - A class that handles the input that controls a pVoice-like application

=head1 SYNOPSIS

  # this module will normally not be called directly. It's called from
  # AAC::Pvoice::Panel by default


=head1 DESCRIPTION

AAC::Pvoice::Input allows one or two button operation of an AAC::Pvoice based
application.
The module uses Device::ParallelPort, so it should be able to run
on Win32 as well as Linux platforms.

=head1 USAGE

=head2 new($window)

This constructor takes the window (AAC::Pvoice::Panel typically) on which
the events and timer will be called as a parameter.
If the configuration (read using Wx::ConfigBase::Get) has a key called
'Device' (which can be set to 'icon', 'keys' , 'mouse' or 'adremo') is set to 'adremo', it
will start polling the parallel port every x milliseconds, where x is the
value of the configuration key 'Interval'. This setting is only useful if you connect
an "Adremo" electrical wheelchair to the parallel port of your PC (for more
information see http://www.adremo.nl).
If the key 'Device' is set to 'icon' it will respond to the left and right
mouse button, and if it's set to 'keys' it will respond to the configuration
keys 'SelectKey' and 'NextKey' (which are the keyboard codes for the 'select'
and 'next' events respectively.

AAC::Pvoice::Input has the ability to operate with either one or two buttons.
If you want to use only one button, you need to set the configuration key "Buttons"
to 1, and it will automatically invoke the subroutine you pass to Next() 
at an interval of the value set in the configuration key OneButtonInterval (set in milliseconds).

The default for is to operate in two button mode, and if OneButtonInterval is not 
set, it will use a default of 2000 milliseconds if "Buttons"  is set to 1.

=head2 newchild($window)

This semi-constructor takes the window (usually a child of the panel you
passed to the new() constructor, on which the events will be called as a parameter.
It doesn't start the timers for polling the parallel port and automatic
invocation of the Next() subroutine, because those timers otherwise would
be started multiple times.
Apart from starting those timers, this method works exactly like the new()

=head2 Next(sub)

This method takes a coderef as parameter. This coderef will be invoked when
the 'Next' event happens.

If the Device (see 'new') is set to 'icon', and a right mousebutton is
clicked, a 'Next' event is generated.
If the Device is set to 'adremo' and the headsupport of the wheelchair
is moved to the right, that will also generate a 'Next' event.
If the Device is set to 'keys' and a key is pressed that corresponds with the 
keycode set in the 'NextKey', this will generate a 'Next' event too.

=head2 Select(sub)

This method takes a coderef as parameter. This coderef will be invoked when
the 'Select' event happens.

If the Device (see 'new') is set to 'icon', and a left mousebutton is
clicked, a 'Select' event is generated.
If the Device is set to 'adremo' and the headsupport of the wheelchair
is moved to the left, that will also generate a 'Select' event.
If the Device is set to 'keys' and a key is pressed that corresponds with the 
keycode set in the 'SelectKey', this will generate a 'Select' event too.

=head2 GetDevice

This method will return the value of the configuration key called 'Device'

=head2 SetupMouse($window, $subgetfocus, $subup, $sublosefocus)

This method is used to setup a button for normal mouse input (when
configuration key 'Device' is set to 'mouse'). It takes the wxWindow
(typically a Wx::BitmapButton) that should respond to this way of
input as the first parameter.
$subgetfocus is the coderef that should be invoked when the mousecursor
hovers over this $window (EVT_ENTER).
$subup is the coderef that should be invoked when the left mousebutton
is released (EVT_LEFT_UP).
$sublosefocus is the coderef that should be invoked when the $window
loses focus (EVT_LEAVE).

=head2 StartMonitor

This method will start polling the the parallel port for input of the Adremo
Electrical Wheelchair.

=head2 QuitMonitor

This method will stop the timer that monitors the parallel port.

=head2 PauseMonitor($bool)

This method will pause ($bool is set to 1) or restart ($bool is set to 0)
the timer that monitors the parallel port.

=head2 StartAutoscan

This method will start the timer that invokes the Next() event every n milliseconds.

=head2 QuitAutoscan

This method will stop the timer that invokes the Next() method.

=head2 PauseAutoscan($bool)

This method will pause ($bool is set to 1) or restart ($bool is set to 0)
the timer that invokes the Next() method.



=head1 BUGS

probably a lot, patches welcome!


=head1 AUTHOR

	Jouke Visser
	jouke@pvoice.org
	http://jouke.pvoice.org

=head1 COPYRIGHT

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.


=head1 SEE ALSO

perl(1), Wx

lib/AAC/Pvoice/Panel.pm  view on Meta::CPAN

package AAC::Pvoice::Panel;
use strict;
use warnings;

our $VERSION     = sprintf("%d.%02d", q$Revision: 1.15 $=~/(\d+)\.(\d+)/);

use Wx qw(:everything);
use Wx::Perl::Carp;
use Wx::Event qw(EVT_PAINT EVT_UPDATE_UI);
use base qw(Wx::Panel);

#----------------------------------------------------------------------
sub new
{
    my $class = shift;
    $_[2] ||= wxDefaultPosition;
    $_[3] ||= wxDefaultSize;
    $_[4] ||= wxTAB_TRAVERSAL;
    my $self = $class->SUPER::new(@_[0..4]);

    $self->SetBackgroundColour(wxWHITE);

    $self->{parent}         = $_[0];
    $self->{position}       = $_[2];
    $self->{size}           = $_[3];
    $self->{disabletextrow} = $_[5] || 0;
    $self->{itemspacing}    = $_[6] || 0;
    $self->{selectionborder}= $_[7] || int($self->{itemspacing}/2)||1;
    $self->{disabletitle}   = $_[8] || 0;
    $self->{tls} = Wx::FlexGridSizer->new(0,1);
    $self->{totalrows}   = 0;
    $self->{lastrow}     = 0;
    $self->{currentpage} = 0;
    $self->{unfinished}  = 1;
    
    $self->RoundCornerRadius(10);

    my ($x, $y);

    # to get the right dimensions for the items, we maximize the
    # frame, show it, get the dimensions, and hide it again
    if (ref($self->{parent}) =~ /Frame/)
    {
	if ($self->{parent}->IsMaximized)
	{
	    ($x, $y) = @{$self->{size}};
	}
	else
	{
	    $self->{parent}->Maximize(1);
	    $self->{parent}->Show(1);
	    ($x, $y) = ( $self->GetSize()->GetWidth(),
			 $self->GetSize()->GetHeight() );
	    $self->{parent}->Show(0);
	}
    }
    else
    {
	# if our parent isn't a frame, we're not able to maximize
	# it, so we just get the dimensions of the parent
	($x, $y) = @{$self->{size}};
    }
    $self->{realx} = $x;
    $self->{realy} = $y;
    $self->xsize($x);
    $self->ysize($y);
    unless ($self->{disabletitle})
    {
	# to be able to calculate the useable y-size, we need to add the
	# title and get its height. Since we don't know what the title
	# will be, we'll simple draw an empty title.
	$self->TitleFont(Wx::Font->new( 18,                 # font size
					wxDECORATIVE,       # font family
					wxNORMAL,           # style
					wxNORMAL,           # weight
					0,                  
					'Comic Sans MS',    # face name
					wxFONTENCODING_SYSTEM)) unless $self->TitleFont;
	$self->AddTitle('');
	my $usableysize = $y - 2*$self->{title}->GetSize()->GetHeight();
	# If we want to use a textrow, we have to subtract another 60
	# pixels from the y size, since the textrow is always 60 pixels high.
	$usableysize-=60 unless $self->{disabletextrow};
	$self->ysize($usableysize);
    }
    # set the default colours...these can of course be changed...
    $self->SelectColour(Wx::Colour->new(255,131,131));
    $self->BackgroundColour(Wx::Colour->new(220,220,220));
    
    $self->SetSizer($self->{tls});
    $self->SetAutoLayout(1);

    $self->{displaytextsave} = [];
    $self->{speechtextsave}  = [];
    
    # Initialize the input stuff
    $self->{input} = AAC::Pvoice::Input->new($self);
    $self->{input}->Next(  sub{$self->Next});
    $self->{input}->Select(sub{$self->Select});
    
    $self->{rowcolumnscanning} = ($self->{input}->GetDevice ne 'mouse');
    EVT_PAINT($self, \&OnPaint);
    EVT_UPDATE_UI($self, $self, \&OnPaint);
    return $self;
}

sub SetEditmode
{
    my $self = shift;
    $self->{editmode} = shift;
}

sub OnPaint
{
    my ($self, $event) = @_;
    $self->{setselection} = 1;
    my $dc = Wx::PaintDC->new($self);
    $self->SetBackgroundColour($self->{parent}->GetBackgroundColour);
    $self->DrawBackground($dc);
    if ($self->{rowcolumnscanning} && not $self->{editmode})
    {
	$dc = Wx::WindowDC->new($self->{selectedwindow}->GetParent);
	$self->DrawBorder($dc);
    }
    $event->Skip;
}

sub DrawBorder
{
    my $self = shift;
    my $dc = shift;
    my $window = $self->{selectedwindow};
    my ($x, $y) = $window->GetPositionXY;
    my $size = $window->GetSize;
    my ($xsize, $ysize) = ($size->GetWidth, $size->GetHeight);
    $dc->BeginDrawing;
    $dc->SetBrush(wxTRANSPARENT_BRUSH);
    $dc->SetPen(Wx::Pen->new($self->{setselection} ? $self->SelectColour :
			                         $self->BackgroundColour, $self->{selectionborder}, wxSOLID));
    $dc->DrawRoundedRectangle($x-($self->{itemspacing}/2-1), $y-($self->{itemspacing}/2-1), $xsize+($self->{itemspacing}/2+1), $ysize+($self->{itemspacing}/2+1), $self->RoundCornerRadius);
    $dc->EndDrawing;
}

sub SetSelectionBorder
{
    my $self = shift;
    $self->{selectedwindow} = shift;
    $self->{setselection} = 1;
    my $dc = Wx::WindowDC->new($self->{selectedwindow}->GetParent);
    $self->DrawBorder($dc);
}

sub SetNormalBorder
{
    my $self = shift;
    $self->{selectedwindow} = shift;
    $self->{setselection} = 0;
    my $dc = Wx::WindowDC->new($self->{selectedwindow}->GetParent);
    $self->DrawBorder($dc);
}

sub RoundCornerRadius
{
    my $self = shift;
    $self->{radius} = shift || $self->{radius};
    return $self->{radius};
}

sub xsize
{
    my $self = shift;
    $self->{xsize} = shift || $self->{xsize};
    return $self->{xsize}-2*$self->RoundCornerRadius; 
}

sub ysize
{
    my $self = shift;
    $self->{ysize} = shift || $self->{ysize};
    return $self->{ysize}-2*$self->RoundCornerRadius;
}

sub lastrow
{
    my $self = shift;
    return $self->{lastrow};
}


sub SelectColour
{
    my $self = shift;
    $self->{selectcolour} = shift || $self->{selectcolour};
    return $self->{selectcolour};
}

sub BackgroundColour
{
    my $self = shift;
    $self->{backgroundcolour} = shift || $self->{backgroundcolour};
    return $self->{backgroundcolour};
}

sub DrawBackground
{
    my $self = shift;
    my $dc = shift;
    $dc->SetBrush(Wx::Brush->new($self->BackgroundColour, wxSOLID));
    $dc->SetPen(Wx::Pen->new($self->BackgroundColour, 1, wxSOLID));
    $dc->DrawRoundedRectangle(0,0,$self->{realx}, $self->{realy}, $self->RoundCornerRadius);
}

sub AddTitle
{
    my ($self, $title) = @_;
    return if $self->{disabletitle};
    my $titleupdate = exists $self->{title};
    if ($titleupdate)
    {
	$self->{tls}->Remove($self->{title});
    }
    # Create the TextControl
    $self->{title} = Wx::StaticText->new(   $self,         
                                            -1,             
                                            $title,
                                            wxDefaultPosition,
                                            wxDefaultSize,
                                            wxALIGN_CENTRE);
    $self->TitleFont();
    # Don't use 'Add' here...the title should be on top!!
    $self->{tls}->Prepend($self->{title},0, wxALIGN_CENTRE, 0);
}

sub TitleFont
{
    my $self = shift;
    $self->{titlefont} = shift || $self->{titlefont};
    return if not $self->{titlefont};
    $self->{title}->SetFont($self->{titlefont}) if $self->{title};
    return $self->{titlefont};
}

sub Append
{
    my $self = shift;
    my $row = shift;
    my $unselectable = shift;
    $self->{tls}->Add($row,                 # what to add
                      0,                    # unused
                      wxALIGN_CENTRE,       # style
                      0);                   # padding

    # setup the input event handling unless we're in editmode
    unless ($self->{editmode})
    {
	$row->{input} = AAC::Pvoice::Input->newchild($row);
	$row->{input}->Next(  sub{$self->Next});
	$row->{input}->Select(sub{$self->Select});
	my $index=0;
	foreach my $child ($row->GetChildren)
	{
	    $child->{input} = AAC::Pvoice::Input->newchild($child);
	    $child->{input}->Next(  sub{$self->Next});
	    $child->{input}->Select(sub{$self->Select});
	    if ((defined $row->{ids}->[$index]) && ($child->GetId == $row->{ids}->[$index]))
	    {
		my $action = $row->{actions}->[$index];
		$self->{input}->SetupMouse($child, sub{$self->SetSelectionBorder($child)}, $action, sub{$self->SetNormalBorder($child)});
		$index++;
	    }
	}
    }

    $self->{totalrows}++ if not $unselectable;
    $self->{lastrow}++;
    push @{$self->{rows}}, $row if not $unselectable;
    push @{$self->{unselectablerows}}, $row if $unselectable;
}

sub PauseInput
{
    my $self = shift;
    my $bool = shift;
    $self->{input}->PauseMonitor($bool);
    $self->{input}->PauseAutoscan($bool);
    $self->{input}->Pause($bool);
}

sub Clear
{
    my $self = shift;
    $self->{tls}->Remove($_) for (0..$self->{lastrow});
    foreach my $row (@{$self->{rows}})
    {
	$_->Destroy for $row->GetChildren();
	$row->Destroy
    }
    $_->Destroy for @{$self->{unselectablerows}};
    $self->{text}->Destroy if exists $self->{text};
    $self->{title}->Destroy if exists $self->{title};
    $self->{rows} = [];
    $self->{unselectablerows} = [];
    $self->SUPER::Clear();
    $self->{totalrows} = 0;
    $self->{lastrow} = 0;
    $self->Refresh;
}

sub Finalize
{
    my $self = shift;
    my $dc = Wx::WindowDC->new($self);
    $self->DrawBackground($dc);

    unless ($self->{disabletextrow})
    { 
	# Create the TextControl
	my $font = Wx::Font->new(  24,             # font size
				   wxSWISS,        # font family
				   wxNORMAL,       # style
				   wxNORMAL,       # weight
				   0,
				   'Comic Sans MS',# face name
				   wxFONTENCODING_SYSTEM);
	$font->SetUnderlined(1);
	$self->{ta} = Wx::TextAttr->new( Wx::Colour->new(0,0,0),      # textcol
					 Wx::Colour->new(255,255,255),# backgr.
					 $font);                      # font
	my $rowsizer = Wx::GridSizer->new(1,0);
	$self->{text} = Wx::TextCtrl->new( $self,            # parent
					   -1,               # id
					   '',               # text
					   wxDefaultPosition,# position
					   [4*($self->{realx}/5),60], # size
					   wxTE_RICH|
					   wxTE_MULTILINE);  # style
	# set the text-attributes
	$self->{text}->SetDefaultStyle($self->{ta});
	$rowsizer->Add($self->{text},          # what to add
		       0,                      # unused
		       wxALIGN_CENTRE|wxALL,   # style
		       $self->{itemspacing});  # padding
	$self->{tls}->Add($rowsizer, 0, wxALIGN_CENTRE, 0);
	$self->{textrowsizer} = $rowsizer;
    
	$self->{text}->SetValue(my $x = $self->RetrieveText);
	$self->{text}->SetStyle(0, length($self->{text}->GetValue), $self->{ta});
	$self->{text}->Refresh(); # Added to test it on the Mercury...added text
				  # isn't visible there...
    }    
    $self->{title}->SetBackgroundColour($self->BackgroundColour) unless $self->{disabletitle};

    $self->{tls}->AddGrowableCol(0);
    $self->Layout;

    # Select the first row
    $self->{selectedrow} = 0;
    $self->{selecteditem} = 0;
    $self->SetSelectionBorder($self->{rows}->[$self->{selectedrow}]) if $self->{rowcolumnscanning} && not $self->{editmode};
    $self->{rowselection} = 1;
    $self->Refresh;
    $self->Update();
    $self->{unfinished} = 0;
}

sub Next
{
    my $self = shift;
    return if ($self->{editmode} || $self->{unfinished});
    $self->{input}->QuitAutoscan;
    if ($self->{rowselection})
    {
        $self->SetNormalBorder($self->{rows}->[$self->{selectedrow}]) if $self->{rowcolumnscanning};
        if ($self->{selectedrow} < ($self->{totalrows}-1))
        {
            $self->{selectedrow}++;
        }
        else
        {
            $self->{selectedrow} = 0;
        }
        $self->SetSelectionBorder($self->{rows}->[$self->{selectedrow}]) if $self->{rowcolumnscanning};
    }
    else
    {
        $self->SetNormalBorder($self->{rows}->[$self->{selectedrow}]->{items}->[$self->{selecteditem}]) if $self->{rowcolumnscanning};
        if ($self->{selecteditem} < ($self->{rows}->[$self->{selectedrow}]->{totalitems}-1))
        {
            $self->{selecteditem}++;
        }
        else
        {
            $self->{selecteditem} = 0;
        }
        $self->SetSelectionBorder($self->{rows}->[$self->{selectedrow}]->{items}->[$self->{selecteditem}]) if $self->{rowcolumnscanning};
    }
    $self->{input}->StartAutoscan;
}

sub Select
{
    my $self = shift;
    return if $self->{editmode};
    $self->{input}->QuitAutoscan;
    if (($self->{rowselection}) &&  (@{$self->{rows}->[$self->{selectedrow}]->{items}} == 1))
    {
	$self->{rowselection} = 0;
	$self->{selecteditem} = 0;
    }
    if ($self->{rowselection})
    {
        $self->SetNormalBorder($self->{rows}->[$self->{selectedrow}]) if $self->{rowcolumnscanning};
        $self->{rowselection} = 0;
        $self->{selecteditem} = 0;
        $self->SetSelectionBorder($self->{rows}->[$self->{selectedrow}]->{items}->[$self->{selecteditem}]) if $self->{rowcolumnscanning};
    }
    else
    {
        $self->SetNormalBorder($self->{rows}->[$self->{selectedrow}]->{items}->[$self->{selecteditem}]) if $self->{rowcolumnscanning};
        $self->SetSelectionBorder($self->{rows}->[$self->{selectedrow}]) if $self->{rowcolumnscanning};

        &{$self->{rows}->[$self->{selectedrow}]->{actions}->[$self->{selecteditem}]};
        $self->{rowselection} = 1;
    }
    $self->{input}->StartAutoscan;
}

sub ToRowSelection
{
    my $self = shift;
	return if $self->{editmode};
    $self->SetNormalBorder($self->{rows}->[$self->{selectedrow}]->{items}->[$self->{selecteditem}]) if $self->{rowcolumnscanning};
    $self->SetSelectionBorder($self->{rows}->[$self->{selectedrow}]) if $self->{rowcolumnscanning};
    $self->{rowselection} = 1;
}

sub DisplayAddText
{
    my $self = shift;
    push @{$self->{displaytextsave}}, $_[0];
    $self->{text}->AppendText($_[0]);
    $self->{text}->Refresh(); # Added to test it on the Mercury...added text
                              # isn't visible there...
}

sub SpeechAddText
{
    my $self = shift;
    push @{$self->{speechtextsave}}, $_[0];
}

sub RetrieveText
{
    my $self = shift;
    return wantarray ? @{$self->{displaytextsave}} : join('', @{$self->{displaytextsave}});
}

sub ClearText
{
    my $self = shift;
    $self->{displaytextsave}=[];
    $self->{speechtextsave}=[];
    $self->{text}->SetValue('');
    $self->{text}->Refresh(); # Added to test it on the Mercury...added text
                              # isn't visible there...
}

sub BackspaceText
{
    my $self = shift;
    pop @{$self->{displaytextsave}};
    pop @{$self->{speechtextsave}};
    $self->{text}->SetValue(my $x = $self->RetrieveText);
    $self->{text}->SetStyle(0, length($self->{text}->GetValue), $self->{ta});
    $self->{text}->Refresh(); # Added to test it on the Mercury...added text
                              # isn't visible there...
}

sub SpeechRetrieveText
{
    my $self = shift;
    return wantarray ? @{$self->{speechtextsave}} : join('', @{$self->{speechtextsave}});
}
    
1;

__END__

=pod

=head1 NAME

AAC::Pvoice::Panel - The base where a pVoice application consists of

=head1 SYNOPSIS

  use AAC::Pvoice::Panel;



=head1 DESCRIPTION



=head1 USAGE

=head2 new(parent, id, size, position, style, disabletextrow, itemspacing, selectionborderwidth, disabletitle)

This is the constructor for a new AAC::Pvoice::Panel. The first 5 parameters are
equal to the parameters for a normal Wx::Panel, see the wxPerl documentation
for those parameters.

=over 4

=item disabletextrow

This is s a boolean (1 or 0), which determines
if the text-input field at the bottom of the screen should be hidden or
not. Normally this inputfield will be shown (for an application like pVoice
this is normal, because that will contain the text the user is writing),
but for an application like pMusic this row is not nessecary, so it can be
disabled.

=item itemspacing

This is the spacing used between the rows that are appended.

=item selectionborderwidth

This is the width of the border around a selected row or a selected item.

=item disabletitle

This is also a boolean (1 or 0), which determines if the panel should
reserve space for a title. If disabletitle is set to 1, AddTitle won't have
any effect at all.

=back

=head2 SetEditmode($onoff)

This sets Editmode on or off (depending on $onoff to be a true or false value).
Editmode means that the typical pVoice input doesn't work anymore, and is
typically used in combination with AAC::Pvoice::EditableRow...

=head2 xsize

This returns the x-size of the panel in pixels.

=head2 ysize

This returns the y-size of the panel in pixels.

=head2 RoundCornerRadius

This sets the radius for the round corners that are used to draw the panel
background and to draw the selectionborder around rows and buttons.

=head2 lastrow

This retrieves the index of the last row that was added to the panel.

=head2 SelectColour(Wx::Colour)

This gets or sets the colour that indicates a selected row or selected item. It
takes a Wx::Colour (or a predefined colour constant) as a parameter.

=head2 BackgroundColour(Wx::Colour)

This gets or sets the normal backgroundcolour. It
takes a Wx::Colour (or a predefined colour constant) as a parameter.

=head2 AddTitle(title)

This method sets the title of the page and draws it on the AAC::Pvoice::Panel.
By default it uses the Comic Sans MS font at a size of 18pt. You can change
this using TitleFont.

=head2 TitleFont(Wx::Font)

This method gets or sets the Wx::Font used to write the Title.

=head2 Append(row, unselectable)

This method adds a row (AAC::Pvoice::Row or any subclass of Wx::Window) to
the panel. If this row shouldn't be selectable by the user, you should set
unselectable to 1. Omitting this parameter, or setting it to 0 makes the
row selectable.

=head2 Clear

This method clears the panel completely and destroys all objects on it.

=head2 Finalize

This method 'finalizes' the panel by creating the textinput row (if appliccable)
and setting up the selection of the first row. You always need to call
this method before being able to let the user interact with the pVoice panel.

=head2 Next

This method normally won't be called directly. It will highlight the 'next'
row (when we're in 'rowselection') or the next item inside a row (when
we're in 'columnselection')

=head2 Select

This method normally won't be called directly either. It will either 'select'
the row that is highlighted and thus go into columnselection, or, when we're
in columnselection, invoke the callback associated with that item and
go into rowselection again.

=head2 ToRowSelection

This method will remove the highlighting of an item (if nessecary) and highlight
the entire current row again and set rowselection back on.

=head2 DisplayAddText(text)

In pVoice-like applications there's a difference between 'displaytext' (which is
the text that the user actually is writing and which should be displayed on the
textrow) and the speech (phonetical) text (which is not displayed, but -if nessecary-
differs from the text as we would write it, so a speechsynthesizer sounds
better.

This method adds text to the displaytext. It is saved internally and displayed
on the textrow

=head2 SpeechAddText(text)

This method add text to the speechtext. It is saved internally and not displayed
on the textrow. See DisplayAddText for more information.

=head2 RetrieveText

This method returns the text that is added to the Displaytext since the
last 'ClearText'. In scalar context it returns it as one string, in listcontext
it returns the array of text as it was added.

=head2 SpeechRetrieveText

This method returns the text that is added to the Speechtext since the
last 'ClearText'. In scalar context it returns it as one string, in listcontext
it returns the array of text as it was added.

=head2 ClearText

This method clears both the displaytext and the speechtext. It also updates
the textrow to show nothing.

=head2 BackspaceText

This method removes the last text added to the speech *and* displaytext.
Make sure that both speechtext and displaytext have the same amount of
text added, because it just pops off the last item from both lists and
updates the textrow.

=head2 PauseInput($bool)

This method makes sure that the timers that are used for the input (using
AAC::Pvoice::Input) are paused if $bool is set to 1. If $bool is 0, they're
restarted.

=head1 BUGS

probably a lot, patches welcome!


=head1 AUTHOR

	Jouke Visser
	jouke@pvoice.org
	http://jouke.pvoice.org

=head1 COPYRIGHT

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.


=head1 SEE ALSO

perl(1), Wx

=cut

lib/AAC/Pvoice/Row.pm  view on Meta::CPAN

package AAC::Pvoice::Row;
use strict;
use warnings;

use Wx qw(:everything);
use Wx::Perl::Carp;
use AAC::Pvoice::Bitmap;
use base qw(Wx::Panel);

our $VERSION     = sprintf("%d.%02d", q$Revision: 1.5 $=~/(\d+)\.(\d+)/);
#----------------------------------------------------------------------
sub new
{
    my $class = shift;
    my ($parent,$maxitems,$items,
		$wxPos,$wxSize, $itemmaxX, $itemmaxY,
		$itemspacing, $background, $style,$name) = @_;
    my $self = $class->SUPER::new(  $parent,
				    Wx::NewId,
				    $wxPos  || wxDefaultPosition,
				    $wxSize || wxDefaultSize,
				    $style  || 0,
				    $name   || '');

    $self->{maxitems}    = $maxitems;

    my $sizer = Wx::GridSizer->new(1,0);
    $self->{items}   = [];
    $self->{actions} = [];
    
    my ($maxX, $maxY) = ($itemmaxX, $itemmaxY);

    # Add the defined keys for this row
    for (@$items)
    {
    	if (not defined $_)
    	{
            my $empty = Wx::BitmapButton->new(  $self, 
                                                Wx::NewId, 
                                                wxNullBitmap, 
                                                wxDefaultPosition, 
                                                [$maxX, $maxY],
                                                wxSUNKEN_BORDER);
            $empty->SetBackgroundColour($background);
    	    $sizer->Add($empty,0, wxALIGN_CENTRE|wxALL, $itemspacing);
            next;
    	}
        my ($id, $img, $sub) = @$_;
        my $button = Wx::BitmapButton->new ($self,             # parent
					    $id,               # id
					    $img,              # image
					    wxDefaultPosition, # position
					    [$maxX, $maxY],# size
					    wxSUNKEN_BORDER);  # style
        $button->SetBackgroundColour($background);
        $sizer->Add($button, 0, wxALIGN_CENTRE|wxALL, $itemspacing);
        push @{$self->{items}}, $button;
        push @{$self->{actions}}, $sub;
        push @{$self->{ids}}, $id;
    }
    my $totalitems = scalar(@$items);
    $self->{totalitems} = scalar(@{$self->{items}});
    for (0..($self->{maxitems} - $totalitems -1))
    {
	my $empty = Wx::BitmapButton->new(  $self, 
					    Wx::NewId, 
					    wxNullBitmap, 
					    wxDefaultPosition, 
					    [$maxX, $maxY],
					    wxSUNKEN_BORDER);
	$empty->SetBackgroundColour($background);
	$sizer->Add($empty,0, wxALIGN_CENTRE|wxALL, $itemspacing);
    }
    $self->SetBackgroundColour($background);
    $self->SetSizer($sizer);
    $self->SetAutoLayout(1);
    $sizer->Fit($self);
    return $self;
}

1;

__END__

=pod

=head1 NAME

AAC::Pvoice::Row - A row of selectable items

=head1 SYNOPSIS

  use AAC::Pvoice::Row;
  use Wx;
  
  my $panel = Wx::Panel->new($self, -1);
  my $items = [ [Wx::NewId, $SomeWxBitmap,      sub{ print "do something useful here"} ],
                [Wx::NewId, $SomeOtherWxBitmap, sub{ print "do something else here"} ]];
		
  my $row = AAC::Pvoice::Row->new($panel,           # parent
                                  scalar(@$items),  # max
                                  $items,           # items
                                  wxDefaultPosition,# pos
                                  wxDefaultSize,    # size
                                  50,		    # maxX
                                  75,               # maxY
                                  5,                # spacing
                                  wxWHITE)          # background colour

=head1 DESCRIPTION

AAC::Pvoice::Row is a subclass of Wx::Panel. It will typically be placed
on an AAC::Pvoice::Panel, and contains selectable Wx::Bitmap-s, which,
when selected, will invoke a callback.

=head1 USAGE

=head 2 new(parent, maxitems, items, position, size, maxX, maxY, spacing, backgroundcolour)

This constructor is the only overridden function in AAC::Pvoice::Row. It
takes quite a number of parameters

=over 4

=item parent

The parent on which this row will be placed. Typically you'll be using an
instance of AAC::Pvoice::Panel for this, but it can be any Wx::Window
subclass

=item maxitems

The maximum number of items (images) in this row. If the supplied number
of items (next parameter) is lower than maxitems, the row will be filled up
with (unselectable) WxNullBitmap-s.

=item items

This parameter is a reference to a list of lists. Each item in the listref
contains three items: a unique id, a Wx::Bitmap (or AAC::Pvoice::Bitmap for
that matter), and a callback that will be invoked when the item is selected.

=item position

This parameter is passed on to the SUPER's constructor directly. See the
documentation for Wx::Panel.

=item size

This parameter is passed on to the SUPER's constructor directly. See the
documentation for Wx::Panel.

=item maxX

This is the maximum X size in pixels for an item (a Bitmap) in this row

=item maxY

This is the maximum Y size in pixels for an item (a Bitmap) in this row

=item spacing

This is the spacing between the items in pixels in this row

=item backgroundcolour

This is the backgroundcolour of the panel, defined as a Wx::Colour, or one
of the constants defined by Wx (like wxWHITE)

=back

=head1 BUGS

probably a lot, patches welcome!


=head1 AUTHOR

	Jouke Visser
	jouke@pvoice.org
	http://jouke.pvoice.org

=head1 COPYRIGHT

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.


=head1 SEE ALSO

perl(1), Wx

=cut

t/001_load.t  view on Meta::CPAN

# -*- perl -*-

# t/001_load.t - check module loading and create testing directory
# more testing will be added later

use Test::More tests => 2;
use Wx qw(:everything);

BEGIN { use_ok( 'AAC::Pvoice' ); }

package MyApp;
use base 'Wx::App';

sub OnInit
{
    my $frame = MyFrame->new();
    return 1;
}

package MyFrame;
use base 'Wx::Frame';
sub new
{
    my $class = shift;
    my $self = $class->SUPER::new(undef, -1, 'Test');
    my $panel = AAC::Pvoice::Panel->new ($self, -1);
    main::isa_ok ($panel, 'AAC::Pvoice::Panel');
    return $self;
}


package main;
my $obj = MyApp->new();

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 0.627 second using v1.00-cache-2.02-grep-82fe00e-cpan-1925d2aa809 )