This file is indexed.

/usr/share/pyshared/freevo/menu.py is in python-freevo 1.9.2b2-4.2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------
# Freevo menu handling system
# -----------------------------------------------------------------------
# $Id: menu.py 11905 2011-11-14 21:54:46Z adam $
# -----------------------------------------------------------------------
# Freevo - A Home Theater PC framework
# Copyright (C) 2002 Krister Lagerstrom, et al.
# Please see the file freevo/Docs/CREDITS for a complete list of authors.
#
# 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 2 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 MER-
# CHANTABILITY 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# -----------------------------------------------------------------------

"""
Freevo menu handling system
"""
import logging
logger = logging.getLogger("freevo.menu")

import string
import copy
from pprint import pprint

import config
import plugin
import util
import skin
import rc

from gui import sounds
from event import *
from item import Item
from gui import GUIObject, AlertBox
import osd

osd = osd.get_singleton()


class MenuItem(Item):
    """
    Default item for the menu. It includes one action
    """
    def __init__(self, name='', action=None, arg=None, type=None, image=None, icon=None, parent=None, skin_type=None):
        Item.__init__(self, parent, skin_type=skin_type)
        if name:
            self.name  = Unicode(name)
        if icon: # puts an icon next to the menu item
            self.icon  = icon
        if image:
            self.image = image

        self.function = action
        self.arg      = arg
        self.type     = type


    def __str__(self):
        """
        return the event as string
        """
        s = '"'+self.name+'"'
        if hasattr(self, 'action'):    s += ' action=%s' % self.action
        #if hasattr(self, 'arg') and self.arg: s += ' arg=%s' % self.arg[0]
        if hasattr(self, 'type'):      s += ' type=%s' % self.type
        if hasattr(self, 'image'):     s += ' image=%s' % String(self.image)
        if hasattr(self, 'icon'):      s += ' icon=%s' % self.icon
        if hasattr(self, 'skin_type'): s += ' skin_type=%s' % self.skin_type
        #if hasattr(self, 'parent'):    s += ' parent=%s' % self.parent
        return s


    def __repr__(self):
        """
        return the menu item as a raw string
        """
        if hasattr(self, 'name') and self.name:
            return '<%-.16s: %r>' % (self.name, self.__class__)
        if hasattr(self, 'type') and self.type:
            return '<%r: %r>' % (self.type, self.__class__)
        return '<%r>' % (self.__class__,)


    def actions(self):
        """
        return the default action
        """
        return [ (self.select, self.name, 'MENU_SUBMENU') ]


    def select(self, arg=None, menuw=None):
        """
        call the default acion
        """
        if self.function and callable(self.function):
            self.function(arg=self.arg, menuw=menuw)



class Menu:
    """
    a Menu with Items for the MenuWidget
    """
    def __init__(self, heading, choices, fxd_file=None, umount_all=0, reload_func=None, item_types=None,
        force_skin_layout=-1):

        self.heading = heading
        self.choices = choices          # List of MenuItems
        if len(self.choices):
            self.selected = self.choices[0]
        else:
            self.selected = None
        self.page_start = 0
        self.previous_page_start = []
        self.previous_page_start.append(0)
        self.umount_all = umount_all    # umount all ROM drives on display?
        self.skin_settings = None
        if fxd_file:
            self.skin_settings = skin.load(fxd_file)

        # special items for the new skin to use in the view or info
        # area. If None, menu.selected will be taken
        self.infoitem = None
        self.viewitem = None

        # Called when a child menu returns. This function returns a new menu
        # or None and the old menu will be reused
        self.reload_func       = reload_func
        self.item_types        = item_types
        self.force_skin_layout = force_skin_layout
        self.display_style     = skin.get_display_style(self)

        # How many menus to go back when 'BACK_ONE_MENU' is called
        self.back_one_menu = 1


    def __str__(self):
        """
        return the class as string
        """
        s = '"%s" choices=%d' % (self.heading, len(self.choices))
        return s


    def __repr__(self):
        """
        return the class as string
        """
        return '<%-.16s: %r>' % (self.heading, self.__class__)


    def items_per_page(self):
        """
        return the number of items per page for this skin
        """
        return skin.items_per_page(('menu', self))



