1 package OS2::localMorphPM;
7 # print STDERR ">>>>>\n";
11 # print STDERR "<<<<<\n";
12 OS2::UnMorphPM(shift->[0])
22 our @ISA = qw(Exporter);
23 our $VERSION = "1.03";
24 XSLoader::load('OS2::Process', $VERSION);
27 # Items to export into callers namespace by default. Note: do not export
28 # names by default without a very good reason. Use EXPORT_OK instead.
29 # Do not simply export all your public functions/methods/constants.
153 FocusWindow_set_keep_Zorder
155 ActiveDesktopPathname
216 # This AUTOLOAD is used to 'autoload' constants from the constant()
217 # XS function. If a constant is not found then control is passed
218 # to the AUTOLOAD in AutoLoader.
220 (my $constname = $AUTOLOAD) =~ s/.*:://;
221 my $val = constant($constname, @_ ? $_[0] : 0);
223 if ($! =~ /Invalid/ || $!{EINVAL}) {
224 die "Unsupported function $AUTOLOAD"
226 my ($pack,$file,$line) = caller;
227 die "Your vendor has not defined OS2::Process macro $constname, used at $file line $line.
231 eval "sub $AUTOLOAD { $val }";
236 require OS2::Process::Const;
238 my ($err, $val) = OS2::Process::Const::constant($sym);
244 require OS2::Process::Const;
246 my $val = os2constant($sym);
251 *{"$p\::$sym"} = sub () { $val };
252 (); # needed by import()
260 /^(HWND|WM|SC|SWP|WC|PROG|QW|EDI|WS|QWS|QWP|QWL|FF|FI|LS|FS|FCF|BS|MS|TBM|CF|CFI|FID|MB|MBID|CF|CFI|SPTR)_/ ? const_import($_) : $_
262 goto &Exporter::import if @_ > 1 or $ini == 0;
265 # Preloaded methods go here.
267 sub Title () { (process_entry())[0] }
269 # *Title_set = \&sesmgr_title_set;
272 my ($title, @sw) = @_;
277 sub swTitle_set ($) {
278 my (@sw) = process_entry();
279 swTitle_set_sw(shift, @sw);
282 sub winTitle_set_sw {
283 my ($title, @sw) = @_;
284 my $h = OS2::localMorphPM->new(0);
285 WindowText_set $sw[1], $title;
288 sub winTitle_set ($) {
289 my (@sw) = process_entry();
290 winTitle_set_sw(shift, @sw);
294 my (@sw) = process_entry();
295 my $h = OS2::localMorphPM->new(0);
299 sub bothTitle_set ($) {
300 my (@sw) = process_entry();
302 winTitle_set_sw($t, @sw);
303 swTitle_set_sw($t, @sw);
308 return 1 if sesmgr_title_set($t);
309 return 0 unless $^E == 372;
310 my (@sw) = process_entry();
311 winTitle_set_sw($t, @sw);
312 swTitle_set_sw($t, @sw);
315 sub process_entry { swentry_expand(process_swentry(@_)) }
317 our @hentry_fields = qw( title owner_hwnd icon_hwnd
318 owner_phandle owner_pid owner_sid
319 visible nonswitchable jumpable ptype sw_entry );
321 sub swentry_hexpand ($) {
323 @h{@hentry_fields} = swentry_expand(shift);
327 sub process_hentry { swentry_hexpand(process_swentry(@_)) }
328 sub process_hwnd { process_hentry()->{owner_hwnd} }
330 my $swentry_size = swentry_size();
333 my $s = swentries_list();
334 my ($c, $s1) = unpack 'La*', $s;
335 die "Unconsistent size in swentries_list()" unless 4+$c*$swentry_size == length $s;
337 push @l, $e while $e = substr $s1, 0, $swentry_size, '';
341 sub process_entries () {
342 map [swentry_expand($_)], sw_entries;
345 sub process_hentries () {
346 map swentry_hexpand($_), sw_entries;
350 change_swentry(create_swentry(@_));
353 sub create_swentryh ($) {
355 create_swentry(@$h{@hentry_fields});
358 sub change_entryh ($) {
359 change_swentry(create_swentryh(shift));
362 # Massage entries into the same order as WindowPos_set:
364 my ($fl, $h, $w, $y, $x, $behind, $hwnd, @rest)
365 = unpack 'L l4 L4', WindowSWP(shift);
366 ($x, $y, $fl, $w, $h, $behind, @rest);
369 # Put them into a hash
372 @h{ qw(flags height width y x behind hwnd reserved1 reserved2) }
373 = unpack 'L l4 L4', WindowSWP(shift);
377 my @SWP_keys = ( [qw(width height)], # SWP_SIZE=1
378 [qw(x y)], # SWP_MOVE=2
379 [qw(behind)] ); # SWP_ZORDER=3
381 @SWP_def{ map @$_, @SWP_keys } = (0) x 20;
383 # Get them from a hash
384 sub hWindowPos_set ($$) {
386 my $hwnd = (@_ ? shift : $hash->{hwnd} );
388 if (exists $hash->{flags}) {
389 $flags = $hash->{flags};
390 } else { # Set flags according to existing keys in $hash
393 exists $hash->{$_} and $flags |= (1<<$bit) for @{$SWP_keys[$bit]};
396 for my $bit (0..2) { # Check for required keys
397 next unless $flags & (1<<$bit);
399 or die sprintf "key $_ required for flags=%#x", $flags
400 for @{$SWP_keys[$bit]};
402 my %h = (%SWP_def, flags => $flags, %$hash); # Avoid warnings
403 my ($x, $y, $fl, $w, $h, $behind) = @h{ qw(x y flags width height behind) };
404 WindowPos_set($hwnd, $x, $y, $fl, $w, $h, $behind);
407 sub ChildWindows (;$) {
408 my $hm = OS2::localMorphPM->new(0);
410 my $h = BeginEnumWindows(@_ ? shift : 1); # HWND_DESKTOP
412 push @kids, $w while $w = GetNextWindow $h;
418 my $d = DesktopWindow;
421 my $p = QueryWindow $w, 5; # QW_PARENT;
422 return $w if not $p or $p == $d;
427 sub FocusWindow_set_keep_Zorder ($) {
430 my $b = hWindowPos($t)->{behind}; # we are behind this
431 EnableWindowUpdate($t, 0);
433 # sleep 1; # Make flicker stronger when present
434 hWindowPos_set {behind => $b}, $t;
435 EnableWindowUpdate($t, 1);
438 sub WindowStyle ($) {
439 WindowULong(shift,-2); # QWL_STYLE
442 sub OS2::localClipbrd::new {
445 push @$morph, OS2::localMorphPM->new(0) unless shift;
447 # print STDERR ">>>>>\n";
450 sub OS2::localClipbrd::DESTROY {
451 # print STDERR "<<<<<\n";
455 sub OS2::localFlashWindow::new ($$) {
456 my ($c, $w) = (shift, shift);
457 my $morph = OS2::localMorphPM->new(0);
459 # print STDERR ">>>>>\n";
460 bless [$w, $morph], $c
462 sub OS2::localFlashWindow::DESTROY {
463 # print STDERR "<<<<<\n";
464 FlashWindow(shift->[0], 0);
467 # Good for \0-terminated text (not "text/unicode" and other Firefox stuff)
468 sub ClipbrdText (@) {
469 my $h = OS2::localClipbrd->new;
470 my $data = ClipbrdData @_;
472 my $lim = MemoryRegionSize($data);
473 $lim = StrLen($data, $lim); # Look for 1-byte 0
474 return unpack "P$lim", pack 'L', $data;
477 sub ClipbrdText_2byte (@) {
478 my $h = OS2::localClipbrd->new;
479 my $data = ClipbrdData @_;
481 my $lim = MemoryRegionSize($data);
482 $lim = StrLen($data, $lim, 2); # Look for 2-byte 0
483 return unpack "P$lim", pack 'L', $data;
486 sub ClipbrdTextUCS2le (@) {
487 my $txt = ClipbrdText_2byte @_; # little-endian shorts
488 #require Unicode::String;
489 pack "U*", unpack "v*", $txt;
492 sub ClipbrdText_set ($;@) {
493 my $h = OS2::localClipbrd->new;
494 EmptyClipbrd(); # It may contain other types
495 my ($txt, $no_convert_nl) = (shift, shift);
496 ClipbrdData_set($txt, !$no_convert_nl, @_);
499 sub ClipbrdFmtAtoms {
500 my $h = OS2::localClipbrd->new('nomorph');
503 push @formats, $fmt while eval {$fmt = EnumClipbrdFmts $fmt};
504 die $@ if $@ and $^E == 0x1001 and $fmt = 0; # Croaks on empty list?
508 sub ClipbrdFmtNames {
509 map AtomName($_), ClipbrdFmtAtoms(@_);
512 sub MessageBox ($;$$$$$) {
513 my $morph = OS2::localMorphPM->new(0);
514 die "MessageBox needs text" unless @_;
515 push @_ , ($0 eq '-e' ? "Perl one-liner's message" : "$0 message") if @_ == 1;
521 sub get_pointer ($;$$) {
523 return $pointers{$id} if exists $pointers{$id};
524 $pointers{$id} = &SysPointer;
527 # $button needs to be of the form 'String', ['String'] or ['String', flag].
528 # If ['String'], it is assumed the default button; same for 'String' if $only
530 sub process_MB2 ($$;$) {
531 die "process_MB2() needs 2 arguments, got '@_'" unless @_ == 2 or @_ == 3;
532 my ($button, $ret, $only) = @_;
533 # default is BS_PUSHBUTTON, add BS_DEFAULT if $only is set
534 $button = [$button, $only ? 0x400 : 0] unless ref $button eq 'ARRAY';
535 push @$button, 0x400 if @$button == 1; # BS_PUSHBUTTON|BS_DEFAULT
536 die "Button needs to be of the form 'String', ['String'] or ['String', flag]"
537 unless @$button == 2;
538 pack "Z71 x L l", $button->[0], $ret, $button->[1]; # name, retval, flag
541 # If one button, make it the default one even if it is of 'String' => val form.
542 # If icon is of the form 'SP#<number>', load this via SysPointer.
543 sub process_MB2_INFO ($;$$$) {
546 die "process_MB2_INFO() needs 1..4 arguments" unless @_ and @_ < 5;
548 die "Buttons array should consist of pairs" if @$buttons % 2;
550 push @_, 0 unless @_; # Icon id; non-0 ignored without MB_CUSTOMICON
551 # Box flags (MB_MOVABLE and MB_INFORMATION or MB_CUSTOMICON)
552 push @_, ($_[0] ? 0x4080 : 0x4030) unless @_ > 1;
553 push @_, 0 unless @_ > 2; # Notify window
555 my ($icon, $style, $notify) = (shift, shift, shift);
556 $icon = get_pointer $1 if $icon =~ /^SP#(\d+)\z/;
557 $out = pack "L L L L", # icon, #buttons, style, notify, buttons
558 $icon, @$buttons/2, $style, $notify;
560 map process_MB2($buttons->[2*$_], $buttons->[2*$_+1], @$buttons == 2),
562 pack('L', length(pack 'L', 0) + length $out) . $out;
565 # MessageBox2 'Try this', OS2::Process::process_MB2_INFO([['Dismiss', 0] => 0x1000], OS2::Process::get_pointer(22),0x4080,0), 'me', 1, 0, 0
567 # MessageBox2 'Try this', [[['Dismiss', 0] => 0x1000], 'SP#22'], 'me'
568 # 0x80 means MB_CUSTOMICON (does not focus?!). This focuses:
569 # MessageBox2 'Try this', [[['Dismiss',0x400] => 0x1000], 0, 0x4030,0]
570 # 0x400 means BS_DEFAULT. This is the same as the shortcut
571 # MessageBox2 'Try this', [[Dismiss => 0x1000]]
572 sub MessageBox2 ($;$$$$$) {
573 my $morph = OS2::localMorphPM->new(0);
574 die "MessageBox needs text" unless @_;
575 push @_ , [[Dismiss => 0x1000], # Name, retval (style BS_PUSHBUTTON|BS_DEFAULT)
576 #0, # e.g., get_pointer(11),# SPTR_ICONINFORMATION
577 #0x4030, # = MB_MOVEABLE | MB_INFORMATION
578 #0, # Notify window; was 1==HWND_DESKTOP
580 push @_ , ($0 eq '-e' ? "Perl one-liner" : $0). "'s message" if @_ == 2;
581 $_[1] = &process_MB2_INFO(@{$_[1]}) if ref($_[1]) eq 'ARRAY';
586 text => 'Something happened',
587 title => ($0 eq '-e' ? "Perl one-liner" : $0). "'s message",
588 parent => 1, # HWND_DESKTOP
591 buttons => ['Dismiss' => 0x1000],
593 # icon => 0x30, # MB_INFORMATION
594 # iconID => 0, # XXX???
596 notifyWindow => 0, # XXX???
600 die "MessageBoxH: even number of arguments expected" if @_ % 2;
601 my %a = (%mbH_default, @_);
602 die "MessageBoxH: even number of elts of button array expected"
603 if @{$a{buttons}} % 2;
604 if (defined $a{iconID}) {
605 $a{flags} |= 0x80; # MB_CUSTOMICON
607 $a{icon} = 0x30 unless defined $a{icon};
609 $a{flags} |= $a{icon};
611 # Mark default_button as MessageBox2() expects it:
612 $a{buttons}[2*$a{default_button}] = [$a{buttons}[2*$a{default_button}]];
614 my $use_2 = 'ARRAY' eq ref $a{buttons};
616 MessageBox2 $a{text}, [@a{qw(buttons iconID flags notifyWindow)}],
617 $a{parent}, $a{owner}, $a{helpID}
619 die "MessageBoxH: unexpected format of argument 'buttons'";
622 # backward compatibility
623 *set_title = \&Title_set;
624 *get_title = \&Title;
626 # New (logical) names
627 *WindowBits_set = \&SetWindowBits;
628 *WindowPtr_set = \&SetWindowPtr;
629 *WindowULong_set = \&SetWindowULong;
630 *WindowUShort_set = \&SetWindowUShort;
632 # adapter; display; cbMemory; Configuration; VDHVersion; Flags; HWBufferSize;
633 # FullSaveSize; PartSaveSize; EMAdaptersOFF; EMDisplaysOFF;
634 sub vioConfig (;$$) {
635 my $data = &_vioConfig;
636 my @out = unpack 'x[S]SSLSSSLLLSS', $data;
637 # If present, offset points to S/S (with only the first work making sense)
638 my (@adaptersEMU, @displayEMU);
639 @displaysEMU = unpack("x[$out[10]]S/S", $data), pop @out if @out > 10;
640 @adaptersEMU = unpack("x[$out[ 9]]S/S", $data), pop @out if @out > 9;
641 $out[9] = $adaptersEMU[0] if @adaptersEMU;
642 $out[10] = $displaysEMU[0] if @displaysEMU;
646 my @vioConfig = qw(adapter display cbMemory Configuration VDHVersion Flags
647 HWBufferSize FullSaveSize PartSaveSize EMAdapters EMDisplays);
649 sub viohConfig (;$$) {
651 @h{@vioConfig} = &vioConfig;
655 # fbType; color; col; row; hres; vres; fmt_ID; attrib; buf_addr; buf_length;
656 # full_length; partial_length; ext_data_addr;
657 sub vioMode() {unpack 'x[S]CCSSSSCCLLLLL', _vioMode}
659 my @vioMode = qw( fbType color col row hres vres fmt_ID attrib buf_addr
660 buf_length full_length partial_length ext_data_addr);
664 @h{@vioMode} = vioMode;
669 my %h = (viohMode, @_);
670 my $o = pack 'x[S]CCSSSSCCLLLLL', @h{@vioMode};
671 $o = pack 'SCCSSSSCCLLLLL', length $o, @h{@vioMode};
675 sub kbdChar (;$$) {unpack 'CCCCSL', &_kbdChar}
677 my @kbdChar = qw(ascii scancode status nlsstate shifts time);
680 @h{@kbdChar} = &kbdChar;
684 sub kbdStatus (;$) {unpack 'x[S]SSSS', &_kbdStatus}
685 my @kbdStatus = qw(state turnChar intCharFlags shifts);
686 sub kbdhStatus (;$) {
688 @h{@kbdStatus} = &kbdStatus;
692 my $h = (@_ % 2 ? shift @_ : 0);
693 my %h = (kbdhStatus($h), @_);
694 my $o = pack 'x[S]SSSS', @h{@kbdStatus};
695 $o = pack 'SSSSS', length $o, @h{@kbdStatus};
696 _kbdStatus_set($o,$h);
699 #sub DeleteAtom { !WinDeleteAtom(@_) }
700 sub DeleteAtom { !_DeleteAtom(@_) }
701 sub DestroyAtomTable { !_DestroyAtomTable(@_) }
703 # XXXX This is a wrong order: we start keyreader, then screenwriter; so it is
704 # the writer who gets signals.
706 # XXXX Do we ever get a message "screenwriter killed"??? If reader HUPs us...
707 # Large buffer works at least for read from pipes; should we binmode???
708 sub __term_mirror_screen { # Read from fd=$in and write to the console
709 local $SIG{TERM} = $SIG{HUP} = $SIG{BREAK} = $SIG{INT} = # die() can stop END
710 sub { my $s = shift; warn "screenwriter killed ($s)...\n";};
712 open IN, "<&=$in" or die "open <&=$in: $!";
713 # Attempt to redirect to STDERR/OUT is not very useful, but try this anyway...
714 open OUT, '>', '/dev/con' or open OUT, '>&STDERR' or open OUT, '>&STDOUT'
715 and select OUT or die "Can't open /dev/con or STDERR/STDOUT for write";
716 $| = 1; local $SIG{TERM} = sub { die "screenwriter exits...\n"};
717 binmode IN; binmode OUT;
718 eval { print $_ while sysread IN, $_, 1<<16; }; # print to OUT...
720 warn "Screenwriter can't read any more ($!, $^E), terminating...\n";
723 # Does not automatically ends when the parent exits if related => 0
724 # copy from fd=$in to screen ; same for $out; or $in may be a named pipe
727 ### If related => 1, we get TERM when our parent exits...
728 local $SIG{TERM} = sub { my $s = shift;
729 die "keyreader exits in a few secs ($s)...\n" };
730 my ($in, $out) = (shift, shift);
731 if (defined $out and length $out) { # Allow '' for ease of @ARGV
732 open OUT, ">&=$out" or die "Cannot open &=$out for write: $!";
733 fcntl(OUT, 4, 1); # F_SETFD, NOINHERIT
734 open IN, "<&=$in" or die "Cannot open &=$in for read/ioctl: $!";
735 fcntl(IN, 4, 0); # F_SETFD, INHERIT
737 warn "Unexpected i/o pipe name: `$in'" unless $in =~ m,^[\\/]pipe[\\/],i;
738 OS2::pipe $in, 'wait';
739 open OUT, '+<', $in or die "Can't open `$in' for r/w: $!";
740 fcntl(OUT, 4, 0); # F_SETFD, INHERIT
745 Title_set $opt{title} if exists $opt{title};
746 &scrsize_set(split /,/, $opt{scrsize}) if exists $opt{scrsize};
748 my @i = map +('-I', $_), @INC; # Propagate @INC
750 # Careful unless PERL_SIGNALS=unsafe: SIGCHLD does not work...
751 $SIG{CHLD} = sub {wait; die "Keyreader follows screenwriter...\n"}
754 $pid = system 1, $^X, @i, '-MOS2::Process',
755 '-we', 'END {sleep 2} OS2::Process::__term_mirror_screen shift', $in;
756 close IN if defined $out;
757 $pid > 0 or die "Cannot start a grandkid";
759 open STDIN, '</dev/con' or warn "reopen stdin: $!";
760 select OUT; $| = 1; binmode OUT; # need binmode: sysread() may be bin
761 $SIG{PIPE} = sub { die "writing to a closed pipe" };
762 $SIG{HUP} = $SIG{BREAK} = $SIG{INT} = $SIG{TERM};
763 # Workaround: EMX v61 won't return pid on SESSION|UNRELATED after fork()...
764 syswrite OUT, pack 'L', $$ or die "syswrite failed: $!" if $opt{writepid};
765 # Turn Nodelay on kbd. Pipe is automatically nodelay...
766 if ($opt{read_by_key}) {
767 if (eval {require Term::ReadKey; 1}) {
768 Term::ReadKey::ReadMode(4);
769 } else { warn "can't load Term::ReadKey; input by lines..." }
771 print while sysread STDIN, $_, 1<<($opt{smallbuffer} ? 0 : 16); # to OUT
775 sub io_term { # arguments as hash: read_by_key/title/scrsize/related/writepid
776 # read_by_key disables echo too...
778 my ($sysf, $in1, $out1, $in2, $out2, $f1, $f2, $fd) = 4; # P_SESSION
782 pipe $in1, $out1 or die "pipe(): $!";
783 pipe $in2, $out2 or do { close($in1), close($out1), die "pipe(): $!" };
784 $f1 = fileno $in1; $f2 = fileno $out2;
785 fcntl($in2, 4, 1); fcntl($out1, 4, 1); # F_SETFD, NOINHERIT
786 fcntl($in1, 4, 0); fcntl($out2, 4, 0); # F_SETFD, INHERIT
788 $f1 = "/pipe/perlmodule/OS2/Process/$$-" . $c++;
789 $out1 = OS2::pipe $f1, 'rw' or die "OS2::pipe(): $^E";
790 #open $out1, "+<&=$fd" or die "dup($fd): $!, $^E";
791 fcntl($out1, 4, 1); # F_SETFD, NOINHERIT
794 $sysf |= 0x40000; # P_UNRELATED
795 $opt{writepid} = 1, unless exists $opt{writepid};
798 # system P_SESSION will fail if there is another process
799 # in the same session with a "related" asynchronous child session.
800 my @i = map +('-I', $_), @INC; # Propagate @INC
802 END {sleep($sleep || 5)}
803 use OS2::Process; $sleep = 1;
804 OS2::Process::__term_mirror(@ARGV);
808 $kpid = system $sysf, $^X, @i, '-we', $krun, $f1, $f2, %opt;
810 local $ENV{PERL_SIGNALS} = 'unsafe';
811 $kpid = system $sysf, $^X, @i, '-we', $krun, $f1, $f2, %opt;
813 close $in1 or warn if defined $in1;
814 close $out2 or warn if defined $out2;
815 # EMX BUG with $kpid == 0 after fork()
816 do { close($in2), ($out1 != $in2 and close($out1)),
817 die "system $sysf, $^X: kid=$kpid, \$!=`$!', \$^E=`$^E'" }
818 unless $kpid > 0 or $kpid == 0 and $opt{writepid};
819 # Can't read or write until the kid opens the pipes
820 OS2::pipeCntl $out1, 'connect', 'wait' unless length $f2;
821 # Without duping: write after read (via termio) on the same fd dups input
822 open $in2, '<&', $out1 or die "dup($out1): $^E" unless $opt{related};
823 if ($opt{writepid}) {
824 my $c = length pack 'L', 0;
825 my $c1 = sysread $in2, (my $pid), $c;
826 $c1 == $c or die "unexpected length read: $c1 vs $c";
827 $kpid = unpack 'L', $pid;
829 return ($in2, $out1, $kpid);
832 # Autoload methods go after __END__, and are processed by the autosplit program.
839 OS2::Process - exports constants for system() call, and process control on OS2.
844 $pid = system(P_PM | P_BACKGROUND, "epm.exe");
848 =head2 Optional argument to system()
850 the builtin function system() under OS/2 allows an optional first
851 argument which denotes the mode of the process. Note that this argument is
852 recognized only if it is strictly numerical.
854 You can use either one of the process modes:
856 P_WAIT (0) = wait until child terminates (default)
857 P_NOWAIT = do not wait until child terminates
858 P_SESSION = new session
862 and optionally add PM and session option bits:
864 P_DEFAULT (0) = default
865 P_MINIMIZE = minimized
866 P_MAXIMIZE = maximized
867 P_FULLSCREEN = fullscreen (session only)
868 P_WINDOWED = windowed (session only)
870 P_FOREGROUND = foreground (if running in foreground)
871 P_BACKGROUND = background
873 P_NOCLOSE = don't close window on exit (session only)
875 P_QUOTE = quote all arguments
876 P_TILDE = MKS argument passing convention
877 P_UNRELATED = do not kill child when father terminates
879 =head2 Access to process properties
881 On OS/2 processes have the usual I<parent/child> semantic;
882 additionally, there is a hierarchy of sessions with their own
883 I<parent/child> tree. A session is either a FS session, or a windowed
884 pseudo-session created by PM. A session is a "unit of user
885 interaction", a change to in/out settings in one of them does not
886 affect other sessions.
892 returns the type of the current process (one of
893 "FS", "DOS", "VIO", "PM", "DETACH" and "UNKNOWN"), or C<undef> on error.
895 =item C<file_type(file)>
897 returns the type of the executable file C<file>, or
898 dies on error. The bits 0-2 of the result contain one of the values
902 =item C<T_NOTSPEC> (0)
904 Application type is not specified in the executable header.
906 =item C<T_NOTWINDOWCOMPAT> (1)
908 Application type is not-window-compatible.
910 =item C<T_WINDOWCOMPAT> (2)
912 Application type is window-compatible.
914 =item C<T_WINDOWAPI> (3)
916 Application type is window-API.
920 The remaining bits should be masked with the following values to
921 determine the type of the executable:
927 Set to 1 if the executable file has been "bound" (by the BIND command)
928 as a Family API application. Bits 0, 1, and 2 still apply.
930 =item C<T_DLL> (0x10)
932 Set to 1 if the executable file is a dynamic link library (DLL)
933 module. Bits 0, 1, 2, 3, and 5 will be set to 0.
935 =item C<T_DOS> (0x20)
937 Set to 1 if the executable file is in PC/DOS format. Bits 0, 1, 2, 3,
938 and 4 will be set to 0.
940 =item C<T_PHYSDRV> (0x40)
942 Set to 1 if the executable file is a physical device driver.
944 =item C<T_VIRTDRV> (0x80)
946 Set to 1 if the executable file is a virtual device driver.
948 =item C<T_PROTDLL> (0x100)
950 Set to 1 if the executable file is a protected-memory dynamic link
953 =item C<T_32BIT> (0x4000)
955 Set to 1 for 32-bit executable files.
959 file_type() may croak with one of the strings C<"Invalid EXE
960 signature"> or C<"EXE marked invalid"> to indicate typical error
961 conditions. If given non-absolute path, will look on C<PATH>, will
962 add extension F<.exe> if no extension is present (add extension F<.>
965 =item C<@list = process_codepages()>
967 the first element is the currently active codepage, up to 2 additional
968 entries specify the system's "prepared codepages": the codepages the
969 user can switch to. The active codepage of a process is one of the
970 prepared codepages of the system (if present).
972 =item C<process_codepage_set($cp)>
974 sets the currently active codepage. [Affects printer output, in/out
975 codepages of sessions started by this process, and the default
976 codepage for drawing in PM; is inherited by kids. Does not affect the
977 out- and in-codepages of the session.]
981 returns the PID of the parent process.
983 =item C<ppidOf($pid = $$)>
985 returns the PID of the parent process of $pid. -1 on error.
987 =item C<sidOf($pid = $$)>
989 returns the session id of the process id $pid. -1 on error.
993 =head2 Control of VIO sessions
995 VIO applications are applications running in a text-mode session.
1001 gets code page used for screen output (glyphs). -1 means that a user font
1004 =item C<out_codepage_set($cp)>
1006 sets code page used for screen output (glyphs). -1 switches to a preloaded
1007 user font. -2 switches off the preloaded user font.
1011 gets code page used for keyboard input. 0 means that a hardware codepage
1014 =item C<in_codepage_set($cp)>
1016 sets code page used for keyboard input.
1018 =item C<($w, $h) = scrsize()>
1020 width and height of the given console window in character cells.
1022 =item C<scrsize_set([$w, ] $h)>
1024 set height (and optionally width) of the given console window in
1025 character cells. Use 0 size to keep the old size.
1027 =item C<($s, $e, $w, $a) = cursor()>
1029 gets start/end lines of the blinking cursor in the charcell, its width
1030 (1 on text modes) and attribute (-1 for hidden, in text modes other
1031 values mean visible, in graphic modes color).
1033 =item C<cursor_set($s, $e, [$w [, $a]])>
1035 sets start/end lines of the blinking cursor in the charcell. Negative
1036 values mean percents of the character cell height.
1040 gets a buffer with characters and attributes of the screen.
1042 =item C<screen_set($buffer)>
1044 restores the screen given the result of screen(). E.g., if the file
1045 C<$file> contains the screen contents, then
1047 open IN, $file or die;
1049 read IN, $in, -s IN;
1051 $in .= qq(\0) x (length($s) - length $in);
1052 substr($in, length $s) = '';
1055 will restore the screen content even if the height of the window
1056 changed (if the width changed, more manipulation is needed).
1060 =head2 Control of the process list
1062 With the exception of Title_set(), all these calls require that PM is
1063 running, they would not work under alternative Session Managers.
1067 =item process_entry()
1069 returns a list of the following data:
1075 Title of the process (in the C<Ctrl-Esc> list);
1079 window handle of switch entry of the process (in the C<Ctrl-Esc> list);
1083 window handle of the icon of the process;
1087 process handle of the owner of the entry in C<Ctrl-Esc> list;
1091 process id of the owner of the entry in C<Ctrl-Esc> list;
1095 session id of the owner of the entry in C<Ctrl-Esc> list;
1099 whether visible in C<Ctrl-Esc> list;
1103 whether item cannot be switched to (note that it is not actually
1104 grayed in the C<Ctrl-Esc> list));
1108 whether participates in jump sequence;
1112 program type. Possible values are:
1116 PROG_WINDOWABLEVIO 2
1121 Although there are several other program types for WIN-OS/2 programs,
1122 these do not show up in this field. Instead, the PROG_VDM or
1123 PROG_WINDOWEDVDM program types are used. For instance, for
1124 PROG_31_STDSEAMLESSVDM, PROG_WINDOWEDVDM is used. This is because all
1125 the WIN-OS/2 programs run in DOS sessions. For example, if a program
1126 is a windowed WIN-OS/2 program, it runs in a PROG_WINDOWEDVDM
1127 session. Likewise, if it's a full-screen WIN-OS/2 program, it runs in
1132 switch-entry handle.
1136 Optional arguments: the pid and the window-handle of the application running
1137 in the OS/2 session to query.
1139 =item process_hentry()
1141 similar to process_entry(), but returns a hash reference, the keys being
1143 title owner_hwnd icon_hwnd owner_phandle owner_pid owner_sid
1144 visible nonswitchable jumpable ptype sw_entry
1146 (a copy of the list of keys is in @hentry_fields).
1148 =item process_entries()
1150 similar to process_entry(), but returns a list of array reference for all
1151 the elements in the switch list (one controlling C<Ctrl-Esc> window).
1153 =item process_hentries()
1155 similar to process_hentry(), but returns a list of hash reference for all
1156 the elements in the switch list (one controlling C<Ctrl-Esc> window).
1158 =item change_entry()
1160 changes a process entry, arguments are the same as process_entry() returns.
1162 =item change_entryh()
1164 Similar to change_entry(), but takes a hash reference as an argument.
1166 =item process_hwnd()
1168 returns the C<owner_hwnd> of the process entry (for VIO windowed processes
1169 this is the frame window of the session).
1173 returns the text of the task switch menu entry of the current session.
1174 (There is no way to get this info in non-standard Session Managers. This
1175 implementation is a shortcut via process_entry().)
1177 =item C<Title_set(newtitle)>
1179 tries two different interfaces. The Session Manager one does not work
1180 with some windows (if the title is set from the start).
1181 This is a limitation of OS/2, in such a case $^E is set to 372 (type
1185 for a funny - and wrong - explanation ;-). In such cases a
1186 direct-manipulation of low-level entries is used (same as bothTitle_set()).
1187 Keep in mind that some versions of OS/2 leak memory with such a manipulation.
1191 returns text of the titlebar of the current process' window.
1193 =item C<winTitle_set(newtitle)>
1195 sets text of the titlebar of the current process' window. The change does not
1196 affect the text of the switch entry of the current window.
1198 =item C<swTitle_set(newtitle)>
1200 sets text of the task switch menu entry of the current process' window. [There
1201 is no API to query this title.] Does it via SwitchEntry interface,
1202 not Session manager interface. The change does not affect the text of the
1203 titlebar of the current window.
1205 =item C<bothTitle_set(newtitle)>
1207 sets text of the titlebar and task switch menu of the current process' window
1208 via direct manipulation of the windows' texts.
1210 =item C<SwitchToProgram([$sw_entry])>
1212 switch to session given by a switch list handle (defaults to the entry of our process).
1214 Use of this function causes another window (and its related windows)
1215 of a PM session to appear on the front of the screen, or a switch to
1216 another session in the case of a non-PM program. In either case,
1217 the keyboard (and mouse for the non-PM case) input is directed to
1222 =head2 Control of the PM windows
1224 Some of these API's require sending a message to the specified window.
1225 In such a case the process needs to be a PM process, or to be morphed
1226 to a PM process via OS2::MorphPM().
1228 For a temporary morphing to PM use L<OS2::localMorphPM class>.
1230 Keep in mind that PM windows are engaged in 2 "orthogonal" window
1231 trees, as well as in the z-order list.
1233 One tree is given by the I<parent/child> relationship. This
1234 relationship affects drawing (child is drawn relative to its parent
1235 (lower-left corner), and the drawing is clipped by the parent's
1236 boundary; parent may request that I<it's> drawing is clipped to be
1237 confined to the outsize of the childs and/or siblings' windows);
1238 hiding; minimizing/restoring; and destroying windows.
1240 Another tree (not necessarily connected?) is given by I<ownership>
1241 relationship. Ownership relationship assumes cooperation of the
1242 engaged windows via passing messages on "important events"; e.g.,
1243 scrollbars send information messages when the "bar" is moved, menus
1244 send messages when an item is selected; frames
1245 move/hide/unhide/minimize/restore/change-z-order-of owned frames when
1246 the owner is moved/etc., and destroy the owned frames (even when these
1247 frames are not descendants) when the owner is destroyed; etc. [An
1248 important restriction on ownership is that owner should be created by
1249 the same thread as the owned thread, so they engage in the same
1252 Windows may be in many different state: Focused (take keyboard events) or not,
1253 Activated (=Frame windows in the I<parent/child> tree between the root and
1254 the window with the focus; usually indicate such "active state" by titlebar
1255 highlights, and take mouse events) or not, Enabled/Disabled (this influences
1256 the ability to update the graphic, and may change appearance, as for
1257 enabled/disabled buttons), Visible/Hidden, Minimized/Maximized/Restored, Modal
1260 The APIs below all die() on error with the message being $^E.
1264 =item C<WindowText($hwnd)>
1266 gets "a text content" of a window. Requires (morphing to) PM.
1268 =item C<WindowText_set($hwnd, $text)>
1270 sets "a text content" of a window. Requires (morphing to) PM.
1272 =item C<($x, $y, $flags, $width, $height, $behind, @rest) = WindowPos($hwnd)>
1274 gets window position info as 8 integers (of C<SWP>), in the order suitable
1275 for WindowPos_set(). @rest is marked as "reserved" in PM docs. $flags
1276 is a combination of C<SWP_*> constants.
1278 =item C<$hash = hWindowPos($hwnd)>
1280 gets window position info as a hash reference; the keys are C<flags width
1281 height x y behind hwnd reserved1 reserved2>.
1285 exit unless $hash->{flags} & SWP_MAXIMIZE; # Maximized
1287 =item C<WindowPos_set($hwnd, $x, $y, $flags = SWP_MOVE, $width = 0, $height = 0, $behind = HWND_TOP)>
1289 Set state of the window: position, size, zorder, show/hide, activation,
1290 minimize/maximize/restore etc. Which of these operations to perform
1291 is governed by $flags.
1293 =item C<hWindowPos_set($hash, [$hwnd])>
1295 Same as C<WindowPos_set>, but takes the position from keys C<fl width height
1296 x y behind hwnd> of the hash referenced by $hash. If $hwnd is explicitly
1297 specified, it overrides C<$hash->{hwnd}>. If $hash->{flags} is not specified,
1298 it is calculated basing on the existing keys of $hash. Requires (morphing to) PM.
1302 hWindowPos_set {flags => SWP_MAXIMIZE}, $hwnd; # Maximize
1304 =item C<($pid, $tid) = WindowProcess($hwnd)>
1306 gets I<PID> and I<TID> of the process associated to the window.
1308 =item C<ClassName($hwnd)>
1310 returns the class name of the window.
1312 If this window is of any of the preregistered WC_* classes the class
1313 name returned is in the form "#nnnnn", where "nnnnn" is a group
1314 of up to five digits that corresponds to the value of the WC_* class name
1317 =item WindowStyle($hwnd)
1319 Returns the "window style" flags for window handle $hwnd.
1321 =item WindowULong($hwnd, $id), WindowPtr($hwnd, $id), WindowUShort($hwnd, $id)
1323 Return data associated to window handle $hwnd. $id should be one of
1324 C<QWL_*>, C<QWP_PFNWP>, C<QWS_*> constants, or a byte offset referencing
1325 a region (of length 4, 4, 2 correspondingly) fully inside C<0..cbWindowData-1>.
1326 Here C<cbWindowData> is the count of extra user-specified bytes reserved
1327 for the given class of windows.
1329 =item WindowULong_set($hwnd, $id, $value), WindowPtr_set, WindowUShort_set
1331 Similar to WindowULong(), WindowPtr(), WindowUShort(), but for assigning the
1334 =item WindowBits_set($hwnd, $id, $value, $mask)
1336 Similar to WindowULong_set(), but will change only the bits which are
1341 returns the handle of the focus window. Optional argument for specifying
1344 =item C<FocusWindow_set($hwnd)>
1346 set the focus window by handle. Optional argument for specifying the desktop
1347 to use. E.g, the first entry in program_entries() is the C<Ctrl-Esc> list.
1348 To show an application, use either one of
1350 WinShowWindow( $hwnd, 1 );
1351 FocusWindow_set( $hwnd );
1352 SwitchToProgram($switch_handle);
1354 (Which work with alternative focus-to-front policies?) Requires
1357 Switching focus to currently-unfocused window moves the window to the
1358 front in Z-order; use FocusWindow_set_keep_Zorder() to avoid this.
1360 =item C<FocusWindow_set_keep_Zorder($hwnd)>
1362 same as FocusWindow_set(), but preserves the Z-order of windows.
1364 =item C<ActiveWindow([$parentHwnd])>
1366 gets the active subwindow's handle for $parentHwnd or desktop.
1367 Returns FALSE if none.
1369 =item C<ActiveWindow_set($hwnd, [$parentHwnd])>
1371 sets the active subwindow's handle for $parentHwnd or desktop. Requires (morphing to) PM.
1373 =item C<ShowWindow($hwnd [, $show])>
1375 Set visible/hidden flag of the window. Default: $show is TRUE.
1377 =item C<EnableWindowUpdate($hwnd [, $update])>
1379 Set window visibility state flag for the window for subsequent drawing.
1380 No actual drawing is done at this moment. Use C<ShowWindow($hwnd, $state)>
1381 when redrawing is needed. While update is disabled, changes to the "window
1382 state" do not change the appearance of the window. Default: $update is TRUE.
1384 (What is manipulated is the bit C<WS_VISIBLE> of the window style.)
1386 =item C<EnableWindow($hwnd [, $enable])>
1388 Set the window enabled state. Default: $enable is TRUE.
1390 Results in C<WM_ENABLED> message sent to the window. Typically, this
1391 would change the appearence of the window. If at the moment of disabling
1392 focus is in the window (or a descendant), focus is lost (no focus anywhere).
1393 If focus is needed, it can be reassigned explicitly later.
1395 =item IsWindowEnabled(), IsWindowVisible(), IsWindowShowing()
1397 these functions take $hwnd as an argument. IsWindowEnabled() queries
1398 the state changed by EnableWindow(), IsWindowVisible() the state changed
1399 by ShowWindow(), IsWindowShowing() is true if there is a part of the window
1400 visible on the screen.
1402 =item C<PostMsg($hwnd, $msg, $mp1, $mp2)>
1404 post message to a window. The meaning of $mp1, $mp2 is specific for each
1405 message id $msg, they default to 0. E.g.,
1407 use OS2::Process qw(:DEFAULT WM_SYSCOMMAND WM_CONTEXTMENU
1408 WM_SAVEAPPLICATION WM_QUIT WM_CLOSE
1409 SC_MAXIMIZE SC_RESTORE);
1410 $hwnd = process_hentry()->{owner_hwnd};
1411 # Emulate choosing `Restore' from the window menu:
1412 PostMsg $hwnd, WM_SYSCOMMAND, MPFROMSHORT(SC_RESTORE); # Not immediate
1414 # Emulate `Show-Contextmenu' (Double-Click-2), two ways:
1415 PostMsg ActiveWindow, WM_CONTEXTMENU;
1416 PostMsg FocusWindow, WM_CONTEXTMENU;
1418 /* Emulate `Close' */
1419 PostMsg ActiveWindow, WM_CLOSE;
1421 /* Same but with some "warnings" to the application */
1422 $hwnd = ActiveWindow;
1423 PostMsg $hwnd, WM_SAVEAPPLICATION;
1424 PostMsg $hwnd, WM_CLOSE;
1425 PostMsg $hwnd, WM_QUIT;
1427 In fact, MPFROMSHORT() may be omitted above.
1429 For messages to other processes, messages which take/return a pointer are
1434 The functions MPFROMSHORT(), MPVOID(), MPFROMCHAR(), MPFROM2SHORT(),
1435 MPFROMSH2CH(), MPFROMLONG() can be used the same way as from C. Use them
1436 to construct parameters $m1, $m2 to PostMsg().
1438 These functions are not exported by default.
1440 =item C<$eh = BeginEnumWindows($hwnd)>
1442 starts enumerating immediate child windows of $hwnd in z-order. The
1443 enumeration reflects the state at the moment of BeginEnumWindows() calls;
1444 use IsWindow() to be sure. All the functions in this group require (morphing to) PM.
1446 =item C<$kid_hwnd = GetNextWindow($eh)>
1448 gets the next kid in the list. Gets 0 on error or when the list ends.
1450 =item C<EndEnumWindows($eh)>
1452 End enumeration and release the list.
1454 =item C<@list = ChildWindows([$hwnd])>
1456 returns the list of child windows at the moment of the call. Same remark
1457 as for enumeration interface applies. Defaults to HWND_DESKTOP.
1462 printf ' ' x $o . "%#x\n", $h;
1463 l($o+2,$_) for ChildWindows $h;
1467 =item C<IsWindow($hwnd)>
1469 true if the window handle is still valid.
1471 =item C<QueryWindow($hwnd, $type)>
1473 gets the handle of a related window. $type should be one of C<QW_*> constants.
1475 =item C<IsChild($hwnd, $parent)>
1477 return TRUE if $hwnd is a descendant of $parent.
1479 =item C<WindowFromId($hwnd, $id)>
1481 return a window handle of a child of $hwnd with the given $id.
1483 hwndSysMenu = WinWindowFromID(hwndDlg, FID_SYSMENU);
1484 WinSendMsg(hwndSysMenu, MM_SETITEMATTR,
1485 MPFROM2SHORT(SC_CLOSE, TRUE),
1486 MPFROM2SHORT(MIA_DISABLED, MIA_DISABLED));
1488 =item C<WindowFromPoint($x, $y [, $hwndParent [, $descedantsToo]])>
1490 gets a handle of a child of $hwndParent at C<($x,$y)>. If $descedantsToo
1491 (defaulting to 1) then children of children may be returned too. May return
1492 $hwndParent (defaults to desktop) if no suitable children are found,
1493 or 0 if the point is outside the parent.
1495 $x and $y are relative to $hwndParent.
1497 =item C<EnumDlgItem($dlgHwnd, $type [, $relativeHwnd])>
1499 gets a dialog item window handle for an item of type $type of $dlgHwnd
1500 relative to $relativeHwnd, which is descendant of $dlgHwnd.
1501 $relativeHwnd may be specified if $type is EDI_FIRSTTABITEM or
1504 The return is always an immediate child of hwndDlg, even if hwnd is
1505 not an immediate child window. $type may be
1509 =item EDI_FIRSTGROUPITEM
1511 First item in the same group.
1513 =item EDI_FIRSTTABITEM
1515 First item in dialog with style WS_TABSTOP. hwnd is ignored.
1517 =item EDI_LASTGROUPITEM
1519 Last item in the same group.
1521 =item EDI_LASTTABITEM
1523 Last item in dialog with style WS_TABSTOP. hwnd is ignored.
1525 =item EDI_NEXTGROUPITEM
1527 Next item in the same group. Wraps around to beginning of group when
1528 the end of the group is reached.
1530 =item EDI_NEXTTABITEM
1532 Next item with style WS_TABSTOP. Wraps around to beginning of dialog
1533 item list when end is reached.
1535 =item EDI_PREVGROUPITEM
1537 Previous item in the same group. Wraps around to end of group when the
1538 start of the group is reached. For information on the WS_GROUP style,
1541 =item EDI_PREVTABITEM
1543 Previous item with style WS_TABSTOP. Wraps around to end of dialog
1544 item list when beginning is reached.
1548 =item DesktopWindow()
1550 gets the actual window handle of the PM desktop; most APIs accept the
1551 pseudo-handle C<HWND_DESKTOP> instead. Keep in mind that the WPS
1552 desktop (one with WindowText() being C<"Desktop">) is a different beast?!
1554 =item TopLevel($hwnd)
1556 gets the toplevel window of $hwnd.
1558 =item ResetWinError()
1560 Resets $^E. One may need to call it before the C<Win*>-class APIs which may
1561 return 0 during normal operation. In such a case one should check both
1562 for return value being zero and $^E being non-zero. The following APIs
1563 do ResetWinError() themselves, thus do not need an explicit one:
1572 This function is normally not needed. Not exported by default.
1576 =head2 Control of the PM data
1580 =item ActiveDesktopPathname()
1582 gets the path of the directory which corresponds to Desktop.
1584 =item InvalidateRect
1586 =item CreateFrameControls
1590 =head2 Control of the PM clipboard
1596 gets the content of the clipboard. An optional argument is the format
1597 of the data in the clipboard (defaults to C<CF_TEXT>). May croak with error
1598 C<PMERR_INVALID_HWND> if no data of given $fmt is present.
1600 Note that the usual convention is to have clipboard data with
1601 C<"\r\n"> as line separators. This function will only work with clipboard
1602 data types which are delimited by C<"\0"> byte (not included in the result).
1604 =item ClipbrdText_2byte
1606 Same as ClipbrdText(), but will only work with clipboard
1607 data types which are collection of C C<shorts> delimited by C<0> short
1608 (not included in the result).
1610 =item ClipbrdTextUCS2le
1612 Same as ClipbrdText_2byte(), but will assume that the shorts represent
1613 an Unicode string in I<UCS-2le> format (little-endian 2-byte representation
1614 of Unicode), and will provide the result in Perl internal C<utf8> format
1615 (one short of input represents one Perl character).
1617 Note that Firefox etc. export their selection in unicode types of this format.
1619 =item ClipbrdText_set($txt, [$no_convert_nl, [$fmt, [$fmtinfo, [$hab] ] ] ] )
1621 sets the text content of the clipboard after removing old contents. Unless the
1622 optional argument $no_convert_nl is TRUE, will convert newlines to C<"\r\n">. Another optional
1623 argument $fmt is the format of the data in the clipboard (should be an
1624 atom, defaults to C<CF_TEXT>). Other arguments are as for C<ClipbrdData_set>.
1627 =item ClipbrdFmtInfo( [$fmt, [ $hab ] ])
1629 returns the $fmtInfo flags set by the application which filled the
1630 format $fmt of the clipboard. $fmt defaults to C<CF_TEXT>.
1632 =item ClipbrdOwner( [ $hab ] )
1634 Returns window handle of the current clipboard owner.
1636 =item ClipbrdViewer( [ $hab ] )
1638 Returns window handle of the current clipboard viewer.
1640 =item ClipbrdData( [$fmt, [ $hab ] ])
1642 Returns a handle to clipboard data of the given format as an integer.
1643 Format defaults to C<CF_TEXT> (in this case the handle is a memory address).
1645 Clipboard should be opened before calling this function. May croak with error
1646 C<PMERR_INVALID_HWND> if no data of given $fmt is present.
1648 The result should not be used after clipboard is closed. Hence a return handle
1649 of type C<CLI_POINTER> may need to be converted to a string and stored for
1650 future usage. Use MemoryRegionSize() to get a high estimate on the length
1651 of region addressed by this pointer; the actual length inside this region
1652 should be obtained by knowing particular format of data. E.g., it may be
1653 0-byte terminated for string types, or 0-short terminated for wide-char string
1656 =item OpenClipbrd( [ $hab ] )
1658 claim read access to the clipboard. May need a message queue to operate.
1659 May block until other processes finish dealing with clipboard.
1661 =item CloseClipbrd( [ $hab ] )
1663 Allow other processes access to clipboard.
1664 Clipboard should be opened before calling this function.
1666 =item ClipbrdData_set($data, [$convert_nl, [$fmt, [$fmtInfo, [ $hab] ] ] ] )
1668 Sets the clipboard data of format given by atom $fmt. Format defaults to
1671 $fmtInfo should declare what type of handle $data is; it should be either
1672 C<CFI_POINTER>, or C<CFI_HANDLE> (possibly qualified by C<CFI_OWNERFREE>
1673 and C<CFI_OWNERDRAW> flags). It defaults to C<CFI_HANDLE> for $fmt being
1674 standard bitmap, metafile, and palette (undocumented???) formats;
1675 otherwise defaults to C<CFI_POINTER>. If format is C<CFI_POINTER>, $data
1676 should contain the string to copy to clipboard; otherwise it should be an
1679 If $convert_nl is TRUE (the default), C<"\n"> in $data are converted to
1680 C<"\r\n"> pairs if $fmt is C<CFI_POINTER> (as is the convention for text
1681 format of the clipboard) unless they are already in such a pair.
1683 =item _ClipbrdData_set($data, [$fmt, [$fmtInfo, [ $hab] ] ] )
1685 Sets the clipboard data of format given by atom $fmt. Format defaults to
1686 CF_TEXT. $data should be an address (in givable unnamed shared memory which
1687 should not be accessed or manipulated after this call) or a handle in a form
1690 $fmtInfo has the same semantic as for ClipbrdData_set().
1692 =item ClipbrdOwner_set( $hwnd, [ $hab ] )
1694 Sets window handle of the current clipboard owner (window which gets messages
1695 when content of clipboard is retrieved).
1697 =item ClipbrdViewer_set( $hwnd, [ $hab ] )
1699 Sets window handle of the current clipboard owner (window which gets messages
1700 when content of clipboard is changed).
1702 =item ClipbrdFmtNames()
1704 Returns list of names of formats currently available in the clipboard.
1706 =item ClipbrdFmtAtoms()
1708 Returns list of atoms of formats currently available in the clipboard.
1710 =item EnumClipbrdFmts($fmt [, $hab])
1712 Low-level access to the list of formats currently available in the clipboard.
1713 Returns the atom for the format of clipboard after $fmt. If $fmt is 0, returns
1714 the first format of clipboard. Returns 0 if $fmt is the last format. Example:
1717 my $h = OS2::localClipbrd->new('nomorph');
1719 push @formats, AtomName $fmt
1720 while $fmt = EnumClipbrdFmts $fmt;
1723 Clipboard should be opened before calling this function. May croak if
1724 no format is present.
1726 =item EmptyClipbrd( [ $hab ] )
1728 Remove all the data handles in the clipboard. croak()s on failure.
1729 Clipboard should be opened before calling this function.
1731 Recommended before assigning a value to clipboard to remove extraneous
1732 formats of data from clipboard.
1734 =item ($size, $flags) = MemoryRegionSize($addr, [$size_lim, [ $interrupt ]])
1736 $addr should be a memory address (encoded as integer). This call finds
1737 the largest continuous region of memory belonging to the same memory object
1738 as $addr, and having the same memory flags as $addr. $flags is the value of
1739 the memory flag of $addr (see docs of DosQueryMem(3) for details). If
1740 optional argumetn $size_lim is given, the search is restricted to the region
1741 this many bytes long (after $addr).
1743 ($addr and $size are rounded so that all the memory pages containing
1744 the region are inspected.) Optional argument $interrupt (defaults to 1)
1745 specifies whether region scan should be interruptable by signals.
1749 Use class C<OS2::localClipbrd> to ensure that clipboard is closed even if
1750 the code in the block made a non-local exit.
1752 See L<"OS2::localMorphPM and OS2::localClipbrd classes">.
1754 =head2 Control of the PM atom tables
1756 Low-level methods to access the atom table(s). $atomtable defaults to
1757 the SystemAtomTable().
1761 =item AddAtom($name, [$atomtable])
1763 Returns the atom; increments the use count unless $name is a name of an
1766 =item FindAtom($name, [$atomtable])
1768 Returns the atom if it exists, 0 otherwise (actually, croaks).
1770 =item DeleteAtom($name, [$atomtable])
1772 Decrements the use count unless $name is a name of an integer atom.
1773 When count goes to 0, association of the name to an integer is removed.
1774 (Version with prepended underscore returns 0 on success.)
1776 =item AtomName($atom, [$atomtable])
1778 Returns the name of the atom. Integer atoms have names of format C<"#ddddd">
1779 of variable length up to 7 chars.
1781 =item AtomLength($atom, [$atomtable])
1783 Returns the length of the name of the atom. Return of 0 means that no
1784 such atom exists (but usually croaks in such a case).
1786 Integer atoms always return length 6.
1788 =item AtomUsage($name, [$atomtable])
1790 Returns the usage count of the atom.
1792 =item SystemAtomTable()
1794 Returns central atom table accessible to any process.
1796 =item CreateAtomTable( [ $initial, [ $buckets ] ] )
1798 Returns new per-process atom table. See docs for WinCreateAtomTable(3).
1800 =item DestroyAtomTable($atomtable)
1802 Dispose of the table. (Version with prepended underscore returns 0 on success.)
1807 =head2 Alerting the user
1811 =item Alarm([$type])
1813 Audible alarm of type $type (defaults to C<WA_ERROR=2>). Other useful
1814 values are C<WA_WARNING=0>, C<WA_NOTE=1>. (What is C<WA_CDEFALARMS=3>???)
1816 The duration and frequency of the alarms can be changed by the
1817 OS2::SysValues_set(). The alarm frequency is defined to be in the range 0x0025
1818 through 0x7FFF. The alarm is not generated if system value SV_ALARM is set
1819 to FALSE. The alarms are dependent on the device capability.
1821 =item FlashWindow($hwnd, $doFlash)
1823 Starts/stops (depending on $doFlash being TRUE/FALSE) flashing the window
1824 $hwnd's borders and titlebar. First 5 flashes are accompanied by alarm beeps.
1826 Example (for VIO applications):
1828 { my $morph = OS2::localMorphPM->new(0);
1829 print STDERR "Press ENTER!\n";
1830 FlashWindow(process_hwnd, 1);
1832 FlashWindow(process_hwnd, 0);
1835 Since flashing window persists even when application ends, it is very
1836 important to protect the switching off flashing from non-local exits. Use
1837 the class C<OS2::localFlashWindow> for this. Creating the object of this
1838 class starts flashing the window until the object is destroyed. The above
1841 print STDERR "Press ENTER!\n";
1842 { my $flash = OS2::localFlashWindow->new( process_hwnd );
1846 B<Notes from IBM docs:> Flashing a window brings the user's attention to a
1847 window that is not the active window, where some important message or dialog
1848 must be seen by the user.
1850 Note: It should be used only for important messages, for example, where some
1851 component of the system is failing and requires immediate attention to avoid
1854 =item MessageBox($text, [ $title, [$flags, ...] ])
1856 Shows a simple messagebox with (optional) icon, message $text, and one or
1857 more buttons to dismiss the box. Returns the indicator of which action was
1858 taken by the user. If optional argument $title is not given,
1859 the title is constructed from the application name. The optional argument
1860 $flags describes the appearance of the box; the default is to have B<Cancel>
1861 button, I<INFO>-style icon, and a border for moving. Flags should be
1864 Buttons on the box: or Button Group
1866 MB_OKCANCEL both OK and CANCEL
1869 MB_ENTERCANCEL both ENTER and CANCEL
1870 MB_RETRYCANCEL both RETRY and CANCEL
1871 MB_ABORTRETRYIGNORE ABORT, RETRY, and IGNORE
1872 MB_YESNO both YES and NO
1873 MB_YESNOCANCEL YES, NO, and CANCEL
1876 MB_ICONHAND a small red circle with a red line across it.
1877 MB_ERROR a small red circle with a red line across it.
1878 MB_ICONASTERISK an information (i) icon.
1879 MB_INFORMATION an information (i) icon.
1880 MB_ICONEXCLAMATION an exclamation point (!) icon.
1881 MB_WARNING an exclamation point (!) icon.
1882 MB_ICONQUESTION a question mark (?) icon.
1883 MB_QUERY a question mark (?) icon.
1886 Default action (i.e., focussed button; default is MB_DEFBUTTON1)
1887 MB_DEFBUTTON1 The first button is the default selection.
1888 MB_DEFBUTTON2 The second button is the default selection.
1889 MB_DEFBUTTON3 The third button is the default selection.
1892 MB_APPLMODAL Message box is application modal (default).
1893 MB_SYSTEMMODAL Message box is system modal.
1896 MB_MOVEABLE Message box is moveable.
1898 With C<MB_MOVEABLE> the message box is displayed with a title bar and a
1899 system menu, which shows only the Move, Close, and Task Manager choices,
1900 which can be selected either by use of the pointing device or by
1901 accelerator keys. If the user selects Close, the message box is removed
1902 and the usResponse is set to C<MBID_CANCEL>, whether or not a cancel button
1903 existed within the message box.
1905 C<Esc> key dismisses the dialogue only if C<CANCEL> button is present; the
1906 return value is C<MBID_CANCEL>.
1908 With C<MB_APPLMODAL> the owner of the dialogue is disabled; therefore, do not
1909 specify the owner as the parent if this option is used.
1911 Additionally, the following flag is possible, but probably not very useful:
1914 MB_HELP a HELP button appears, which sends a WM_HELP
1915 message is sent to the window procedure of the
1918 Other optional arguments: $parent window, $owner_window, $helpID (used with
1919 C<WM_HELP> message if C<MB_HELP> style is given).
1921 The return value is one of
1923 MBID_ENTER ENTER was selected
1924 MBID_OK OK was selected
1925 MBID_CANCEL CANCEL was selected
1926 MBID_ABORT ABORT was selected
1927 MBID_RETRY RETRY was selected
1928 MBID_IGNORE IGNORE was selected
1929 MBID_YES YES was selected
1930 MBID_NO NO was selected
1932 0 Function not successful; an error occurred.
1934 B<BUGS???> keyboard transversal by pressing C<TAB> key does not work.
1935 Do not appear in window list, so may be hard to find if covered by other
1938 =item _MessageBox($text, [ $title, [$flags, ...] ])
1940 Similar to MessageBox(), but the default $title does not depend on the name
1943 =item MessageBox2($text, [ $buttons_Icon, [$title, ...] ])
1945 Similar to MessageBox(), but allows more flexible choice of button texts
1946 and the icon. $buttons_Icon is a reference to an array with information about
1947 buttons and the icon to use; the semantic of this array is the same as
1948 for argument list of process_MB2_INFO(). The default value will show
1949 one button B<Dismiss> which will return C<0x1000>.
1951 Other optional arguments are the same as for MessageBox().
1953 B<NOTE.> Remark about C<MBID_CANCEL> in presence of C<MB_MOVABLE> is
1954 equally applicable to MessageBox() and MessageBox2().
1959 'Foo prints 100, Bar 101, Baz 102',
1960 [['~Foo' => 100, 'B~ar' => 101, ['Ba~z'] => 102]],
1961 'Choose a number to print';
1963 will show a messagebox with
1969 B<Choose a number to print>,
1973 B<Foo prints 100, Bar 101, Baz 102>
1981 B<Foo>, B<Bar>, B<Baz>
1983 =item Default button
1987 =item accelerator keys
1989 B<F>, B<a>, and B<z>
1993 100, 101, and 102 correspondingly,
2000 'Foo prints 100, Bar 101, Baz 102',
2001 [['~Foo' => 100, 'B~ar' => 101, ['Ba~z'] => 102], 'SP#22'],
2002 'Choose a number to print';
2004 will show the 22nd system icon as the dialog icon (small folder icon).
2006 =item _MessageBox2($text, $buttons_Icon_struct, [$title, ...])
2008 low-level workhorse to implement MessageBox2(). Differs by the dafault
2009 $title, and that $buttons_Icon_struct is required, and is a string with
2012 =item process_MB2_INFO($buttons, [$iconID, [$flags, [$notifyWindow]]])
2014 low-level workhorse to implement MessageBox2(); calculates the second
2015 argument of _MessageBox2(). $buttons is a reference
2016 to array of button descriptions. $iconID is either an ID of icon for
2017 the message box, or a string of the form C<"SP#number">; in the latter case
2018 the number's system icon is chosen; this field is ignored unless
2019 $flags contains C<MB_CUSTOMICON> flag. $flags has the same meaning as mobility,
2020 modality, and icon flags for MessageBox() with addition of extra flags
2022 MB_CUSTOMICON Use a custom icon specified in hIcon.
2023 MB_NONMODAL Message box is nonmodal
2025 $flags defaults to C<MB_INFORMATION> or C<MB_CUSTOMICON> (depending on whether
2026 $iconID is non-0), combined with MB_MOVABLE.
2028 Each button's description takes two elements of the description array,
2029 appearance description, and the return value of MessageBox2() if this
2030 button is selected. The appearance description is either an array reference
2031 of the form C<[$button_Text, $button_Style]>, or the same without
2032 $button_Style (then style is C<BS_DEFAULT>, making this button the default)
2033 or just $button_Text (with "normal" style). E.g., the list
2035 Foo => 100, Bar => 101, [Baz] => 102
2037 will show three buttons B<Foo>, B<Bar>, B<Baz> with B<Baz> being the default
2038 button; pressing buttons return 100, 101, or 102 correspondingly.
2040 In particular, exactly one button should have C<BS_DEFAULT> style (e.g.,
2041 given as C<[$button_Name]>); otherwise the message box will not have keyboard
2042 focus! (The only exception is the case of one button; then C<[$button_Name]>
2043 can be replaced (for convenience) with plain C<$button_Name>.)
2045 If text of the button contains character C<~>, the following character becomes
2046 the keyboard accelerator for this button. One can also get the handle
2047 of system icons directly, so C<'SP#22'> can be replaced by
2048 C<OS2::Process::get_pointer(22)>; see also C<SPTR_*> constants.
2050 B<NOTE> With C<MB_NONMODAL> the program continues after displaying the
2051 nonmodal message box. The message box remains visible until the owner window
2052 destroys it. Two notification messages, WM_MSGBOXINIT and WM_MSGBOXDISMISS,
2053 are used to support this non-modality.
2055 =item LoadPointer($id, [$module, [$hwnd]])
2057 Loads a handle for the pointer $id from the resources of the module
2058 $module on desktop $hwnd. If $module is 0 (default), loads from the main
2059 executable; otherwise from a DLL with the handle $module.
2061 The pointer is owned by the process, and is destroyed by
2062 DestroyPointer() call, or when the process terminates.
2064 =item SysPointer($id, [$copy, [$hwnd]])
2066 Gets a handle for (a copy of) the system pointer $id (the value should
2067 be one of C<SPTR_*> constants). A copy is made if $copy is TRUE (the
2068 default). $hwnd defaults to C<HWND_DESKTOP>.
2070 =item get_pointer($id, [$copy, [$hwnd]])
2072 Gets (and caches) a copy of the system pointer.
2076 =head2 Constants used by OS/2 APIs
2078 Function C<os2constant($name)> returns the value of the constant; to
2079 decrease the memory usage of this package, only the constants used by
2080 APIs called by Perl functions in this package are made available.
2082 For direct access, see also the L<"EXPORTS"> section; the latter way
2083 may also provide some performance advantages, since the value of the
2086 =head1 OS2::localMorphPM, OS2::localFlashWindow, and OS2::localClipbrd classes
2088 The class C<OS2::localMorphPM> morphs the process to PM for the duration of
2092 my $h = OS2::localMorphPM->new(0);
2096 The argument has the same meaning as one to OS2::MorphPM(). Calls can
2097 nest with internal ones being NOPs.
2099 Likewise, C<OS2::localClipbrd> class opens the clipboard for the duration
2100 of the current scope; if TRUE optional argument is given, it would not
2101 morph the application into PM:
2104 my $handle = OS2::localClipbrd->new(1); # Do not morph into PM
2105 # Do something with clipboard here...
2108 C<OS2::localFlashWindow> behaves similarly; see
2109 L<"FlashWindow($hwnd,$doFlash)">.
2113 The test suite for this module contains an almost comprehensive collection
2114 of examples of using the API of this module.
2144 Document: InvalidateRect,
2145 CreateFrameControls, kbdChar, kbdhChar,
2146 kbdStatus, _kbdStatus_set, kbdhStatus, kbdhStatus_set,
2147 vioConfig, viohConfig, vioMode, viohMode, viohMode_set, _vioMode_set,
2148 _vioState, _vioState_set, vioFont, vioFont_set
2150 Test: SetWindowULong/Short/Ptr, SetWindowBits. InvalidateRect,
2151 CreateFrameControls, ClipbrdOwner_set, ClipbrdViewer_set, _ClipbrdData_set,
2152 Alarm, FlashWindow, _MessageBox, MessageBox, _MessageBox2, MessageBox2,
2153 LoadPointer, SysPointer, kbdChar, kbdhChar, kbdStatus, _kbdStatus_set,
2154 kbdhStatus, kbdhStatus_set, vioConfig, viohConfig, vioMode, viohMode,
2155 viohMode_set, _vioMode_set, _vioState, _vioState_set, vioFont, vioFont_set
2157 Implement SOMETHINGFROMMR.
2160 >But I wish to change the default button if the user enters some
2161 >text into an entryfield. I can detect the entry ok, but can't
2162 >seem to get the button to change to default.
2164 >No matter what message I send it, it's being ignored.
2166 You need to get the style of the buttons using WinQueryWindowULong/QWL_STYLE,
2167 set and reset the BS_DEFAULT bits as appropriate and then use
2168 WinSetWindowULong/QWL_STYLE to set the button style.
2169 Something like this:
2170 hwnd1 = WinWindowFromID (hwnd, id1);
2171 hwnd2 = WinWindowFromID (hwnd, id2);
2172 style1 = WinQueryWindowULong (hwnd1, QWL_STYLE);
2173 style2 = WinQueryWindowULong (hwnd2, QWL_STYLE);
2174 style1 |= style2 & BS_DEFAULT;
2175 style2 &= ~BS_DEFAULT;
2176 WinSetWindowULong (hwnd1, QWL_STYLE, style1);
2177 WinSetWindowULong (hwnd2, QWL_STYLE, style2);
2179 > How to do query and change a frame creation flags for existing window?
2181 Set the style bits that correspond to the FCF_* flag for the frame
2182 window and then send a WM_UPDATEFRAME message with the appropriate FCF_*
2186 ulFrameStyle = WinQueryWindowULong( WinQueryWindow(hwnd, QW_PARENT),
2188 ulFrameStyle = (ulFrameStyle & ~FS_SIZEBORDER) | FS_BORDER;
2189 WinSetWindowULong( WinQueryWindow(hwnd, QW_PARENT),
2192 WinSendMsg( WinQueryWindow(hwnd, QW_PARENT),
2194 MPFROMP(FCF_SIZEBORDER),
2197 If the FCF_* flags you want to change does not have a corresponding FS_*
2198 style (i.e. the FCF_* flag corresponds to the presence/lack of a frame
2199 control rather than a property of the frame itself) then you create or
2200 destroy the appropriate control window using the correct FID_* window
2201 identifier and then send the WM_UPDATEFRAME message with the appropriate
2204 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*
2205 | SetFrameBorder() |
2206 | Changes a frame window's border to the requested type. |
2208 | Parameters on entry: |
2209 | hwndFrame -> Frame window whose border is to be changed. |
2210 | ulBorderStyle -> Type of border to change to. |
2213 | BOOL -> Success indicator. |
2215 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
2216 BOOL SetFrameBorder( HWND hwndFrame, ULONG ulBorderType ) {
2218 BOOL fSuccess = TRUE;
2220 ulFrameStyle = WinQueryWindowULong( hwndFrame, QWL_STYLE );
2222 switch ( ulBorderType ) {
2223 case FS_SIZEBORDER :
2224 ulFrameStyle = (ulFrameStyle & ~(FS_DLGBORDER | FS_BORDER))
2229 ulFrameStyle = (ulFrameStyle & ~(FS_SIZEBORDER | FS_BORDER))
2234 ulFrameStyle = (ulFrameStyle & ~(FS_SIZEBORDER | FS_DLGBORDER))
2244 fSuccess = WinSetWindowULong( hwndFrame, QWL_STYLE, ulFrameStyle );
2247 fSuccess = (BOOL)WinSendMsg( hwndFrame, WM_UPDATEFRAME, 0, 0 );
2249 fSuccess = WinInvalidateRect( hwndFrame, NULL, TRUE );
2253 return ( fSuccess );
2255 } // End SetFrameBorder()
2257 hwndMenu=WinLoadMenu(hwndParent,NULL,WND_IMAGE);
2258 WinSetWindowUShort(hwndMenu,QWS_ID,FID_MENU);
2259 ulStyle=WinQueryWindowULong(hwndMenu,QWL_STYLE);
2260 WinSetWindowULong(hwndMenu,QWL_STYLE,ulStyle|MS_ACTIONBAR);
2261 WinSendMsg(hwndParent,WM_UPDATEFRAME,MPFROMSHORT(FCF_MENU),0L);
2263 OS/2-windows have another "parent" called the *owner*,
2264 which must be set separately - to get a close relationship:
2266 WinSetOwner (hwndFrameChild, hwndFrameMain);
2268 Now your child should move with your main window!
2269 And always stays on top of it....
2271 To avoid this, for example for dialogwindows, you can
2272 also "disconnect" this relationship with:
2274 WinSetWindowBits (hwndFrameChild, QWL_STYLE
2275 , FS_NOMOVEWITHOWNER
2276 , FS_NOMOVEWITHOWNER);
2278 Adding a button icon later:
2280 /* switch the button style to BS_MINIICON */
2281 WinSetWindowBits(hwndBtn, QWL_STYLE, BS_MINIICON, BS_MINIICON) ;
2283 /* set up button control data */
2285 bcd.cb = sizeof(BTNCDATA);
2286 bcd.hImage = WinLoadPointer(HWND_DESKTOP, dllHandle, ID_ICON_BUTTON1) ;
2287 bcd.fsCheckState = bcd.fsHiliteState = 0 ;
2291 wp.fsStatus = WPM_CTLDATA;
2294 /* add the icon on the button */
2295 WinSendMsg(hwndBtn, WM_SETWINDOWPARAMS, (MPARAM)&wp, NULL);
2297 MO> Can anyone tell what OS/2 expects of an application to be properly
2298 MO> minimized to the desktop?
2299 case WM MINMAXFRAME :
2301 BOOL fShow = ! (((PSWP) mp1)->fl & SWP MINIMIZE);
2306 WinEnableWindowUpdate ( hwnd, FALSE );
2308 for (henum=WinBeginEnumWindows(hwnd);
2309 (hwndChild = WinGetNextWindow (henum)) != 0; )
2310 WinShowWindow ( hwndChild, fShow );
2312 WinEndEnumWindows ( henum );
2313 WinEnableWindowUpdate ( hwnd, TRUE );
2317 Why C<hWindowPos DesktopWindow> gives C<< behind => HWND_TOP >>?
2321 the majority of the APIs of this module set $^E on failure (no matter
2322 whether they die() on failure or not). By the semantic of PM API
2323 which returns something other than a boolean, it is impossible to
2324 distinguish failure from a "normal" 0-return. In such cases C<$^E ==
2325 0> indicates an absence of error.
2329 In addition to symbols described above, the following constants (available
2330 also via module C<OS2::Process::Const>) are exportable. Note that these
2331 symbols live in package C<OS2::Process::Const>, they are not available
2332 by full name through C<OS2::Process>!
2334 HWND_* Standard (abstract) window handles
2336 SC_* WM_SYSCOMMAND flavor
2337 SWP_* Size/move etc flag
2338 WC_* Standard window classes
2339 PROG_* Program category (PM, VIO etc)
2340 QW_* Query-Window flag
2341 EDI_* Enumerate-Dialog-Item code
2342 WS_* Window Style flag
2343 QWS_* Query-window-UShort offsets
2344 QWP_* Query-window-pointer offsets
2345 QWL_* Query-window-ULong offsets
2346 FF_* Frame-window state flags
2347 FI_* Frame-window information flags
2348 LS_* List box styles
2350 FCF_* Frame creation flags
2353 TBM_* Title bar messages?
2354 CF_* Clipboard formats
2355 CFI_* Clipboard storage type
2356 FID_* ids of subwindows of frames
2360 whether a given API dies or returns FALSE/empty-list on error may be
2361 confusing. This may change in the future.
2365 Andreas Kaiser <ak@ananke.s.bawue.de>,
2366 Ilya Zakharevich <ilya@math.ohio-state.edu>.
2370 C<spawn*>() system calls, L<OS2::Proc> and L<OS2::WinObject> modules.