summaryrefslogtreecommitdiff
path: root/xdg/Menu.py
blob: 01b59f0fd4956eeaa87ff448ff55f3b0ce4c4013 (plain)
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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
"""
Implementation of the XDG Menu Specification
http://standards.freedesktop.org/menu-spec/

Example code:

from xdg.Menu import parse, Menu, MenuEntry

def print_menu(menu, tab=0):
  for submenu in menu.Entries:
    if isinstance(submenu, Menu):
      print ("\t" * tab) + unicode(submenu)
      print_menu(submenu, tab+1)
    elif isinstance(submenu, MenuEntry):
      print ("\t" * tab) + unicode(submenu.DesktopEntry)

print_menu(parse())
"""

import os
import locale
import subprocess
import ast
try:
    import xml.etree.cElementTree as etree
except ImportError:
    import xml.etree.ElementTree as etree

from xdg.BaseDirectory import xdg_data_dirs, xdg_config_dirs
from xdg.DesktopEntry import DesktopEntry
from xdg.Exceptions import ParsingError, debug
from xdg.util import PY3

import xdg.Locale
import xdg.Config


def _strxfrm(s):
    """Wrapper around locale.strxfrm that accepts unicode strings on Python 2.

    See Python bug #2481.
    """
    if (not PY3) and isinstance(s, unicode):
        s = s.encode('utf-8')
    return locale.strxfrm(s)