class MenuWidget(GUIObject):
    """
    The MenuWidget handles a stack of Menus
    """
    def __init__(self):
        GUIObject.__init__(self)
        self.menustack = []
        self.rows = 0
        self.cols = 0
        self.visible = 1
        self.eventhandler_plugins = None
        self.event_context  = 'menu'
        self.show_callbacks = []
        self.force_page_rebuild = False

        self.screen_transition = skin.TRANSITION_NONE


    def __str__(self):
        """
        return the class as string
        """
        s = '%s' % (self.label,)
        #s += ', rect=%s' % (self.rect,)
        return s


    def __repr__(self):
        if self.label:
            return '<%-.16s: %r>' % (self.label, self.__class__)
        return '%r' % (self.__class__)


    def set_event_context(self):
        """
        Set the event context
        """
        context = self.event_context
        if self.menustack and hasattr(self.menustack[-1], 'event_context'):
            context = self.menustack[-1].event_context
        rc.set_app_context(self, context)


    def show(self):
        if not self.visible:
            self.visible = 1
            self.refresh(reload=1)
            for callback in copy.copy(self.show_callbacks):
                callback()
        self.set_event_context()


    def hide(self, clear=True):
        if self.visible:
            self.visible = 0
            if clear:
                skin.clear(osd_update=clear)


    def delete_menu(self, arg=None, menuw=None, allow_reload=True):
        if len(self.menustack) > 1:
            self.menustack = self.menustack[:-1]
            menu = self.menustack[-1]

            self.set_event_context()

            if not isinstance(menu, Menu):
                return True
            
            if menu.reload_func and allow_reload:
                reload = menu.reload_func()
                if reload:
                    self.menustack[-1] = reload

            self.init_page()
            self.screen_transition = skin.TRANSITION_OUT


    def delete_submenu(self, refresh=True, reload=False, osd_message=''):
        """
        Delete the last menu if it is a submenu. Also refresh or reload the
        new menu if the attributes are set to True. If osd_message is set,
        this message will be send if the current menu is no submenu
        """
        if len(self.menustack) > 1 and hasattr(self.menustack[-1], 'is_submenu') and \
               self.menustack[-1].is_submenu:
            if refresh and reload:
                self.back_one_menu(arg='reload')
            elif refresh:
                self.back_one_menu()
            else:
                self.delete_menu()
        elif len(self.menustack) > 1 and osd_message:
            rc.post_event(Event(OSD_MESSAGE, arg=osd_message))


    def back_one_menu(self, arg=None, menuw=None):
        if len(self.menustack) > 1:
            try:
                count = -self.menustack[-1].back_one_menu
            except:
                count = -1

            self.menustack = self.menustack[:count]
            menu = self.menustack[-1]

            self.set_event_context()

            if not isinstance(menu, Menu):
                menu.refresh()
                return True

            if skin.get_display_style(menu) != menu.display_style:
                self.rebuild_page()

            if menu.reload_func:
                reload = menu.reload_func()
                if reload:
                    self.menustack[-1] = reload
                self.init_page()
            else:
                self.init_page()
            
            self.screen_transition = skin.TRANSITION_OUT
            if arg == 'reload':
                self.refresh(reload=1)
            else:
                self.refresh()


    def goto_main_menu(self, arg=None, menuw=None):
        self.menustack = [self.menustack[0]]
        self.set_event_context()
        self.init_page()
        self.refresh()


    def goto_media_menu(self, media='audio'):
        """
        Go to a main menu item media = 'tv' or 'audio' or 'video' or 'image' or 'games'
        used for events:
            - MENU_GOTO_TVMENU
            - MENU_GOTO_TVGUIDEMENU #doesn't yet work
            - MENU_GOTO_VIDEOMENU
            - MENU_GOTO_AUDIOMENU
            - MENU_GOTO_IMAGEMENU
            - MENU_GOTO_GAMESMENU
            - MENU_GOTO_RADIOMENU
            - MENU_GOTO_SHUTDOWN
        """
        self.menustack = [self.menustack[0]]
        menu = self.menustack[0]
        self.set_event_context()
        self.init_page()

        if media == 'shutdown':
            for menuitem in self.menustack[0].choices:
                if self.all_items.index(menuitem) >= self.rows - 1:
                    self.goto_next_page()
                if string.find(str(menuitem), 'shutdown.') > 0:
                    menu.selected = menuitem
                    self.eventhandler(MENU_SELECT)
                    return

        elif media == 'tv.guide':
            menu.selected = self.all_items[len(self.menustack[0].choices)-1]
            for menuitem in self.menustack[0].choices:
                try:
                    if menuitem.arg == ('tv', 0):
                        menu.selected = menuitem
                        self.refresh()
                        self.eventhandler(MENU_SELECT)
                        self.refresh()
                        self.eventhandler(MENU_SELECT)
                        return
                except:
                    return
        level = 0
        for mediaitem in media.split('.'):
            for menuitem in self.menustack[level].choices:
                try:
                    if menuitem.arg[0] == mediaitem:
                        if config.OSD_SOUNDS:
                            try:
                                key = "menu." + media
                                if config.OSD_SOUNDS[key]:
                                    sounds.play_sound(sounds.load_sound(key))
                            except KeyError:
                                pass
                        osd.busyicon.wait(config.OSD_BUSYICON_TIMER[0])
                        menuitem.select(menuw=self)
                        osd.busyicon.stop()
                        break
                except AttributeError: # may have no .arg (no media menu)
                    pass
                except TypeError: # .arg may be not indexable
                    pass
            level += 1


    def goto_prev_page(self, arg=None, menuw=None):
        menu = self.menustack[-1]

        if self.cols == 1:
            if menu.page_start != 0:
                menu.page_start = menu.previous_page_start.pop()
            self.init_page()
            menu.selected = self.all_items[0]
        else:
            if menu.page_start - self.cols >= 0:
                menu.page_start -= self.cols
                self.init_page()

        if arg != 'no_refresh':
            self.refresh()


    def goto_next_page(self, arg=None, menuw=None):
        menu = self.menustack[-1]
        self.rows, self.cols = menu.items_per_page()
        items_per_page = self.rows*self.cols

        if self.cols == 1:
            down_items = items_per_page - 1

            if menu.page_start + down_items < len(menu.choices):
                menu.previous_page_start.append(menu.page_start)
                menu.page_start += down_items
                self.init_page()
                menu.selected = self.menu_items[-1]
        else:
            if menu.page_start + self.cols * self.rows < len(menu.choices):
                if self.rows == 1:
                    menu.page_start += self.cols
                else:
                    menu.page_start += self.cols * (self.rows-1)
                self.init_page()

        if arg != 'no_refresh':
            self.refresh()


    def pushmenu(self, menu):
        self.menustack.append(menu)
        self.set_event_context()
        
        if isinstance(menu, Menu):
            menu.page_start = 0
            self.init_page()
            menu.selected = self.all_items[0]
            self.screen_transition = skin.TRANSITION_IN
            self.refresh()
        else:
            menu.refresh()


    def refresh(self, reload=0):
        menu = self.menustack[-1]

        if not isinstance(menu, Menu):
            # Do not draw if there are any children
            if self.children:
                return False
            return menu.refresh()

        # We need to unmount devices but only at the top menu
        if len(self.menustack) == 1:
            if self.menustack[-1].umount_all == 1:
                util.umount_all()

        if reload:
            if menu.reload_func:
                reload = menu.reload_func()
                if reload:
                    self.menustack[-1] = reload
            if self.force_page_rebuild:
                self.force_page_rebuild = False
                self.rebuild_page()
            self.init_page()
        
        skin.draw('menu', self, self.menustack[-1], self.screen_transition)
        self.screen_transition = skin.TRANSITION_NONE


    def make_submenu(self, menu_name, actions, item):
        #print 'make_submenu(menu_name=%r, actions=%r, item=%r)' % (menu_name, actions, item)
        items = []
        for a in actions:
            if isinstance(a, Item):
                items.append(a)
            else:
                items.append(MenuItem(a[1], a[0]))
        fxd_file = None

        if item.skin_fxd:
            fxd_file = item.skin_fxd

        for i in items:
            if not hasattr(item, 'is_mainmenu_item'):
                i.image = item.image
            if hasattr(item, 'display_type'):
                i.display_type = item.display_type
            elif hasattr(item, 'type'):
                i.display_type = item.type

        s = Menu(menu_name, items, fxd_file=fxd_file)
        s.is_submenu = True
        self.pushmenu(s)


    def _handle_up(self, menu, event):
        curr_selected = self.all_items.index(menu.selected)
        sounds.play_sound(sounds.MENU_NAVIGATE)
        if curr_selected-self.cols < 0 and \
               menu.selected != menu.choices[0]:
            self.goto_prev_page(arg='no_refresh')
            try:
                if self.cols == 1:
                    curr_selected = self.rows - 1
                elif self.rows != 1:
                    curr_selected = self.all_items.index(menu.selected)
                else:
                    curr_selected+=self.cols
            except ValueError:
                curr_selected += self.cols
        curr_selected = max(curr_selected-self.cols, 0)
        menu.selected = self.all_items[curr_selected]
        self.refresh()


    def _handle_down(self, menu, event):
        curr_selected = self.all_items.index(menu.selected)
        sounds.play_sound(sounds.MENU_NAVIGATE)
        if curr_selected+self.cols > len(self.all_items)-1 and \
               menu.page_start + len(self.all_items) < len(menu.choices):

            self.goto_next_page(arg='no_refresh')
            try:
                if self.cols == 1:
                    curr_selected = 0
                elif self.rows != 1:
                    curr_selected = self.all_items.index(menu.selected)
                else:
                    curr_selected-=self.cols
            except ValueError:
                curr_selected -= self.cols
        curr_selected = min(curr_selected+self.cols, len(self.all_items)-1)
        menu.selected = self.all_items[curr_selected]
        self.refresh()


    def _handle_pageup(self, menu, event):
        # Do nothing for an empty file list
        if not len(self.menu_items):
            return

        curr_selected = self.all_items.index(menu.selected)

        # Move to the previous page if the current position is at the
        # top of the list, otherwise move to the top of the list.
        if curr_selected == 0:
            self.goto_prev_page()
        else:
            curr_selected = 0
            menu.selected = self.all_items[curr_selected]
            self.refresh()
        return


    def _handle_pagedown(self, menu, event):
        # Do nothing for an empty file list
        if not len(self.menu_items):
            return

        if menu.selected == menu.choices[-1]:
            return

        curr_selected = self.all_items.index(menu.selected)
        bottom_index = self.menu_items.index(self.menu_items[-1])

        # Move to the next page if the current position is at the
        # bottom of the list, otherwise move to the bottom of the list.
        if curr_selected >= bottom_index:
            self.goto_next_page()
        else:
            curr_selected = bottom_index
            menu.selected = self.all_items[curr_selected]
            self.refresh()
        return

    def _handle_left(self, menu, event):
        # Do nothing for an empty file list
        if not len(self.menu_items):
            return

        sounds.play_sound(sounds.MENU_NAVIGATE)
        curr_selected = self.all_items.index(menu.selected)
        if curr_selected == 0:
            self.goto_prev_page(arg='no_refresh')
            try:
                curr_selected = self.all_items.index(menu.selected)
                if self.rows == 1:
                    curr_selected = len(self.all_items)
            except ValueError:
                curr_selected += self.cols
        curr_selected = max(curr_selected-1, 0)
        menu.selected = self.all_items[curr_selected]
        self.refresh()
        return


    def _handle_right(self, menu, event):
        # Do nothing for an empty file list
        if not len(self.menu_items):
            return

        sounds.play_sound(sounds.MENU_NAVIGATE)
        curr_selected = self.all_items.index(menu.selected)
        if curr_selected == len(self.all_items)-1:
            self.goto_next_page(arg='no_refresh')
            try:
                curr_selected = self.all_items.index(menu.selected)
                if self.rows == 1:
                    curr_selected -= 1
            except ValueError:
                curr_selected -= self.cols

        curr_selected = min(curr_selected+1, len(self.all_items)-1)
        menu.selected = self.all_items[curr_selected]
        self.refresh()
        return


    def _handle_play_item(self, menu, event):
        action = None
        arg    = None

        sounds.play_sound(sounds.MENU_SELECT)
        try:
            action = menu.selected.action
        except AttributeError:
            actions = menu.selected.actions() or []

            # Add the actions of the plugins to the list of actions.  This is needed when a
            # Item class has no actions but plugins provides them. This case happens with an
            # empty disc.
            #
            # FIXME The event MENU_SELECT is called when selecting a submenu entry too. The
            # item passed to the plugin is then the submenu entry instead its parent item. So
            # if we are in a submenu we don't want to call the actions of the plugins.
            # because we'll break some (or all) plugins behavior.  Does that sound correct?

            if config.OSD_SOUNDS:
                if hasattr(menu.selected, 'arg'):
                    try:
                        key = "menu." + menu.selected.arg[0]
                        if config.OSD_SOUNDS[key]:
                            sounds.play_sound(sounds.load_sound(key))
                    except:
                        pass
                else:
                    try:
                        key = "menu." + menu.selected.__class__.__name__
                        if config.OSD_SOUNDS[key]:
                            sounds.play_sound(sounds.load_sound(key))
                    except:
                        pass

            if not hasattr(menu, 'is_submenu'):
                plugins = plugin.get('item') + plugin.get('item_%s' % menu.selected.type)

                if hasattr(menu.selected, 'display_type'):
                    plugins += plugin.get('item_%s' % menu.selected.display_type)

                plugins.sort(lambda l, o: cmp(l._level, o._level))

                for p in plugins:
                    for a in p.actions(menu.selected):
                        if isinstance(a, MenuItem):
                            actions.append(a)
                        else:
                            actions.append(a[:2])

            if actions:
                action = actions[0]
                if isinstance(action, MenuItem):
                    action = action.function
                    arg    = action.arg
                else:
                    action = action[0]
        if not action:
            AlertBox(text=_('No action defined for this choice!')).show()
            return
        action(arg=arg, menuw=self)


    def _handle_submenu(self, menu, event):
        action = None
        arg    = None
        #try:
        #    action = menu.selected.action
        #except AttributeError:
        #    pass

        actions = menu.selected.actions()
        force   = False
        if not actions:
            actions = []
            force   = True

        if not hasattr(menu, 'is_submenu'):
            plugins = plugin.get('item') + plugin.get('item_%s' % menu.selected.type)

            if hasattr(menu.selected, 'display_type'):
                plugins += plugin.get('item_%s' % menu.selected.display_type)

            plugins.sort(lambda l, o: cmp(l._level, o._level))

            for p in plugins:
                for a in p.actions(menu.selected):
                    if isinstance(a, MenuItem):
                        actions.append(a)
                    else:
                        actions.append(a[:2])
                        if len(a) == 3 and a[2] == 'MENU_SUBMENU':
                            a[0](menuw=self)
                            return

        if actions:
            if len(actions) > 1 or force:
                self.make_submenu(menu.selected.name, actions, menu.selected)
            elif len(actions) == 1:
                # if there is only one action, call it!
                action = actions[0]
                if isinstance(action, MenuItem):
                    action = action.function
                    arg    = action.arg
                else:
                    action = action[0]
                action(arg=arg, menuw=self)


    def _handle_call_item_action(self, menu, event):
        _debug_('calling action %s' % event.arg)

        for a in menu.selected.actions():
            if not isinstance(a, Item) and len(a) > 2 and a[2] == event.arg:
                a[0](arg=None, menuw=self)
                return

        plugins = plugin.get('item') + plugin.get('item_%s' % menu.selected.type)

        if hasattr(menu.selected, 'display_type'):
            plugins += plugin.get('item_%s' % menu.selected.display_type)

        for p in plugins:
            for a in p.actions(menu.selected):
                if not isinstance(a, MenuItem) and len(a) > 2 and a[2] == event.arg:
                    a[0](arg=None, menuw=self)
                    return
        _debug_('action %s not found' % event.arg)


    def __call_action(self, action, arg):
        result = action(arg=arg, menuw=self)
        if isinstance(result, kaa.InProgress):
            result.wait()

    def eventhandler(self, event):
        menu = self.menustack[-1]

        if self.cols == 1 and isinstance(menu, Menu):
            if config.MENU_ARROW_NAVIGATION:
                if event == MENU_LEFT:
                    event = MENU_BACK_ONE_MENU
                elif event == MENU_RIGHT:
                    event = MENU_SELECT

            else:
                if event == MENU_LEFT:
                    event = MENU_PAGEUP
                elif event == MENU_RIGHT:
                    event = MENU_PAGEDOWN

        if self.eventhandler_plugins == None:
            self.eventhandler_plugins = plugin.get('daemon_eventhandler')

        if event == MENU_GOTO_MAINMENU:
            self.goto_main_menu()
            return True

        if event == MENU_GOTO_TV:
            self.goto_media_menu("tv")
            return True

        if event == MENU_GOTO_TVGUIDE:
            self.goto_media_menu("tv.guide")
            return True

        if event == MENU_GOTO_VIDEOS:
            self.goto_media_menu("video")
            return True

        if event == MENU_GOTO_MUSIC:
            self.goto_media_menu("audio")
            return True

        if event == MENU_GOTO_IMAGES:
            self.goto_media_menu("image")
            return True

        if event == MENU_GOTO_GAMES:
            self.goto_media_menu("games")
            return True

        if event == MENU_GOTO_RADIO:
            self.goto_media_menu("audio.radio")
            return True

        if event == MENU_GOTO_SHUTDOWN:
            self.goto_media_menu("shutdown")
            return True

        if event == MENU_BACK_ONE_MENU or \
            (event == MOUSE_BTN_PRESS and event.button == 3):
            sounds.play_sound(sounds.MENU_BACK_ONE)
            self.back_one_menu()
            return True

        if not isinstance(menu, Menu) and menu.eventhandler(event):
            return True

        if event == 'MENU_RELOAD':
            self.refresh(True)
            return True

        if event == 'MENU_REFRESH':
            self.refresh()
            return True

        if event == 'MENU_REBUILD':
            self.init_page()
            self.refresh()
            return True

        if not self.menu_items:
            if event in (MENU_SELECT, MENU_SUBMENU, MENU_PLAY_ITEM):
                self.back_one_menu()
                return True
            menu = self.menustack[-2]
            if hasattr(menu, 'selected') and hasattr(menu.selected, 'eventhandler') and menu.selected.eventhandler:
                if menu.selected.eventhandler(event=event, menuw=self):
                    return True
            for p in self.eventhandler_plugins:
                if p.eventhandler(event=event, menuw=self):
                    return True
            return False

        if not isinstance(menu, Menu):
            if self.eventhandler_plugins == None:
                self.eventhandler_plugins = plugin.get('daemon_eventhandler')

            for p in self.eventhandler_plugins:
                if p.eventhandler(event=event, menuw=self):
                    return True

            _debug_('no eventhandler for event %s' % event, 2)
            return False

        if event == MENU_UP:
            self._handle_up(menu, event)
            return True

        if event == MENU_DOWN:
            self._handle_down(menu, event)
            return True

        if event == MENU_PAGEUP:
            self._handle_pageup(menu, event)
            return True

        if event == MENU_PAGEDOWN:
            self._handle_pagedown(menu, event)
            return True

        if event == MENU_LEFT:
            self._handle_left(menu, event)
            return True

        if event == MENU_RIGHT:
            self._handle_right(menu, event)
            return True

        if event == MENU_PLAY_ITEM and hasattr(menu.selected, 'play'):
            menu.selected.play(menuw=self)
            return True

        if event == MENU_PLAY_ITEM or event == MENU_SELECT:
            self._handle_play_item(menu, event)
            return True

        if event == MENU_SUBMENU:
            self._handle_submenu(menu, event)
            return True

        if event == MENU_CALL_ITEM_ACTION:
            self._handle_call_item_action(menu, event)
            return True

        if event == MENU_CHANGE_STYLE and len(self.menustack) > 1:
            # did the menu change?
            if skin.toggle_display_style(menu):
                self.rebuild_page()
                self.refresh()
            return True

        if event == MOUSE_MOTION:
            for menuitem in menu.choices:
                if menuitem.rect.collidepoint(event.pos):
                    self.highlight_menuitem(menuitem)
            return True

        if event == MOUSE_BTN_PRESS:
            # Left click
            if event.button == 1:
                for menuitem in menu.choices:
                    if menuitem.rect.collidepoint(event.pos):
                        self.highlight_menuitem(menuitem)
                        self.select_menuitem(menuitem)
            # Middle click
            elif event.button == 2:
                self.submenu_menuitem()
            # Wheel up
            elif event.button == 4:
                self.up_menuitem()
            # Wheel down
            elif event.button == 5:
                self.down_menuitem()
            return True
        
        if hasattr(menu.selected, 'eventhandler') and menu.selected.eventhandler:
            if menu.selected.eventhandler(event=event, menuw=self):
                return True

        for p in self.eventhandler_plugins:
            if p.eventhandler(event=event, menuw=self):
                return True

        _debug_('no eventhandler for event %s' % str(event), 2)
        return False



    def highlight_menuitem(self, clicked_menu):
        i = 0
        menu = self.menustack[-1]
        _debug_('clicked_menu=%s, self.all_item=%s' % (clicked_menu, self.all_items[0]))
        for menuitem in self.all_items:
            if clicked_menu == menuitem:
                sounds.play_sound(sounds.MENU_NAVIGATE)
                curr_selected = i
                menu.selected = self.all_items[curr_selected]
                self.refresh()
                return
            i += 1

    def select_menuitem(self, clicked_menu):
        self.eventhandler(MENU_SELECT)

    def submenu_menuitem(self):
        self.eventhandler(MENU_SUBMENU)

    def up_menuitem(self):
        self.eventhandler(MENU_UP)

    def down_menuitem(self):
        self.eventhandler(MENU_DOWN)

    def rebuild_page(self):
        menu = self.menustack[-1]

        if not menu:
            return

        # recalc everything!
        current = menu.selected
        try:
            pos = menu.choices.index(current)
        except ValueError, e:
            print 'menu.choices.index(current) failed: %s' % (e)

        menu.previous_page_start = []
        menu.previous_page_start.append(0)
        menu.page_start = 0

        rows, cols = menu.items_per_page()
        items_per_page = rows*cols

        while pos >= menu.page_start + items_per_page:
            self.goto_next_page(arg='no_refresh')

        menu.selected = current
        self.init_page()
        menu.display_style = skin.get_display_style(menu)


    def init_page(self):

        self.screen_transition = skin.TRANSITION_PAGE

        menu = self.menustack[-1]
        if not menu:
            return

        # Create the list of main selection items (menu_items)
        menu_items           = []
        first                = menu.page_start
        self.rows, self.cols = menu.items_per_page()

        for choice in menu.choices[first : first+(self.rows*self.cols)]:
            menu_items.append(choice)

        self.rows, self.cols = menu.items_per_page()

        self.menu_items = menu_items

        if len(menu_items) == 0:
            self.all_items = menu_items + [ MenuItem('Back', self.back_one_menu) ]
        else:
            self.all_items = menu_items

        if not menu.selected in self.all_items:
            menu.selected = self.all_items[0]

        if not menu.choices:
            menu.selected = self.all_items[0]

        rc.post_event(MENU_PROCESS_END)




# register menu to the skin
skin.register('menu', ('screen', 'title', 'subtitle', 'view', 'listing', 'info', 'plugin'))