Блокируем клавиатуру в Linux

Изначально может показаться, что это очень странная задача, ведь можно просто заблокировать экран. Но если у вас в доме появился маленький ребенок, который то и дело норовит что то нажать, то поговорить, например, по Skype становится нереально. Итак, нужно максимально быстро заблокировать/разблокировать клавиатуру, чтобы маленький человечек не мог нажать/закрыть/удалить что-то во время общения по Skype с родственниками.

baby

Сначала Гугл меня навел меня на мысль использовать для этих целей xinput, но по какой то неведомомй причине моя клавиатура упорно не блокировалась. Дальнейшие поиски решения привели проекту Lock Keyboard for Baby. Проект не развивается уже с 2008, но у меня все заработало “с пол пинка”. Итак, скачиваем скрипт и кладем его в папочку /usr/bin:

sudo mv lock-keyboard-for-baby-20080706.pl /usr/bin/lock
sudo chmod +x /usr/bin/lock

Откройте скрипт в любом удобном редакторе в первой строке поменяйте путь до вашего интерпретатора perl. Подсмотеть где он располагается можно используя команду

which perl

Далее в 7 строке (параметр defaultpassword) задайте пароль для разблокировки. После чего сохраните изменения и попробуйте его запустить. Если клавиатура заблокировалась, то все в порядке и блокировку можно вызывать по комбинации клавишь Alf+F2 и введя команду lock.

Под катом итоговый скрипт. Спасибо за внимание.

#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my $lastmod="2006/05/25";
my $datemod="2008/07/03";
my $defaultpassword="lock";
my $progname=$0;
$progname =~ s%.*/%%g;