class Menu:
    """Menu containing sub menus under menu.Entries

    Contains both Menu and MenuEntry items.
    """
    def __init__(self):
        # Public stuff
        self.Name = ""
        self.Directory = None
        self.Entries = []
        self.Doc = ""
        self.Filename = ""
        self.Depth = 0
        self.Parent = None
        self.NotInXml = False

        # Can be one of Deleted/NoDisplay/Hidden/Empty/NotShowIn or True
        self.Show = True
        self.Visible = 0

        # Private stuff, only needed for parsing
        self.AppDirs = []
        self.DefaultLayout = None
        self.Deleted = "notset"
        self.Directories = []
        self.DirectoryDirs = []
        self.Layout = None
        self.MenuEntries = []
        self.Moves = []
        self.OnlyUnallocated = "notset"
        self.Rules = []
        self.Submenus = []

    def __str__(self):
        return self.Name

    def __add__(self, other):
        for dir in other.AppDirs:
            self.AppDirs.append(dir)

        for dir in other.DirectoryDirs:
            self.DirectoryDirs.append(dir)

        for directory in other.Directories:
            self.Directories.append(directory)

        if other.Deleted != "notset":
            self.Deleted = other.Deleted

        if other.OnlyUnallocated != "notset":
            self.OnlyUnallocated = other.OnlyUnallocated

        if other.Layout:
            self.Layout = other.Layout

        if other.DefaultLayout:
            self.DefaultLayout = other.DefaultLayout

        for rule in other.Rules:
            self.Rules.append(rule)

        for move in other.Moves:
            self.Moves.append(move)

        for submenu in other.Submenus:
            self.addSubmenu(submenu)

        return self

    # FIXME: Performance: cache getName()
    def __cmp__(self, other):
        return locale.strcoll(self.getName(), other.getName())

    def _key(self):
        """Key function for locale-aware sorting."""
        return _strxfrm(self.getName())

    def __lt__(self, other):
        try:
            other = other._key()
        except AttributeError:
            pass
        return self._key() < other

    def __eq__(self, other):
        try:
            return self.Name == unicode(other)
        except NameError:  # unicode() becomes str() in Python 3
            return self.Name == str(other)

    """ PUBLIC STUFF """
    def getEntries(self, hidden=False):
        """Interator for a list of Entries visible to the user."""
        for entry in self.Entries:
            if hidden:
                yield entry
            elif entry.Show:
                yield entry

    # FIXME: Add searchEntry/seaqrchMenu function
    # search for name/comment/genericname/desktopfileide
    # return multiple items

    def getMenuEntry(self, desktopfileid, deep=False):
        """Searches for a MenuEntry with a given DesktopFileID."""
        for menuentry in self.MenuEntries:
            if menuentry.DesktopFileID == desktopfileid:
                return menuentry
        if deep:
            for submenu in self.Submenus:
                submenu.getMenuEntry(desktopfileid, deep)

    def getMenu(self, path):
        """Searches for a Menu with a given path."""
        array = path.split("/", 1)
        for submenu in self.Submenus:
            if submenu.Name == array[0]:
                if len(array) > 1:
                    return submenu.getMenu(array[1])
                else:
                    return submenu

    def getPath(self, org=False, toplevel=False):
        """Returns this menu's path in the menu structure."""
        parent = self
        names = []
        while 1:
            if org:
                names.append(parent.Name)
            else:
                names.append(parent.getName())
            if parent.Depth > 0:
                parent = parent.Parent
            else:
                break
        names.reverse()
        path = ""
        if not toplevel:
            names.pop(0)
        for name in names:
            path = os.path.join(path, name)
        return path

    def getName(self):
        """Returns the menu's localised name."""
        try:
            return self.Directory.DesktopEntry.getName()
        except AttributeError:
            return self.Name

    def getGenericName(self):
        """Returns the menu's generic name."""
        try:
            return self.Directory.DesktopEntry.getGenericName()
        except AttributeError:
            return ""

    def getComment(self):
        """Returns the menu's comment text."""
        try:
            return self.Directory.DesktopEntry.getComment()
        except AttributeError:
            return ""

    def getIcon(self):
        """Returns the menu's icon, filename or simple name"""
        try:
            return self.Directory.DesktopEntry.getIcon()
        except AttributeError:
            return ""

    def sort(self):
        self.Entries = []
        self.Visible = 0

        for submenu in self.Submenus:
            submenu.sort()

        _submenus = set()
        _entries = set()

        for order in self.Layout.order:
            if order[0] == "Filename":
                _entries.add(order[1])
            elif order[0] == "Menuname":
                _submenus.add(order[1])

        for order in self.Layout.order:
            if order[0] == "Separator":
                separator = Separator(self)
                if len(self.Entries) > 0 and isinstance(self.Entries[-1], Separator):
                    separator.Show = False
                self.Entries.append(separator)
            elif order[0] == "Filename":
                menuentry = self.getMenuEntry(order[1])
                if menuentry:
                    self.Entries.append(menuentry)
            elif order[0] == "Menuname":
                submenu = self.getMenu(order[1])
                if submenu:
                    if submenu.Layout.inline:
                        self.merge_inline(submenu)
                    else:
                        self.Entries.append(submenu)
            elif order[0] == "Merge":
                if order[1] == "files" or order[1] == "all":
                    self.MenuEntries.sort()
                    for menuentry in self.MenuEntries:
                        if menuentry.DesktopFileID not in _entries:
                            self.Entries.append(menuentry)
                elif order[1] == "menus" or order[1] == "all":
                    self.Submenus.sort()
                    for submenu in self.Submenus:
                        if submenu.Name not in _submenus:
                            if submenu.Layout.inline:
                                self.merge_inline(submenu)
                            else:
                                self.Entries.append(submenu)

        # getHidden / NoDisplay / OnlyShowIn / NotOnlyShowIn / Deleted / NoExec
        for entry in self.Entries:
            entry.Show = True
            self.Visible += 1
            if isinstance(entry, Menu):
                if entry.Deleted is True:
                    entry.Show = "Deleted"
                    self.Visible -= 1
                elif isinstance(entry.Directory, MenuEntry):
                    if entry.Directory.DesktopEntry.getNoDisplay():
                        entry.Show = "NoDisplay"
                        self.Visible -= 1
                    elif entry.Directory.DesktopEntry.getHidden():
                        entry.Show = "Hidden"
                        self.Visible -= 1
            elif isinstance(entry, MenuEntry):
                if entry.DesktopEntry.getNoDisplay():
                    entry.Show = "NoDisplay"
                    self.Visible -= 1
                elif entry.DesktopEntry.getHidden():
                    entry.Show = "Hidden"
                    self.Visible -= 1
                elif entry.DesktopEntry.getTryExec() and not entry.DesktopEntry.findTryExec():
                    entry.Show = "NoExec"
                    self.Visible -= 1
                elif xdg.Config.windowmanager:
                    if (entry.DesktopEntry.OnlyShowIn != [] and (
                            xdg.Config.windowmanager not in entry.DesktopEntry.OnlyShowIn
                        )
                    ) or (
                        xdg.Config.windowmanager in entry.DesktopEntry.NotShowIn
                    ):
                        entry.Show = "NotShowIn"
                        self.Visible -= 1
            elif isinstance(entry, Separator):
                self.Visible -= 1

        # remove separators at the beginning and at the end
        if len(self.Entries) > 0:
            if isinstance(self.Entries[0], Separator):
                self.Entries[0].Show = False
        if len(self.Entries) > 1:
            if isinstance(self.Entries[-1], Separator):
                self.Entries[-1].Show = False

        # show_empty tag
        for entry in self.Entries[:]:
            if isinstance(entry, Menu) and not entry.Layout.show_empty and entry.Visible == 0:
                entry.Show = "Empty"
                self.Visible -= 1
                if entry.NotInXml is True:
                    self.Entries.remove(entry)

    """ PRIVATE STUFF """
    def addSubmenu(self, newmenu):
        for submenu in self.Submenus:
            if submenu == newmenu:
                submenu += newmenu
                break
        else:
            self.Submenus.append(newmenu)
            newmenu.Parent = self
            newmenu.Depth = self.Depth + 1

    # inline tags
    def merge_inline(self, submenu):
        """Appends a submenu's entries to this menu
        See the <Menuname> section of the spec about the "inline" attribute
        """
        if len(submenu.Entries) == 1 and submenu.Layout.inline_alias:
            menuentry = submenu.Entries[0]
            menuentry.DesktopEntry.set("Name", submenu.getName(), locale=True)
            menuentry.DesktopEntry.set("GenericName", submenu.getGenericName(), locale=True)
            menuentry.DesktopEntry.set("Comment", submenu.getComment(), locale=True)
            self.Entries.append(menuentry)
        elif len(submenu.Entries) <= submenu.Layout.inline_limit or submenu.Layout.inline_limit == 0:
            if submenu.Layout.inline_header:
                header = Header(submenu.getName(), submenu.getGenericName(), submenu.getComment())
                self.Entries.append(header)
            for entry in submenu.Entries:
                self.Entries.append(entry)
        else:
            self.Entries.append(submenu)


