]> nmode's Git Repositories - Fey/blob - lib/App/Fey.pm
Refactor Fey.pm module
[Fey] / lib / App / Fey.pm
1 package App::Fey;
2
3 use strict;
4 use warnings;
5 use Exporter 'import';
6
7 our @EXPORT_OK = qw(fey);
8 our $version = '0.01';
9
10 sub new {
11 my ($class, $options) = @_;
12 my $config = do ($ENV{XDG_CONFIG_HOME} // "$ENV{HOME}/.config") . '/fey/config.pl';
13
14 my $self = {
15 mime_query => $options->{mime_query} // $config->{mime_query} // sub {
16 open my $mime_type, '-|', 'file', '--brief', '--mime-type', $_[0];
17 <$mime_type>;
18 },
19 contexts => $options->{contexts} // $config->{contexts} // { default => sub { 1 } },
20 targets => $options->{targets} // $config->{targets} // {}
21 };
22
23 bless $self, $class;
24 }
25
26 sub launch {
27 my $self = shift;
28 my $options = ref $_[0] ? shift : {};
29
30 die "No files or URIs specified.\n" unless @_;
31
32 ARG: for my $file_or_uri (@_) {
33 if ($options->{fork} && !$options->{single}) {
34 my $pid = fork;
35 next ARG if ($pid);
36 }
37
38 $file_or_uri = $1 if ($file_or_uri =~ m|^file://(.+)|);
39 my $mime_or_uri = -e $file_or_uri ? $self->{mime_query}->($file_or_uri) : $file_or_uri;
40
41 for my $target (@{ $self->{targets} }) {
42 for my $pattern (@{ $target->{patterns} }) {
43 if ($mime_or_uri =~ /$pattern/) {
44 my $associations = $target->{associations};
45 for my $context (keys %{ $associations }) {
46 if ($self->{contexts}->{$context}->()) {
47 if ($options->{single}) {
48 $associations->{$context}->(@_);
49 return;
50 }
51 $associations->{$context}->($file_or_uri);
52 return if ($options->{fork});
53 next ARG;
54 }
55 }
56 }
57 }
58 }
59 }
60 }
61
62 sub fey {
63 App::Fey->new(ref $_[0] ? $_[0] : {})->launch(@_);
64 }