sub usage($)
{
my ($exitcode)[email protected]_;

print STDERR <<end_of_usage ;="" usage="" for="" $progname="" [-xy="XX,YY]" [-p|password="" thepassword]="" [-stars|-visible|-visible="maxlen]" [-message]="" [-w|-withmouse]="" [-help]="" was="" written="" by:chris="" sincock="" (this="" version="" $datemod)="" copyright="" (c)="" 2006="" chris="" '-withmouse'="" option="" added="" 2008="" andrew="" oakley="" under="" gpl="" this="" is="" free="" software;="" see="" the="" gnu="" license="" copying="" conditions.="" there="" no="" warranty;="" not="" even="" merchantability="" or="" fitness="" a="" particular="" purpose="" if="" you="" specify="" -password="" -stars="" it="" will="" default="" to="" telling="" what="" password="" type="" don't="" -vis,="" tell="" and="" be="" $defaultpassword="" can="" clear="" whatever="" has="" already="" been="" typed="" by="" hitting="" <return="">
END_OF_USAGE

exit($exitcode);
}

my $password=$defaultpassword;
my $message="Type the password to quit\n:";
my $true=1;
my $false=0;
my $noshow=$true;
my $withmouse=$false;
my $maxshownlength=30;
my $defaults_changed=$false;
my $defaults_changed_vis=$false;

my @startpos=(0,0);

while (@ARGV)
{
my $arg=shift @ARGV;
if($arg =~ /^-xy=(\d+),(\d+)$/i)
{
@startpos=($1,$2);
}
elsif($arg =~ /^(-|--)(h|help|usage|[?])$/i)
{
usage(0);
}
elsif($arg =~ /^(-|--)(p|pass|password)$/i)
{
if([email protected])
{
print STDERR "missing argument\n";
usage(-1);
}
$password=shift @ARGV;
$defaults_changed=$true;
}
elsif($arg =~ /^(-|--)(s|stars)$/i)
{
$noshow="stars";
$defaults_changed=$true;
}
elsif($arg =~ /^(-|--)(w|withmouse)$/i)
{
$withmouse=$true;
$defaults_changed=$true;
$defaults_changed_vis=$true;
}
elsif($arg =~ /^(-|--)(v|vis|visible)(=(\d+)|)$/i)
{
$noshow=$false;
if(length($4))
{
$maxshownlength=$4;
}
$defaults_changed=$true;
$defaults_changed_vis=$true;
}
elsif($arg =~ /^(-|--)(m|msg|message)$/i)
{
if([email protected])
{
print STDERR "missing argument\n";
usage(-1);
}
$message=shift @ARGV;
if(length($message))
{
$message.="\n";
}
$defaults_changed=$true;
}
else
{
usage(-1);
}
}
if(!$defaults_changed)
{
$noshow=$false;
}
if((!$defaults_changed || $defaults_changed_vis))
{
$message="Type '$password' to quit\n";
}

use Gtk2 -init;
my $w = new Gtk2::Window -popup;
my $l = new Gtk2::Label $message;
my $eb = new Gtk2::EventBox;
my $gdkwin;
my $grabstatus;
my $typed="";

sub do_grab()
{
$grabstatus= Gtk2::Gdk->keyboard_grab(
$gdkwin,$true,Gtk2::Gdk::X11->get_server_time($gdkwin) );
if($grabstatus ne "success")
{
$l->set_text("keyboard grab failed");
}
if($withmouse)
{
$grabstatus= Gtk2::Gdk->pointer_grab(
$gdkwin,$true,['button-press-mask','button-release-mask'],undef,undef,Gtk2::Gdk::X11->get_server_time($gdkwin));
if($grabstatus ne "success")
{
$l->set_text("pointer grab failed");
}
}
}

sub do_ungrab()
{
Gtk2::Gdk->keyboard_ungrab(Gtk2::Gdk::X11->get_server_time($gdkwin));
if($withmouse)
{
Gtk2::Gdk->pointer_ungrab(Gtk2::Gdk::X11->get_server_time($gdkwin));
}
}

sub do_keypress(@)
{
my ($widg,$evt)[email protected]_;
my $kv = $evt->keyval;
my $cs = Gtk2::Gdk->keyval_name($kv);

if($cs =~ /Return|Enter/)
{
if($typed eq $password)
{
do_ungrab();
Gtk2->main_quit;
}
else
{
$typed="";
}
}
elsif(length($cs) == 1 && $cs =~ /[[:print:]]/)
{
$typed .= $cs;
}
my $showtyped=$typed;
if($noshow eq "stars")
{
$showtyped =~ s/[^*]/*/g;
}
elsif($noshow)
{
$showtyped="";
}
if(length($showtyped) > $maxshownlength)
{
$showtyped=substr($showtyped,0,$maxshownlength);
}
$l->set_text($message.$showtyped);
}
$w->add($eb);
$eb->add($l);
$w->add_events( [ qw(key_press_mask) ]);
$w->signal_connect('key_press_event', \&do_keypress);
$w->signal_connect('realize', sub { $w->window->move(@startpos); });
$w->signal_connect('map', sub { $gdkwin=$w->window; do_grab(); });
$w->show_all;
Gtk2->main;

22 комментария к “Блокируем клавиатуру в Linux

  1. Attractive component to content. I simply stumbled upon your web
    site and in accession capital to assert that I acquire
    actually enjoyed account your weblog posts. Anyway I’ll be subscribing in your augment or even I fulfillment you get
    right of entry to consistently rapidly.

  2. There are definitely a great deal of information like that to take into consideration. That is an excellent indicate bring up. I provide the thoughts over as basic ideas but clearly there are questions like the one you raise where the most essential point will be operating in honest good faith. I don?t recognize if ideal practices have actually arised around things like that, yet I make certain that your work is clearly identified as a level playing field. Both boys as well as ladies really feel the influence of simply a moment?s enjoyment, for the remainder of their lives.

  3. After looking over a few of the blog posts on your site, I really like your technique of blogging. I book-marked it to my bookmark website list and will be checking back soon. Please check out my website too and let me know your opinion.

  4. I?m satisfied, I should state. Truly hardly ever do I come across a blog site that?s both informative as well as amusing, as well as let me inform you, you have actually struck the nail on the head. Your suggestion is impressive; the concern is something that not enough people are talking intelligently about. I am really happy that I came across this in my look for something relating to this.

  5. Youre so amazing! I don’t suppose Ive check out anything like this before. So nice to discover someone with some initial thoughts on this subject. realy thank you for starting this up. this website is something that is needed on the internet, somebody with a little creativity. valuable task for bringing something new to the internet!

  6. Can I just state what a relief to discover somebody who actually recognizes what theyre talking about on the net. You certainly recognize how to bring a problem to light and also make it important. Even more people require to read this as well as understand this side of the tale. I angle believe youre not more popular because you definitely have the present.

  7. Appreciating the commitment you put into your website and detailed information you present.
    It’s good to come across a blog every once in a while that isn’t the same unwanted
    rehashed information. Fantastic read! I’ve bookmarked your site and I’m including your RSS feeds to my Google
    account.

  8. An interesting conversation is worth comment. I believe that you should create extra on this topic, it might not be a taboo subject but typically individuals are insufficient to speak on such topics. To the next. Thanks

  9. This is the appropriate blog site for any individual who intends to find out about this subject. You realize a lot its practically tough to say with you (not that I in fact would want?HaHa). You certainly put a brand-new spin on a topic thats been discussed for several years. Terrific things, just excellent!

  10. Wonderful blog post. I find out something much more challenging on different blogs daily. It will always be stimulating to review material from various other writers and practice a something from their store. I?d favor to use some with the content on my blog site whether you don?t mind. Natually I?ll offer you a web link on your web blog. Thanks for sharing.

  11. When I originally commented I clicked the -Notify me when new remarks are included- checkbox and now each time a comment is added I get 4 emails with the exact same remark. Exists any way you can remove me from that service? Thanks!

  12. An excellent share, I simply provided this onto a colleague who was doing a little evaluation on this. And also he in fact acquired me morning meal due to the fact that I found it for him. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for investing the moment to review this, I feel strongly regarding it and also enjoy reading more on this topic. Preferably, as you end up being proficiency, would certainly you mind upgrading your blog with more details? It is very practical for me. Huge thumb up for this article!

Оставить ответ

Ваш адрес email не будет опубликован. Обязательные поля помечены *