class Move:
    "A move operation"
    def __init__(self, old="", new=""):
        self.Old = old
        self.New = new

    def __cmp__(self, other):
        return cmp(self.Old, other.Old)


class Layout:
    "Menu Layout class"
    def __init__(self, show_empty=False, inline=False, inline_limit=4,
                 inline_header=True, inline_alias=False):
        self.show_empty = show_empty
        self.inline = inline
        self.inline_limit = inline_limit
        self.inline_header = inline_header
        self.inline_alias = inline_alias
        self._order = []
        self._default_order = [
            ['Merge', 'menus'],
            ['Merge', 'files']
        ]

    @property
    def order(self):
        return self._order if self._order else self._default_order

    @order.setter
    def order(self, order):
        self._order = order


class Rule:
    """Include / Exclude Rules Class"""

    TYPE_INCLUDE, TYPE_EXCLUDE = 0, 1

    @classmethod
    def fromFilename(cls, type, filename):
        tree = ast.Expression(
            body=ast.Compare(
                left=ast.Str(filename),
                ops=[ast.Eq()],
                comparators=[ast.Attribute(
                    value=ast.Name(id='menuentry', ctx=ast.Load()),
                    attr='DesktopFileID',
                    ctx=ast.Load()
                )]
            ),
            lineno=1, col_offset=0
        )
        ast.fix_missing_locations(tree)
        rule = Rule(type, tree)
        return rule

    def __init__(self, type, expression):
        # Type is TYPE_INCLUDE or TYPE_EXCLUDE
        self.Type = type
        # expression is ast.Expression
        self.expression = expression
        self.code = compile(self.expression, '<compiled-menu-rule>', 'eval')

    def __str__(self):
        return ast.dump(self.expression)

    def apply(self, menuentries, run):
        for menuentry in menuentries:
            if run == 2 and (menuentry.MatchedInclude is True or
                             menuentry.Allocated is True):
                continue
            if eval(self.code):
                if self.Type is Rule.TYPE_INCLUDE:
                    menuentry.Add = True
                    menuentry.MatchedInclude = True
                else:
                    menuentry.Add = False
        return menuentries


