File: dex

package info (click to toggle)
dex 0.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 112 kB
  • sloc: python: 684; makefile: 47
file content (992 lines) | stat: -rwxr-xr-x 32,073 bytes parent folder | download
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vi: ft=python:tw=0:sw=4:ts=4:noet
# Author:		Jan Christoph Ebersbach <jceb@e-jc.de>

# dex
# DesktopEntry Execution, is a program to generate and execute DesktopEntry
# files of the type Application
#
# Depends: Python
#
# Copyright (C) 2010 - 2024 Jan Christoph Ebersbach
#
# http://www.e-jc.de/
#
# All rights reserved.
#
# This program 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 3 of the License, or
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

__version__ = "0.10.1"

import os
import subprocess
import sys

try:
    from os import scandir
except ImportError:

    class _DirEntry:
        def __init__(self, name, path):
            self.name = name
            self.path = path

        def is_file(self):
            return os.path.isfile(self.path)

    def scandir(path="."):
        return [_DirEntry(f, os.path.join(path, f)) for f in os.listdir(path)]


# DesktopEntry exceptions
class DesktopEntryTypeException(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class ApplicationExecException(Exception):
    def __init__(self, value):
        self.value = value
        Exception.__init__(self, value)

    def __str__(self):
        return repr(self.value)


# DesktopEntry class definitions
class DesktopEntry(object):
    """
    Implements some parts of Desktop Entry specification:
    http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.1.html
    """

    def __init__(self, filename=None):
        """
        @param	filename	Desktop Entry File
        """
        if (
            filename is not None
            and os.path.islink(filename)
            and os.readlink(filename) == os.path.sep + os.path.join("dev", "null")
        ):
            # ignore links to /dev/null
            pass
        elif filename is None or not os.path.isfile(filename):
            raise IOError("File does not exist: %s" % filename)
        self._filename = filename
        self.groups = {}

    def __str__(self):
        if self.Name:
            return self.Name
        elif self.filename:
            return self.filename
        return repr(self)

    def __lt__(self, y):
        return self.filename < y.filename

    @property
    def filename(self):
        """
        The absolute filename
        """
        return self._filename

    @classmethod
    def fromfile(cls, filename):
        """Create DesktopEntry for file

        @params	filename	Create a DesktopEntry object for file and determine
                                                the type automatically
        """

        de = cls(filename=filename)

        # determine filetype
        de_type = "Link"
        if os.path.exists(filename):
            if os.path.isdir(filename):
                de_type = "Directory"
                # TODO fix the value for directories
                de.set_value("??", filename)
            else:
                de_type = "Application"
                de.set_value("Exec", filename)
                de.set_value("Name", os.path.basename(filename))
                if os.name == "posix":
                    whatis = subprocess.Popen(
                        ["whatis", filename],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                    )
                    stdout, stderr = whatis.communicate()
                    res = stdout.decode(sys.stdin.encoding).split("- ", 1)
                    if len(res) == 2:
                        de.set_value("Comment", res[1].split(os.linesep, 1)[0])
        else:
            # type Link
            de.set_value("URL", filename)

        de.set_value("Type", de_type)

        return de

    def load(self):
        """Load or reload contents of desktop entry file"""
        self.groups = {}  # clear settings
        grp_desktopentry = "Desktop Entry"

        with open(self.filename, "r") as fp:
            current_group = None
            for l in fp:
                l = l.strip("\n")
                # handle comments and empty lines
                if l.startswith("#") or l.isspace() or not l:
                    continue

                # handle groups
                if l.startswith("["):
                    if not l.endswith("]"):
                        raise DesktopEntryTypeException(
                            "'%s' is not a valid Desktop Entry because of line '%s'."
                            % (self.filename, l)
                        )
                    group = l[1:-1]
                    if group in self.groups:
                        raise DesktopEntryTypeException(
                            "'%s' is not a valid Desktop Entry because group '%s' is specified multiple times."
                            % (self.filename, group)
                        )
                    current_group = group
                    continue

                # handle all the other lines
                if not current_group:
                    raise DesktopEntryTypeException(
                        "'%s' is not a valid Desktop Entry because line '%s' does not belong to a group."
                        % (self.filename, l)
                    )
                kv = l.split("=", 1)
                if len(kv) != 2 or kv[0] == "":
                    raise DesktopEntryTypeException(
                        "'%s' is not a valid Desktop Entry because line '%s' is not a valid key=value pair."
                        % (self.filename, l)
                    )
                k = kv[0]
                v = kv[1]
                # TODO: parse k for locale specific settings
                # TODO: parse v for multivalue fields
                self.set_value(k, v, current_group)

        if grp_desktopentry not in self.groups:
            raise DesktopEntryTypeException(
                "'%s' is not a valid Desktop Entry group is missing." % (self.filename,)
            )
        if not self.Type or not self.Name:
            if self.Type != "Service":
                # allow files with type Service and no Name
                raise DesktopEntryTypeException(
                    "'%s' is not a valid Desktop Entry because Type or Name keys are missing."
                    % (self.filename,)
                )
        _type = self.Type
        if _type in ("Application", "Service"):
            if not self.Exec:
                raise DesktopEntryTypeException(
                    "'%s' is not a valid Desktop Entry of type '%s' because Exec is missing."
                    % (self.filename, _type)
                )
        elif _type == "Link":
            if not self.URL:
                raise DesktopEntryTypeException(
                    "'%s' is not a valid Desktop Entry of type '%s' because URL is missing."
                    % (self.filename, _type)
                )
        elif _type == "Directory":
            pass
        else:
            raise DesktopEntryTypeException(
                "'%s' is not a valid Desktop Entry because Type '%s' is unknown."
                % (self.filename, self.Type)
            )

    # another name for load
    reload = load

    def write(self, fp):
        """Write DesktopEntry to a file

        @param	fp	DesktopEntry is written to file
        """
        for group in self.groups:
            fp.write("[%s]\n" % (group,))
            for key in self.groups[group]:
                fp.write("%s=%s\n" % (key, self.groups[group][key]))

    def set_value(self, key, value, group="Desktop Entry"):
        """Set a key, value pair in group

        @param	key	Key
        @param	value	Value
        @param	group	The group key and value are set in. Default: Desktop Entry
        """
        if group not in self.groups:
            self.groups[group] = {}
        self.groups[group][key] = str(value)
        return value

    def _get_value(self, key, group="Desktop Entry", default=None):
        if not self.groups:
            self.load()
        if group not in self.groups:
            raise KeyError("Group '%s' not found." % group)
        return self.groups[group].get(key, default)

    def get_boolean(self, key, group="Desktop Entry", default=False):
        val = self._get_value(key, group=group, default=default)
        if type(val) == bool:
            return val
        if val in ["true", "True"]:
            return True
        if val in ["false", "False"]:
            return False
        raise ValueError(
            "'%s's value '%s' in group '%s' is not a boolean value." % (key, val, group)
        )

    def get_list(self, key, group="Desktop Entry", default=None):
        list_of_strings = []
        res = self.get_string(key, group=group, default=default)
        if type(res) == str:
            list_of_strings = [x for x in res.split(";") if x]
        return list_of_strings

    def get_string(self, key, group="Desktop Entry", default=""):
        return self._get_value(key, group=group, default=default)

    def get_strings(self, key, group="Desktop Entry", default=""):
        raise Exception("Not implemented yet.")

    def get_localestring(self, key, group="Desktop Entry", default=""):
        raise Exception("Not implemented yet.")

    def get_numeric(self, key, group="Desktop Entry", default=0.0):
        val = self._get_value(key, group=group, default=default)
        if type(val) == float:
            return val
        return float(val)

    @property
    def Type(self):
        return self.get_string("Type")

    @property
    def Version(self):
        return self.get_string("Version")

    @property
    def Name(self):
        # SHOULD be localestring!
        return self.get_string("Name")

    @property
    def GenericName(self):
        return self.get_localestring("GenericName")

    @property
    def NoDisplay(self):
        return self.get_boolean("NoDisplay")

    @property
    def Comment(self):
        return self.get_localestring("Comment")

    @property
    def Icon(self):
        return self.get_localestring("Icon")

    @property
    def Hidden(self):
        return self.get_boolean("Hidden")

    @property
    def OnlyShowIn(self):
        return self.get_list("OnlyShowIn")

    @property
    def NotShowIn(self):
        return self.get_list("NotShowIn")

    @property
    def TryExec(self):
        return self.get_string("TryExec")

    @property
    def Exec(self):
        return self.get_string("Exec")

    @property
    def Path(self):
        return self.get_string("Path")

    @property
    def Terminal(self):
        return self.get_boolean("Terminal")

    @property
    def MimeType(self):
        return self.get_strings("MimeType")

    @property
    def Actions(self):
        return self.get_list("Actions")

    @property
    def Categories(self):
        return self.get_strings("Categories")

    @property
    def StartupNotify(self):
        return self.get_boolean("StartupNotify")

    @property
    def StartupWMClass(self):
        return self.get_string("StartupWMClass")

    @property
    def URL(self):
        return self.get_string("URL")


class Application(DesktopEntry):
    """
    Implements application files
    """

    def __init__(self, filename):
        """
        @param	filename	Absolute path to a Desktop Entry File
        """
        if not os.path.isabs(filename):
            filename = os.path.join(os.getcwd(), filename)
        super(Application, self).__init__(filename)
        self._basename = os.path.basename(filename)
        if self.Type not in ("Application", "Service"):
            raise DesktopEntryTypeException(
                "'%s' is not of type 'Application'." % self.filename
            )

    @classmethod
    def _build_cmd(cls, exec_string, needs_terminal=False, term="x-terminal-emulator"):
        """
        # test single and multi argument commands
        >>> Application._build_cmd('gvim')
        ['gvim']
        >>> Application._build_cmd('gvim test')
        ['gvim', 'test']

        # test quotes
        >>> Application._build_cmd('"gvim" test')
        ['gvim', 'test']
        >>> Application._build_cmd('"gvim test"')
        ['gvim test']

        # test escape sequences
        # >>> Application._build_cmd('"gvim test" test2 "test \\\\" 3"')
        # ['gvim test', 'test2', 'test " 3']
        # >>> Application._build_cmd(r'"test \\\\\\\\ \\" moin" test')
        # ['test \\\\ " moin', 'test']
        # >>> Application._build_cmd(r'"gvim \\\\\\\\ \\`test\\$"')
        # ['gvim \\\\ \\`test\\$']
        >>> Application._build_cmd(r'vim ~/.vimrc', True)
        ['x-terminal-emulator', '-e', 'vim', '~/.vimrc']
        >>> Application._build_cmd('vim ~/.vimrc', False)
        ['vim', '~/.vimrc']
        >>> Application._build_cmd("vim '~/.vimrc test'", False)
        ['vim', '~/.vimrc test']
        >>> Application._build_cmd('vim \\'~/.vimrc " test\\'', False)
        ['vim', '~/.vimrc " test']
        >>> Application._build_cmd('sh -c \\'vim ~/.vimrc " test\\'', False)
        ['sh', '-c', 'vim ~/.vimrc " test']
        >>> Application._build_cmd("sh -c 'vim ~/.vimrc \\" test\\"'", False)
        ['sh', '-c', 'vim ~/.vimrc " test"']

        # expand field codes by removing them
        >>> Application._build_cmd("vim %u", False)
        ['vim']
        >>> Application._build_cmd("vim ~/.vimrc %u", False)
        ['vim', '~/.vimrc']
        >>> Application._build_cmd("vim '%u' ~/.vimrc", False)
        ['vim', '%u', '~/.vimrc']
        >>> Application._build_cmd("vim %u ~/.vimrc", False)
        ['vim', '~/.vimrc']
        >>> Application._build_cmd("vim /%u/.vimrc", False)
        ['vim', '//.vimrc']
        >>> Application._build_cmd("vim %u/.vimrc", False)
        ['vim', '/.vimrc']
        >>> Application._build_cmd("vim %U/.vimrc", False)
        ['vim', '/.vimrc']
        >>> Application._build_cmd("vim /%U/.vimrc", False)
        ['vim', '//.vimrc']
        >>> Application._build_cmd("vim %U .vimrc", False)
        ['vim', '.vimrc']

        # preserved escaped field codes
        >>> Application._build_cmd("vim \\\\%u ~/.vimrc", False)
        ['vim', '%u', '~/.vimrc']

        # test for non-valid field codes, they should be preserved
        >>> Application._build_cmd("vim %x .vimrc", False)
        ['vim', '%x', '.vimrc']
        >>> Application._build_cmd("vim %x/.vimrc", False)
        ['vim', '%x/.vimrc']
        """
        cmd = []
        if needs_terminal:
            cmd += [term, "-e"]
        _tmp = exec_string.replace("\\\\", "\\")
        _arg = ""
        in_esc = False
        in_quote = False
        in_singlequote = False
        in_fieldcode = False

        for c in _tmp:
            if in_esc:
                in_esc = False
            else:
                if in_fieldcode:
                    in_fieldcode = False
                    if c in ("u", "U", "f", "F"):
                        # TODO ignore field codes for the moment; at some point
                        # field codes should be supported
                        # strip %-char at the end of the argument
                        _arg = _arg[:-1]
                        continue

                if c == '"':
                    if in_quote:
                        in_quote = False
                        cmd.append(_arg)
                        _arg = ""
                        continue
                    if not in_singlequote:
                        in_quote = True
                        continue

                elif c == "'":
                    if in_singlequote:
                        in_singlequote = False
                        cmd.append(_arg)
                        _arg = ""
                        continue
                    if not in_quote:
                        in_singlequote = True
                        continue

                elif c == "\\":
                    if not in_quote:
                        in_esc = True
                        continue

                elif c == "%" and not (in_quote or in_singlequote):
                    in_fieldcode = True

                elif c == " " and not (in_quote or in_singlequote):
                    if not _arg:
                        continue
                    cmd.append(_arg)
                    _arg = ""
                    continue

            _arg += c

        if _arg and not (in_esc or in_quote or in_singlequote):
            cmd.append(_arg)
        elif _arg:
            raise ApplicationExecException(
                "Exec value contains an unbalanced number of quote characters."
            )

        return cmd

    def execute(self, action=None, term=None, wait=False, dryrun=False, verbose=False):
        """
        Execute application or, if given, a specific action
        @return	Return subprocess.Popen object
        """
        if self.TryExec:
            executable = self.TryExec
            if action:
                executable = Action(owner=self, identifier=action).Exec
            if not os.path.isabs(executable):
                executable = which(executable)
            if not os.access(executable, mode=os.F_OK | os.X_OK):
                if verbose:
                    print(
                        "Ignoring file, TryExec not found or not executable file: %s"
                        % executable,
                        file=sys.stderr,
                    )
                return

        path = self.Path
        cmd = self._build_cmd(
            exec_string=self.Exec, needs_terminal=self.Terminal, term=term
        )
        if not cmd:
            raise ApplicationExecException("Failed to build command string.")
        if dryrun or verbose:
            if verbose:
                print("Autostart file: %s" % self.filename)
            if path:
                print("Changing directory to: " + path)
            print("Executing command: " + " ".join(cmd))
        if dryrun:
            return

        _execute_fn = subprocess.Popen
        if wait:
            _execute_fn = subprocess.run
        if path:
            return _execute_fn(cmd, cwd=path, env=os.environ)
        return _execute_fn(cmd, env=os.environ)


class Action(object):
    def __init__(self, owner, identifier):
        """
        @param	owner	The Application that this action is part of
        @param	identifier	The Desktop Action's identifier (not its Name!)
        """
        self._owner = owner
        self._id = identifier

    def group_name(self):
        return "Desktop Action %s" % self._id

    @property
    def identifier(self):
        return self._id

    @property
    def Name(self):
        return self._owner.get_string("Name", group=self.group_name())

    @property
    def Exec(self):
        return self._owner.get_string("Exec", group=self.group_name())


# local methods
def which(filename):
    path = os.environ.get("PATH", None)
    if path:
        for _p in path.split(os.pathsep):
            _f = os.path.join(_p, filename)
            if os.path.isfile(_f):
                return _f


def get_autostart_directories(args):
    """
    Generate the list of autostart directories
    """
    if args.searchpaths:
        return [
            os.path.expandvars(os.path.expanduser(p))
            for p in args.searchpaths[0].split(os.pathsep)
        ]

    # generate list of autostart directories
    autostart_directories = []

    config_home = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
    autostart_directories.append(os.path.join(config_home, "autostart"))

    config_dirs = os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg")
    for d in config_dirs.split(os.pathsep):
        if not d:
            continue
        autostart_dir = os.path.join(d, "autostart")
        if autostart_dir not in autostart_directories:
            autostart_directories.append(autostart_dir)

    return autostart_directories


def get_autostart_files(args, verbose=False):
    """
    Generate a list of autostart files according to autostart-spec 0.5

    TODO: do filetype recognition according to spec
    """
    seen_files = set()
    autostart_files = []  # autostart files, excluding files marked as hidden

    for d in get_autostart_directories(args):
        if os.path.exists(d) and os.path.isdir(d):
            for entry in scandir(d):
                if not entry.is_file() or not entry.name.endswith(".desktop"):
                    if verbose:
                        print("Ignoring non-file: %s" % entry.path, file=sys.stderr)
                    continue
                elif entry.name in seen_files:
                    if verbose:
                        print(
                            "Ignoring file, overridden by other autostart file: %s"
                            % entry.path,
                            file=sys.stderr,
                        )
                    continue

                seen_files.add(entry.name)
                try:
                    app = Application(entry.path)
                except DesktopEntryTypeException as ex:
                    continue
                except ValueError as ex:
                    if verbose:
                        print(ex, file=sys.stderr)
                    continue
                except IOError as ex:
                    if verbose:
                        print(ex, file=sys.stderr)
                    continue

                if verbose:
                    if app.NotShowIn:
                        print(
                            "Not show in environments %s: %s"
                            % (", ".join(app.NotShowIn), app.filename),
                            file=sys.stderr,
                        )
                    if app.OnlyShowIn:
                        print(
                            "Only show in environments %s: %s"
                            % (", ".join(app.OnlyShowIn), app.filename),
                            file=sys.stderr,
                        )

                if app.Hidden:
                    if verbose:
                        print(
                            "Ignoring file, hidden attribute is set: %s" % app.filename,
                            file=sys.stderr,
                        )
                    continue
                elif app.OnlyShowIn and not (
                    args.environment and args.environment in app.OnlyShowIn
                ):
                    if verbose:
                        print(
                            "Ignoring file, it must only start in specific environments (%s): %s"
                            % (", ".join(app.OnlyShowIn), app.filename),
                            file=sys.stderr,
                        )
                    continue
                elif (
                    app.NotShowIn
                    and args.environment
                    and args.environment in app.NotShowIn
                ):
                    if verbose:
                        print(
                            "Ignoring file, it must not start in specific environments (%s): %s"
                            % (", ".join(app.NotShowIn), app.filename),
                            file=sys.stderr,
                        )
                    continue

                autostart_files.append(app)

    return sorted(autostart_files)


def _test(args):
    """
    run tests
    """
    import doctest

    doctest.testmod()


def _autostart(args):
    """
    perform autostart
    """
    if args.dryrun and args.verbose:
        print("Dry run, nothing is executed.", file=sys.stderr)

    exit_value = 0
    for app in get_autostart_files(args, verbose=args.verbose):
        try:
            app.execute(term=args.term, dryrun=args.dryrun, verbose=args.verbose)
        except Exception as ex:
            exit_value = 1
            print(
                "Execution failed: %s%s%s" % (app.filename, os.linesep, ex),
                file=sys.stderr,
            )
    return exit_value


def _run(args):
    """
    execute specified DesktopEntry files, or specified action of each file
    """
    if args.dryrun and args.verbose:
        print("Dry run, nothing is executed.", file=sys.stderr)

    exit_value = 0
    if not args.files:
        print("Nothing to execute, no DesktopEntry files specified!", file=sys.stderr)
        parser.print_help()
        exit_value = 1
    else:
        for f in args.files:
            try:
                app = Application(f)
                app.execute(
                    action=args.action,
                    term=args.term,
                    wait=args.wait,
                    dryrun=args.dryrun,
                    verbose=args.verbose,
                )
            except ValueError as ex:
                print(ex, file=sys.stderr)
            except IOError as ex:
                print(ex, file=sys.stderr)
            except Exception as ex:
                exit_value = 1
                print("Execution failed: %s%s%s" % (f, os.linesep, ex), file=sys.stderr)
    return exit_value


def _create(args):
    """
    create a new DesktopEntry file from the given argument
    """
    target = args.create[0]
    if args.verbose:
        print("Creating DesktopEntry for file %s." % target)

    de = DesktopEntry.fromfile(target)
    if args.verbose:
        print("Type: %s" % de.Type)

    # determine output file
    output = ".".join(
        (os.path.basename(target), "directory" if de.Type == "Directory" else "desktop")
    )
    if args.targetdir:
        output = os.path.join(args.targetdir[0], output)
    elif len(args.create) > 1:
        output = args.create[1]

    if args.verbose:
        print("Output: %s" % output)

    try:
        targetfile = sys.stdout if output == "-" else open(output, "w")
    except FileNotFoundError:
        print("Target directory does not exist: %s" % os.path.dirname(output))
        return 1
    de.write(targetfile)

    if args.targetdir and len(args.create) > 1:
        args.create = args.create[1:]
        return _create(args)
    return 0


def _property(args):
    """
    Display DesktopEntry property value
    """
    exit_value = 0
    if not args.files:
        print("Nothing to parse, no DesktopEntry files specified!", file=sys.stderr)
        parser.print_help()
        exit_value = 1
    else:
        properties = (
            "Type",
            "Version",
            "Name",
            "NoDisplay",
            "Hidden",
            "OnlyShowIn",
            "NotShowIn",
            "TryExec",
            "Exec",
            "Path",
            "Terminal",
            "Actions",
            "StartupNotify",
            "StartupWMClass",
            "URL",
        )
        action_properties = ("Name", "Exec")
        property = args.property[0]
        for f in args.files:
            try:
                app = Application(f)

                allowed_properties = properties
                error_keyword = "Entry"
                if args.action:
                    app = Action(owner=app, identifier=args.action)
                    allowed_properties = action_properties
                    error_keyword = "Action"

                if property in allowed_properties:
                    print(getattr(app, property))
                else:
                    exit_value = 1
                    print(
                        "'%s' is not a valid Desktop %s property."
                        % (property, error_keyword),
                        file=sys.stderr,
                    )
            except ValueError as ex:
                print(ex, file=sys.stderr)
            except IOError as ex:
                print(ex, file=sys.stderr)
            except Exception as ex:
                exit_value = 1
                print("Parse failed: %s%s%s" % (f, os.linesep, ex), file=sys.stderr)
    return exit_value


# start execution
if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser(
        usage="%(prog)s [options] [DesktopEntryFile [DesktopEntryFile ...]]",
        description="dex, DesktopEntry Execution, is a program to generate and execute DesktopEntry files of the type Application",
        epilog="Example usage: list autostart programs: dex -ad",
    )
    parser.add_argument(
        "--action",
        dest="action",
        help='identifier of an "additional application action" to operate on. Also known as a quicklist/jumplist entry',
    )
    parser.add_argument(
        "--test", action="store_true", dest="test", help="perform a self-test"
    )
    parser.add_argument(
        "-v", "--verbose", action="store_true", dest="verbose", help="verbose output"
    )
    parser.add_argument(
        "-V", "--version", action="version", version="%%(prog)s %s" % __version__
    )
    parser.add_argument("files", nargs="*", help="DesktopEntry files")

    property = parser.add_argument_group("property")
    property.add_argument(
        "-p",
        "--property",
        nargs=1,
        dest="property",
        help="display DesktopEntry property value. Supported properties are: Type, Version, Name, NoDisplay, Hidden, OnlyShowIn, NotShowIn, TryExec, Exec, Path, Terminal, Actions, StartupNotify, StartupWMClass, URL. For ACTIONs, only Name and Exec are supported",
    )

    run = parser.add_argument_group("run")
    run.add_argument(
        "-a",
        "--autostart",
        action="store_true",
        dest="autostart",
        help="autostart programs",
    )
    run.add_argument(
        "-d",
        "--dry-run",
        action="store_true",
        dest="dryrun",
        help="dry run, don't execute any command",
    )
    run.add_argument(
        "-e",
        "--environment",
        dest="environment",
        help="specify the Desktop Environment an autostart should be performed for; works only in combination with --autostart",
        default=os.environ.get("XDG_CURRENT_DESKTOP"),
    )
    run.add_argument(
        "-s",
        "--search-paths",
        nargs=1,
        dest="searchpaths",
        help="colon separated list of paths to search for desktop files, overriding the default search list",
    )
    run.add_argument(
        "--term",
        dest="term",
        help="the terminal emulator that will be used to run the program if Terminal=true is set in the desktop file, defaults to x-terminal-emulator",
    )
    run.add_argument(
        "-w",
        "--wait",
        action="store_true",
        dest="wait",
        help="block until the program exits",
    )

    create = parser.add_argument_group("create")
    create.add_argument(
        "-c",
        "--create",
        nargs="+",
        dest="create",
        help="create a DesktopEntry file for the given program. If a second argument is provided it's taken as output filename or written to stdout (filename: -). By default a new file with the postfix .desktop is created",
    )
    create.add_argument(
        "-t",
        "--target-directory",
        nargs=1,
        dest="targetdir",
        help="create files in target directory",
    )

    parser.set_defaults(
        func=_run,
        term="x-terminal-emulator",
        wait=False,
        dryrun=False,
        test=False,
        autostart=False,
        verbose=False,
    )

    args = parser.parse_args()
    if args.autostart:
        args.func = _autostart
    elif args.create:
        args.func = _create
    elif args.test:
        args.func = _test
    elif args.property:
        args.func = _property

    sys.exit(args.func(args))