1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
# -*- perl -*-
#
# Copyright (C) 2012-2021 Alexis Bienvenüe <paamc@passoire.fr>
#
# This file is part of Auto-Multiple-Choice
#
# Auto-Multiple-Choice is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 2 of
# the License, or (at your option) any later version.
#
# Auto-Multiple-Choice is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Auto-Multiple-Choice. If not, see
# <http://www.gnu.org/licenses/>.
use warnings;
use 5.012;
package AMC::FileMonitor;
sub new {
my ( $class, %o ) = (@_);
my $self = { deltat => 1, };
for my $k ( keys %o ) {
$self->{$k} = $o{$k} if ( defined( $self->{$k} ) );
}
$self->{files} = [];
$self->{timeout_id} = 0;
bless( $self, $class );
return ($self);
}
sub add_file {
my ( $self, $path, $callout, %oo ) = @_;
push @{ $self->{files} },
{
path => $path,
callout => $callout,
time => $self->get_change_time($path),
%oo
}
if ($path);
$self->start();
}
sub key_i {
my ( $self, $key, $value ) = @_;
if ( @{ $self->{files} } ) {
for my $i ( 0 .. $#{ $self->{files} } ) {
return ($i) if ( $self->{files}->[$i]->{$key} eq $value );
}
return (undef);
} else {
return (undef);
}
}
sub remove_file {
my ( $self, $path ) = @_;
$self->remove_key( 'file', $path );
}
sub remove_key {
my ( $self, $key, $value ) = @_;
my $i = $self->key_i( $key, $value );
if ( defined($i) ) {
splice( @{ $self->{files} }, $i, 1 );
$self->stop
if ( !@{ $self->{files} } );
}
}
sub update_file {
my ( $self, $path ) = @_;
my $i = $self->file_i($path);
if ( defined($i) ) {
$self->{files}->[$i]->{time} = $self->get_change_time($path);
}
}
sub get_change_time {
my ( $self, $path ) = @_;
if ( -e $path ) {
my @st = stat($path);
return ( $st[10] );
} else {
return (0);
}
}
sub start {
my ($self) = @_;
if ( @{ $self->{files} } ) {
if ( !$self->{timeout_id} ) {
$self->{timeout_id} =
Glib::Timeout->add_seconds( $self->{deltat}, \&monitor, $self );
}
}
}
sub stop {
my ($self) = @_;
Glib::Source->remove( $self->{timeout_id} );
$self->{timeout_id} = 0;
}
sub monitor {
my ($self) = @_;
for my $f ( @{ $self->{files} } ) {
my $t = $self->get_change_time( $f->{path} );
if ( $t > $f->{time} ) {
$f->{time} = $t if ( !$f->{repeat} );
&{ $f->{callout} }() if ( $f->{callout} );
}
}
return (1);
}
1;
|