class MenuEntry:
    "Wrapper for 'Menu Style' Desktop Entries"

    TYPE_USER = "User"
    TYPE_SYSTEM = "System"
    TYPE_BOTH = "Both"

    def __init__(self, filename, dir="", prefix=""):
        # Create entry
        self.DesktopEntry = DesktopEntry(os.path.join(dir, filename))
        self.setAttributes(filename, dir, prefix)

        # Can be one of Deleted/Hidden/Empty/NotShowIn/NoExec or True
        self.Show = True

        # Semi-Private
        self.Original = None
        self.Parents = []

        # Private Stuff
        self.Allocated = False
        self.Add = False
        self.MatchedInclude = False

        # Caching
        self.Categories = self.DesktopEntry.getCategories()

    def save(self):
        """Save any changes to the desktop entry."""
        if self.DesktopEntry.tainted:
            self.DesktopEntry.write()

    def getDir(self):
        """Return the directory containing the desktop entry file."""
        return self.DesktopEntry.filename.replace(self.Filename, '')

    def getType(self):
        """Return the type of MenuEntry, System/User/Both"""
        if not xdg.Config.root_mode:
            if self.Original:
                return self.TYPE_BOTH
            elif xdg_data_dirs[0] in self.DesktopEntry.filename:
                return self.TYPE_USER
            else:
                return self.TYPE_SYSTEM
        else:
            return self.TYPE_USER

    def setAttributes(self, filename, dir="", prefix=""):
        self.Filename = filename
        self.Prefix = prefix
        self.DesktopFileID = os.path.join(prefix, filename).replace("/", "-")

        if not os.path.isabs(self.DesktopEntry.filename):
            self.__setFilename()

    def updateAttributes(self):
        if self.getType() == "System":
            self.Original = MenuEntry(self.Filename, self.getDir(), self.Prefix)
            self.__setFilename()

    def __setFilename(self):
        if not xdg.Config.root_mode:
            path = xdg_data_dirs[0]
        else:
            path = xdg_data_dirs[1]

        if self.DesktopEntry.getType() == "Application":
            dir_ = os.path.join(path, "applications")
        else:
            dir_ = os.path.join(path, "desktop-directories")

        self.DesktopEntry.filename = os.path.join(dir_, self.Filename)

    def __cmp__(self, other):
        return locale.strcoll(self.DesktopEntry.getName(), other.DesktopEntry.getName())

    def _key(self):
        """Key function for locale-aware sorting."""
        return _strxfrm(self.DesktopEntry.getName())

    def __lt__(self, other):
        try:
            other = other._key()
        except AttributeError:
            pass
        return self._key() < other

    def __eq__(self, other):
        if self.DesktopFileID == str(other):
            return True
        else:
            return False

    def __repr__(self):
        return self.DesktopFileID


class Separator:
    "Just a dummy class for Separators"
    def __init__(self, parent):
        self.Parent = parent
        self.Show = True


class Header:
    "Class for Inline Headers"
    def __init__(self, name, generic_name, comment):
        self.Name = name
        self.GenericName = generic_name
        self.Comment = comment

    def __str__(self):
        return self.Name


TYPE_DIR, TYPE_FILE = 0, 1


def _check_file_path(value, filename, type):
    path = os.path.dirname(filename)
    if not os.path.isabs(value):
        value = os.path.join(path, value)
    value = os.path.abspath(value)
    if not os.path.exists(value):
        return False
    if type == TYPE_DIR and os.path.isdir(value):
        return value
    if type == TYPE_FILE and os.path.isfile(value):
        return value
    return False


def _get_menu_file_path(filename):
    dirs = list(xdg_config_dirs)
    if xdg.Config.root_mode is True:
        dirs.pop(0)
    for d in dirs:
        menuname = os.path.join(d, "menus", filename)
        if os.path.isfile(menuname):
            return menuname


def _to_bool(value):
    if isinstance(value, bool):
        return value
    return value.lower() == "true"


# remove duplicate entries from a list
def _dedupe(_list):
    _set = {}
    _list.reverse()
    _list = [_set.setdefault(e, e) for e in _list if e not in _set]
    _list.reverse()
    return _list


