]> nmode's Git Repositories - Fey/blob - lib/App/Fey.pm
025fb091cc9471a760cfcc7d540376f7ee4fc233
[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, $args) = @_;
12 my $config = do ($ENV{XDG_CONFIG_HOME} // "$ENV{HOME}/.config") . '/fey/config.pl';
13
14 my $self = {
15 mime_query => $args->{mime_query} // $config->{mime_query} // sub {
16 open my $mime_type, '-|', 'file', '--brief', '--mime-type', $_[0];
17 <$mime_type>;
18 },
19 contexts => $args->{contexts} // $config->{contexts} // { default => sub { 1 } },
20 targets => $args->{targets} // $config->{targets} // {}
21 };
22
23 bless $self, $class;
24 }
25
26 sub launch {
27 my $self = shift;
28
29 ARG: for my $file_or_uri (@_) {
30 if ($file_or_uri =~ m|^file://(.+)|) {
31 $file_or_uri = $1;
32 }
33
34 my ($mime_or_uri, $targets);
35 if (-e $file_or_uri) {
36 $mime_or_uri = $self->{mime_query}->($file_or_uri)
37 } else {
38 $mime_or_uri = $file_or_uri;
39 }
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 $associations->{$context}->($file_or_uri);
48 next ARG;
49 }
50 }
51 }
52 }
53 }
54 }
55 }
56
57 sub fey {
58 App::Fey->new(ref $_[0] ? shift : {})->launch(@_ ? @_ : die 'Error: No files or URIs specified.');
59 }