]> nmode's Git Repositories - Fey/blob - lib/App/Fey.pm
89f6535a3f28c7fa75482ae885eb2cc9017e8bc8
[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 if ($file_or_uri =~ m|^file://(.+)|) {
39 $file_or_uri = $1;
40 }
41
42 my ($mime_or_uri, $targets);
43 if (-e $file_or_uri) {
44 $mime_or_uri = $self->{mime_query}->($file_or_uri)
45 } else {
46 $mime_or_uri = $file_or_uri;
47 }
48
49 for my $target (@{ $self->{targets} }) {
50 for my $pattern (@{ $target->{patterns} }) {
51 if ($mime_or_uri =~ /$pattern/) {
52 my $associations = $target->{associations};
53 for my $context (keys %{ $associations }) {
54 if ($self->{contexts}->{$context}->()) {
55 if ($options->{single}) {
56 $associations->{$context}->(@_);
57 return;
58 }
59 $associations->{$context}->($file_or_uri);
60 return if ($options->{fork});
61 next ARG;
62 }
63 }
64 }
65 }
66 }
67 }
68 }
69
70 sub fey {
71 App::Fey->new(ref $_[0] ? $_[0] : {})->launch(@_);
72 }