class XMLMenuBuilder(object):

    def __init__(self, debug=False):
        self.debug = debug

    def parse(self, filename=None):
        """Load an applications.menu file.

        filename : str, optional
          The default is ``$XDG_CONFIG_DIRS/menus/${XDG_MENU_PREFIX}applications.menu``.
        """
        # convert to absolute path
        if filename and not os.path.isabs(filename):
            filename = _get_menu_file_path(filename)
        # use default if no filename given
        if not filename:
            candidate = os.environ.get('XDG_MENU_PREFIX', '') + "applications.menu"
            filename = _get_menu_file_path(candidate)
        if not filename:
            raise ParsingError('File not found', "/etc/xdg/menus/%s" % candidate)
        # check if it is a .menu file
        if not filename.endswith(".menu"):
            raise ParsingError('Not a .menu file', filename)
        # create xml parser
        try:
            tree = etree.parse(filename)
        except:
            raise ParsingError('Not a valid .menu file', filename)

        # parse menufile
        self._merged_files = set()
        self._directory_dirs = set()
        self.cache = MenuEntryCache()

        menu = self.parse_menu(tree.getroot(), filename)
        menu.tree = tree
        menu.filename = filename

        self.handle_moves(menu)
        self.post_parse(menu)

        # generate the menu
        self.generate_not_only_allocated(menu)
        self.generate_only_allocated(menu)

        # and finally sort
        menu.sort()

        return menu

    def parse_menu(self, node, filename):
        menu = Menu()
        self.parse_node(node, filename, menu)
        return menu

    def parse_node(self, node, filename, parent=None):
        num_children = len(node)
        for child in node:
            tag, text = child.tag, child.text
            text = text.strip() if text else None
            if tag == 'Menu':
                menu = self.parse_menu(child, filename)
                parent.addSubmenu(menu)
            elif tag == 'AppDir' and text:
                self.parse_app_dir(text, filename, parent)
            elif tag == 'DefaultAppDirs':
                self.parse_default_app_dir(filename, parent)
            elif tag == 'DirectoryDir' and text:
                self.parse_directory_dir(text, filename, parent)
            elif tag == 'DefaultDirectoryDirs':
                self.parse_default_directory_dir(filename, parent)
            elif tag == 'Name' and text:
                parent.Name = text
            elif tag == 'Directory' and text:
                parent.Directories.append(text)
            elif tag == 'OnlyUnallocated':
                parent.OnlyUnallocated = True
            elif tag == 'NotOnlyUnallocated':
                parent.OnlyUnallocated = False
            elif tag == 'Deleted':
                parent.Deleted = True
            elif tag == 'NotDeleted':
                parent.Deleted = False
            elif tag == 'Include' or tag == 'Exclude':
                parent.Rules.append(self.parse_rule(child))
            elif tag == 'MergeFile':
                if child.attrib.get("type", None) == "parent":
                    self.parse_merge_file("applications.menu", child, filename, parent)
                elif text:
                    self.parse_merge_file(text, child, filename, parent)
            elif tag == 'MergeDir' and text:
                self.parse_merge_dir(text, child, filename, parent)
            elif tag == 'DefaultMergeDirs':
                self.parse_default_merge_dirs(child, filename, parent)
            elif tag == 'Move':
                parent.Moves.append(self.parse_move(child))
            elif tag == 'Layout':
                if num_children > 1:
                    parent.Layout = self.parse_layout(child)
            elif tag == 'DefaultLayout':
                if num_children > 1:
                    parent.DefaultLayout = self.parse_layout(child)
            elif tag == 'LegacyDir' and text:
                self.parse_legacy_dir(text, child.attrib.get("prefix", ""), filename, parent)
            elif tag == 'KDELegacyDirs':
                self.parse_kde_legacy_dirs(filename, parent)

    def parse_layout(self, node):
        layout = Layout(
            show_empty=_to_bool(node.attrib.get("show_empty", False)),
            inline=_to_bool(node.attrib.get("inline", False)),
            inline_limit=int(node.attrib.get("inline_limit", 4)),
            inline_header=_to_bool(node.attrib.get("inline_header", True)),
            inline_alias=_to_bool(node.attrib.get("inline_alias", False))
        )
        for child in node:
            tag, text = child.tag, child.text
            text = text.strip() if text else None
            if tag == "Menuname" and text:
                layout.order.append([
                    "Menuname",
                    text,
                    _to_bool(child.attrib.get("show_empty", False)),
                    _to_bool(child.attrib.get("inline", False)),
                    int(child.attrib.get("inline_limit", 4)),
                    _to_bool(child.attrib.get("inline_header", True)),
                    _to_bool(child.attrib.get("inline_alias", False))
                ])
            elif tag == "Separator":
                layout.order.append(['Separator'])
            elif tag == "Filename" and text:
                layout.order.append(["Filename", text])
            elif tag == "Merge":
                layout.order.append([
                    "Merge",
                    child.attrib.get("type", "all")
                ])
        return layout

    def parse_move(self, node):
        old, new = "", ""
        for child in node:
            tag, text = child.tag, child.text
            text = text.strip() if text else None
            if tag == "Old" and text:
                old = text
            elif tag == "New" and text:
                new = text
        return Move(old, new)

    # ---------- <Rule> parsing

    def parse_rule(self, node):
        type = Rule.TYPE_INCLUDE if node.tag == 'Include' else Rule.TYPE_EXCLUDE
        tree = ast.Expression(lineno=1, col_offset=0)
        expr = self.parse_bool_op(node, ast.Or())
        if expr:
            tree.body = expr
        else:
            tree.body = ast.Name('False', ast.Load())
        ast.fix_missing_locations(tree)
        return Rule(type, tree)

    def parse_bool_op(self, node, operator):
        values = []
        for child in node:
            rule = self.parse_rule_node(child)
            if rule:
                values.append(rule)
        num_values = len(values)
        if num_values > 1:
            return ast.BoolOp(operator, values)
        elif num_values == 1:
            return values[0]
        return None

    def parse_rule_node(self, node):
        tag = node.tag
        if tag == 'Or':
            return self.parse_bool_op(node, ast.Or())
        elif tag == 'And':
            return self.parse_bool_op(node, ast.And())
        elif tag == 'Not':
            expr = self.parse_bool_op(node, ast.Or())
            return ast.UnaryOp(ast.Not(), expr) if expr else None
        elif tag == 'All':
            return ast.Name('True', ast.Load())
        elif tag == 'Category':
            category = node.text
            return ast.Compare(
                left=ast.Str(category),
                ops=[ast.In()],
                comparators=[ast.Attribute(
                    value=ast.Name(id='menuentry', ctx=ast.Load()),
                    attr='Categories',
                    ctx=ast.Load()
                )]
            )
        elif tag == 'Filename':
            filename = node.text
            return ast.Compare(
                left=ast.Str(filename),
                ops=[ast.Eq()],
                comparators=[ast.Attribute(
                    value=ast.Name(id='menuentry', ctx=ast.Load()),
                    attr='DesktopFileID',
                    ctx=ast.Load()
                )]
            )

    # ---------- App/Directory Dir Stuff

    def parse_app_dir(self, value, filename, parent):
        value = _check_file_path(value, filename, TYPE_DIR)
        if value:
            parent.AppDirs.append(value)

    def parse_default_app_dir(self, filename, parent):
        for d in reversed(xdg_data_dirs):
            self.parse_app_dir(os.path.join(d, "applications"), filename, parent)

    def parse_directory_dir(self, value, filename, parent):
        value = _check_file_path(value, filename, TYPE_DIR)
        if value:
            parent.DirectoryDirs.append(value)

    def parse_default_directory_dir(self, filename, parent):
        for d in reversed(xdg_data_dirs):
            self.parse_directory_dir(os.path.join(d, "desktop-directories"), filename, parent)

    # ---------- Merge Stuff

    def parse_merge_file(self, value, child, filename, parent):
        if child.attrib.get("type", None) == "parent":
            for d in xdg_config_dirs:
                rel_file = filename.replace(d, "").strip("/")
                if rel_file != filename:
                    for p in xdg_config_dirs:
                        if d == p:
                            continue
                        if os.path.isfile(os.path.join(p, rel_file)):
                            self.merge_file(os.path.join(p, rel_file), child, parent)
                            break
        else:
            value = _check_file_path(value, filename, TYPE_FILE)
            if value:
                self.merge_file(value, child, parent)

    def parse_merge_dir(self, value, child, filename, parent):
        value = _check_file_path(value, filename, TYPE_DIR)
        if value:
            for item in os.listdir(value):
                try:
                    if item.endswith(".menu"):
                        self.merge_file(os.path.join(value, item), child, parent)
                except UnicodeDecodeError:
                    continue

    def parse_default_merge_dirs(self, child, filename, parent):
        basename = os.path.splitext(os.path.basename(filename))[0]
        for d in reversed(xdg_config_dirs):
            self.parse_merge_dir(os.path.join(d, "menus", basename + "-merged"), child, filename, parent)

    def merge_file(self, filename, child, parent):
        # check for infinite loops
        if filename in self._merged_files:
            if debug:
                raise ParsingError('Infinite MergeFile loop detected', filename)
            else:
                return
        self._merged_files.add(filename)
        # load file
        try:
            tree = etree.parse(filename)
        except IOError:
            if self.debug:
                raise ParsingError('File not found', filename)
            else:
                return
        except:
            if self.debug:
                raise ParsingError('Not a valid .menu file', filename)
            else:
                return
        root = tree.getroot()
        # append file
        for child in root:
            self.parse_node(child, filename, parent)
            break

    # ---------- Legacy Dir Stuff

    def parse_legacy_dir(self, dir_, prefix, filename, parent):
        m = self.merge_legacy_dir(dir_, prefix, filename, parent)
        if m:
            parent += m

    def merge_legacy_dir(self, dir_, prefix, filename, parent):
        dir_ = _check_file_path(dir_, filename, TYPE_DIR)
        if dir_ and dir_ not in self._directory_dirs:
            self._directory_dirs.add(dir_)
            m = Menu()
            m.AppDirs.append(dir_)
            m.DirectoryDirs.append(dir_)
            m.Name = os.path.basename(dir_)
            m.NotInXml = True

            for item in os.listdir(dir_):
                try:
                    if item == ".directory":
                        m.Directories.append(item)
                    elif os.path.isdir(os.path.join(dir_, item)):
                        m.addSubmenu(self.merge_legacy_dir(
                            os.path.join(dir_, item),
                            prefix,
                            filename,
                            parent
                        ))
                except UnicodeDecodeError:
                    continue

            self.cache.add_menu_entries([dir_], prefix, True)
            menuentries = self.cache.get_menu_entries([dir_], False)

            for menuentry in menuentries:
                categories = menuentry.Categories
                if len(categories) == 0:
                    r = Rule.fromFilename(Rule.TYPE_INCLUDE, menuentry.DesktopFileId)
                    m.rules.append(r)
                if not dir_ in parent.AppDirs:
                    categories.append("Legacy")
                    menuentry.Categories = categories

            return m

    def parse_kde_legacy_dirs(self, filename, parent):
        try:
            proc = subprocess.Popen(
                ['kde-config', '--path', 'apps'],
                stdout=subprocess.PIPE,
                universal_newlines=True
            )
            output = proc.communicate()[0].splitlines()
        except OSError:
            # If kde-config doesn't exist, ignore this.
            return
        try:
            for dir_ in output[0].split(":"):
                self.parse_legacy_dir(dir_, "kde", filename, parent)
        except IndexError:
            pass

    def post_parse(self, menu):
        # unallocated / deleted
        if menu.Deleted == "notset":
            menu.Deleted = False
        if menu.OnlyUnallocated == "notset":
            menu.OnlyUnallocated = False

        # Layout Tags
        if not menu.Layout or not menu.DefaultLayout:
            if menu.DefaultLayout:
                menu.Layout = menu.DefaultLayout
            elif menu.Layout:
                if menu.Depth > 0:
                    menu.DefaultLayout = menu.Parent.DefaultLayout
                else:
                    menu.DefaultLayout = Layout()
            else:
                if menu.Depth > 0:
                    menu.Layout = menu.Parent.DefaultLayout
                    menu.DefaultLayout = menu.Parent.DefaultLayout
                else:
                    menu.Layout = Layout()
                    menu.DefaultLayout = Layout()

        # add parent's app/directory dirs
        if menu.Depth > 0:
            menu.AppDirs = menu.Parent.AppDirs + menu.AppDirs
            menu.DirectoryDirs = menu.Parent.DirectoryDirs + menu.DirectoryDirs

        # remove duplicates
        menu.Directories = _dedupe(menu.Directories)
        menu.DirectoryDirs = _dedupe(menu.DirectoryDirs)
        menu.AppDirs = _dedupe(menu.AppDirs)

        # go recursive through all menus
        for submenu in menu.Submenus:
            self.post_parse(submenu)

        # reverse so handling is easier
        menu.Directories.reverse()
        menu.DirectoryDirs.reverse()
        menu.AppDirs.reverse()

        # get the valid .directory file out of the list
        for directory in menu.Directories:
            for dir in menu.DirectoryDirs:
                if os.path.isfile(os.path.join(dir, directory)):
                    menuentry = MenuEntry(directory, dir)
                    if not menu.Directory:
                        menu.Directory = menuentry
                    elif menuentry.Type == MenuEntry.TYPE_SYSTEM:
                        if menu.Directory.Type == MenuEntry.TYPE_USER:
                            menu.Directory.Original = menuentry
            if menu.Directory:
                break

    # Finally generate the menu
    def generate_not_only_allocated(self, menu):
        for submenu in menu.Submenus:
            self.generate_not_only_allocated(submenu)

        if menu.OnlyUnallocated is False:
            self.cache.add_menu_entries(menu.AppDirs)
            menuentries = []
            for rule in menu.Rules:
                menuentries = rule.apply(self.cache.get_menu_entries(menu.AppDirs), 1)

            for menuentry in menuentries:
                if menuentry.Add is True:
                    menuentry.Parents.append(menu)
                    menuentry.Add = False
                    menuentry.Allocated = True
                    menu.MenuEntries.append(menuentry)

    def generate_only_allocated(self, menu):
        for submenu in menu.Submenus:
            self.generate_only_allocated(submenu)

        if menu.OnlyUnallocated is True:
            self.cache.add_menu_entries(menu.AppDirs)
            menuentries = []
            for rule in menu.Rules:
                menuentries = rule.apply(self.cache.get_menu_entries(menu.AppDirs), 2)
            for menuentry in menuentries:
                if menuentry.Add is True:
                    menuentry.Parents.append(menu)
                #   menuentry.Add = False
                #   menuentry.Allocated = True
                    menu.MenuEntries.append(menuentry)

    def handle_moves(self, menu):
        for submenu in menu.Submenus:
            self.handle_moves(submenu)
        # parse move operations
        for move in menu.Moves:
            move_from_menu = menu.getMenu(move.Old)
            if move_from_menu:
                # FIXME: this is assigned, but never used...
                move_to_menu = menu.getMenu(move.New)

                menus = move.New.split("/")
                oldparent = None
                while len(menus) > 0:
                    if not oldparent:
                        oldparent = menu
                    newmenu = oldparent.getMenu(menus[0])
                    if not newmenu:
                        newmenu = Menu()
                        newmenu.Name = menus[0]
                        if len(menus) > 1:
                            newmenu.NotInXml = True
                        oldparent.addSubmenu(newmenu)
                    oldparent = newmenu
                    menus.pop(0)

                newmenu += move_from_menu
                move_from_menu.parent.Submenus.remove(move_from_menu)


class MenuEntryCache:
    "Class to cache Desktop Entries"
    def __init__(self):
        self.cacheEntries = {}
        self.cacheEntries['legacy'] = []
        self.cache = {}

    def add_menu_entries(self, dirs, prefix="", legacy=False):
        for dir_ in dirs:
            if not dir_ in self.cacheEntries:
                self.cacheEntries[dir_] = []
                self.__addFiles(dir_, "", prefix, legacy)

    def __addFiles(self, dir_, subdir, prefix, legacy):
        for item in os.listdir(os.path.join(dir_, subdir)):
            if item.endswith(".desktop"):
                try:
                    menuentry = MenuEntry(os.path.join(subdir, item), dir_, prefix)
                except ParsingError:
                    continue

                self.cacheEntries[dir_].append(menuentry)
                if legacy:
                    self.cacheEntries['legacy'].append(menuentry)
            elif os.path.isdir(os.path.join(dir_, subdir, item)) and not legacy:
                self.__addFiles(dir_, os.path.join(subdir, item), prefix, legacy)

    def get_menu_entries(self, dirs, legacy=True):
        entries = []
        ids = set()
        # handle legacy items
        appdirs = dirs[:]
        if legacy:
            appdirs.append("legacy")
        # cache the results again
        key = "".join(appdirs)
        try:
            return self.cache[key]
        except KeyError:
            pass
        for dir_ in appdirs:
            for menuentry in self.cacheEntries[dir_]:
                try:
                    if menuentry.DesktopFileID not in ids:
                        ids.add(menuentry.DesktopFileID)
                        entries.append(menuentry)
                    elif menuentry.getType() == MenuEntry.TYPE_SYSTEM:
                        # FIXME: This is only 99% correct, but still...
                        idx = entries.index(menuentry)
                        entry = entries[idx]
                        if entry.getType() == MenuEntry.TYPE_USER:
                            entry.Original = menuentry
                except UnicodeDecodeError:
                    continue
        self.cache[key] = entries
        return entries


def parse(filename=None):
    """Helper function.
    Equivalent to calling xdg.Menu.XMLMenuBuilder().parse(filename)
    """
    return XMLMenuBuilder().parse(filename)