Ejemplo n.º 1
0
def setup_reservation_menu():
    menu = Menu("Reservations Menu")
    menu.new_option("n", "New Reservation", new_reservation)
    menu.new_option("e", "Edit Reservation", edit_reservation)
    menu.new_option("l", "List Reservations", list_reservations)
    menu.new_option("d", "Delete Reservation", delete_reservation)
    return menu
Ejemplo n.º 2
0
def _setup_flight_menu():
    menu = Menu("Flights Menu")
    menu.new_option("n", "New Flight", new_flight)
    menu.new_option("e", "Edit Flight", edit_flight)
    menu.new_option("l", "List Flights", list_flights)
    menu.new_option("d", "Delete Flight", delete_flight)
    return menu
Ejemplo n.º 3
0
def account_menu(context):
    """
    Show menu for user's "cabinet"
    """
    from lib.menu import Menu
    menu = Menu(context['current_view_name'])
    for view_name, verbose_name in PERSONAL_AREA_MENU:
        menu.add(view_name, verbose_name)

    return {'menu': menu}
Ejemplo n.º 4
0
def staff_menu(context):
    """
    Show menu for user's "cabinet" for staff
    """
    from lib.menu import Menu
    menu = Menu(context['current_view_name'])
    for view_name, verbose_name in PERSONAL_AREA_STAFF_MENU:
        menu.add(view_name, verbose_name)

    return {'menu': menu}
Ejemplo n.º 5
0
def main_menu_list():
    menu = Menu(False)
    title = "======= MAIN MENU ==========================================="
    menu_list = [
        'Menu list for IP-based scan',
        'Menu list for building VulnDB',
        '[Exit]'
    ]
    menu_num = menu.show(title, menu_list)
    return menu_num
Ejemplo n.º 6
0
def staff_menu(context):
    """
    Show menu for user's "cabinet" for staff
    """
    from lib.menu import Menu
    menu = Menu(context['current_view_name'])
    for view_name, verbose_name, id in settings.PERSONAL_AREA_STAFF_MENU:
        menu.add(view_name, verbose_name, attrs={"id": id})

    return {'menu': menu}
Ejemplo n.º 7
0
def account_profile_menu(context):
    """
    Show right menu in profile page
    """
    from lib.menu import Menu
    menu = Menu()
    for view_name, verbose_name, attrs in \
                                    (context['user'].get_profile().is_juridical and \
                                    settings.PROFILE_MENU_JURIDICAL or settings.PROFILE_MENU_PHISICAL):
        menu.add(view_name, verbose_name, attrs)

    return {'account_profile_menu_items': menu, 'user': context['user']}
Ejemplo n.º 8
0
def account_profile_menu(context):
    """
    Show right menu in profile page
    """
    from lib.menu import Menu
    menu = Menu()
    for view_name, verbose_name, attrs in \
                                    (context['user'].get_profile().is_juridical and \
                                    settings.PROFILE_MENU_JURIDICAL or settings.PROFILE_MENU_PHISICAL):
        menu.add(view_name, verbose_name, attrs)
    
    return {'account_profile_menu_items':menu, 'user':context['user']}
Ejemplo n.º 9
0
def report_menu_list():
    menu = Menu(False)
    title = "======= REPORT MENU LIST ===================================="
    menu_list = [
        'Daily report: CVE,EDB,MSF...',
        'View  report',
        'Fetch CVEs',
        'Fetch Exploits',
        'Fetch Msf modules',
        'Menu list for DB',
        '[Return]'
    ]
    menu_num = menu.show(title, menu_list)
    return menu_num
Ejemplo n.º 10
0
def system_exit():
    from lib.menu import Menu

    menu = Menu(False)
    title = "\n[?] Exit penta...?"
    menu_list = [
        '[Return menu]',
        '[Exit]'
    ]
    menu_num = menu.show(title, menu_list)

    if menu_num == 0:
        pass
    elif menu_num == -1 or menu_num == 1:
        logging.info("Stay out of trouble!!!")
        sys.exit(0)
Ejemplo n.º 11
0
def root(req):
    check_login(req)

    no_section = Menu("")
    no_section.items = list(item for item in user_sections if isitem(item))

    x_menu = Menu(user_sections.label)
    x_menu.append(no_section)
    x_menu.items += [item for item in user_sections if ismenu(item)]

    x_menu = correct_menu(req, x_menu)

    # if there is only one link, redirect to it
    if len(x_menu) == 1 and len(x_menu[0]) == 1:
        redirect(req, x_menu[0][0].uri)

    return generate_page(req, "user/user.html", user_sections=x_menu)
Ejemplo n.º 12
0
def ip_menu_list():
    menu = Menu(False)
    title = "======= PENTEST MENU LIST ==================================="
    menu_list = [
        'Port scan',
        'Nmap & vuln scan',
        'Check HTTP option methods',
        'Grab DNS server info',
        'Shodan host search',
        'FTP connect with anonymous',
        'SSH connect with Brute Force',
        'Metasploit Frame Work',
        'Change target host',
        '[Return]'
    ]
    menu_num = menu.show(title, menu_list)
    return menu_num
Ejemplo n.º 13
0
def root(req):
    check_login(req)
    check_right(req, 'admin')

    no_section = Menu('')
    no_section.items = list(item for item in admin_sections if isitem(item))

    x_menu = Menu(admin_sections.label)
    x_menu.append(no_section)
    x_menu.items += [item for item in admin_sections if ismenu(item)]

    x_menu = correct_menu(req, x_menu)

    # if there is only one link, redirect to it
    if len(x_menu) == 1 and len(x_menu[0]) == 1:
        redirect(req, x_menu[0][0].uri)
    return generate_page(req, "admin/admin.html", admin_sections=x_menu)
Ejemplo n.º 14
0
def db_menu():
    menu = Menu(False)
    title = "======= DB MENU ============================================="
    menu_list = ['Optimize DB', 'Clear DB', '[Return]']
    menu_num = menu.show(title, menu_list)

    db_handle = DBInit()
    if menu_num == 0:
        db_handle.optimize()
    elif menu_num == 1:
        db_handle.clear()
        db_handle.optimize()
        db_handle.create()
    elif menu_num == -1 or menu_num == 2:
        pass

    return None
Ejemplo n.º 15
0
    def __init__(self, stdscreen):
        self.screen = stdscreen
        curses.curs_set(0)

        def exit_and_run():
            global run_installer
            run_installer = True
            main_menu.exit()

        package_options_menu = Category.config_menu(self.screen, categories)

        main_menu = Menu(self.screen, 'Main Menu', [
            ('Package Options', package_options_menu.display),
            ('Run Installer', exit_and_run)
        ])

        main_menu.display()
Ejemplo n.º 16
0
def account_top_menu(context):
    """
    Show right menu in profile page
    """
    from lib.menu import Menu
    menu = Menu(context.get('current_view_name'))
    # for view_name, verbose_name, attrs in (context['user'].get_profile().is_juridical and PROFILE_MENU_JURIDICAL or PROFILE_MENU_PHISICAL or PROFILE_MENU_CARD):

    profile = context["user"].get_profile()
    if not profile.is_juridical and not profile.is_card:
        context['button_card_get'] = True
    bill_account_obj = BillserviceAccount.objects.get(id=profile.billing_account_id)

    now = datetime.datetime.now()
    payment_qs = Data_centr_payment.objects.filter(Q(bill_account=profile.billing_account) & Q(postdate=False) & Q(payment_date=None))
    print payment_qs
    context['not_paid'] = True if payment_qs else False

    context["not_is_invoice"] = True

    if not profile.is_juridical or not profile.create_invoice:
        context["not_is_invoice"] = False
    clist = []
#    if profile.is_juridical:
#        clist = PROFILE_MENU_JURIDICAL

#    else:
#        clist = PROFILE_MENU_PHISICAL

    if profile.is_card:
        clist = PROFILE_MENU_CARD

    for view_name, verbose_name, attrs in clist:
        menu.add(view_name, verbose_name, attrs)

    for men in menu:
        # print men
        if men["name"] == 'account_profile':
            context["account_profile"] = men
        if men["name"] == 'helpdesk_account_tickets':
            context["helpdesk_account_tickets"] = men
        if men["name"] == 'account_show_tariffs':
            context["account_show_tariffs"] = men

    return context
Ejemplo n.º 17
0
    def update(self):
        from lib.menu import Menu

        menu = Menu(False)
        title = "[*] Please select a mode..."
        menu_list = [
            'Get the most recent Exploits as many as you want',
            'Get all Exploits by csv data feed'
        ]
        mode = menu.show(title, menu_list)

        if mode == 0:
            self.execute_collect()
        elif mode == 1:
            self.execute_csv_collect()
        else:
            print("[!] Incorrect choice")

        return None
Ejemplo n.º 18
0
    def nmap_menu_list():
        menu = Menu(False)
        title = "======= NMAP MENU LIST ======================================"
        menu_list = [
            'Intense',
            'Intense + UDP',
            'Intense + TCP',
            'Intense + no ping',
            'Ping',
            'Quick',
            'Quick alpha',
            'Quick traceroute',
            'Regular',
            'Send Bad Checksums',
            'Generate Random Mac Address Spoofing',
            'Fragment Packets',
            'Slow comprehensive scan',
            'NSE Script',
            '[Return]'
        ]

        menu_num = menu.show(title, menu_list)
        return menu_num
Ejemplo n.º 19
0
def run():
    # Initialize pygame and other game modules
    pygame.mixer.pre_init(44100, 16, 2)
    pygame.init()

    config = Config()
    image_files = image.load(config)
    setting = Setting(config, image_files)
    menu = Menu(config, image_files)
    game = Game(config, image_files)
    themes = image.init_theme(config, image_files, setting)
    me = music.MusicEngine(config, image_files)
    me.play(config)

    # Create game window
    screen = pygame.display.set_mode(config.DISPLAY_RESOLUTION, config.DISPLAY_MODE, 32)
    pygame.display.set_caption("Sudoku")
    pygame.display.set_icon(pygame.image.load(image_files[config.ICON]))

    # Main Loop
    while True:
        check_events(config, me, menu, setting, game)
        render(config, screen, me, menu, setting, themes, game)
        result_check(config, game)
Ejemplo n.º 20
0
from lib.menu import Menu

if __name__ == "__main__":
    m = Menu()
    m.run()
Ejemplo n.º 21
0
def top_menu(context): # верхрее меню
    from lib.menu import Menu, get_reverse_conf
    menu = Menu(context.get('current_view_name'))
    menu.add('activationcard', _(u'Activate card'))
    menu.add(get_reverse_conf('article_by_slug', slug = 'service_list'), _(u'Services'))
#    menu.add(get_reverse_conf('news_list'), _(u'News'))
    menu.add(get_reverse_conf('article_by_slug', slug = 'feedback'), _(u'Feedback'))
    menu.add(get_reverse_conf('article_by_slug', slug = 'how_to_use'), _(u'How to use<br>our services'))
    menu.add(get_reverse_conf('article_by_slug', slug = 'tariffs'), _(u'Tariffs'))
    
    menu.add(get_reverse_conf('article_by_slug', slug = "payment_methods"), _(u'Payment<br>methods'))
#    menu.add(get_reverse_conf('article_by_slug', slug='call-us-button'), _(u'Call us<br>online'), isCallUs = True)
#    menu.add(get_reverse_conf('helpdesk_account_tickets'), _(u'Support'))
    user = context['user']

    if user.is_anonymous():
        menu.add('account_login', _(u'Log in'))
    elif user.is_staff:
        menu.add('helpdesk_dashboard', u'<span class="">%s:</span> %s' % (user.username, _(u'Management')))
    else:
        menu.add('account_profile', u'<span class="">%s:</span> %s' % (user.username, _(u'Personal area')))
    return {
            'menu': menu,
            }
Ejemplo n.º 22
0
from lib.menu import Menu
from lib.engine import Engine

if __name__ == "__main__":
    engine = Engine()
    menu = Menu(engine)
    menu.run()
Ejemplo n.º 23
0
from lib.menu import Menu
from lib.cli.reservations.menu import res_menu
from lib.cli.flights.menu import flight_menu

menu = Menu("Main Menu")
menu.new_option("r", "Reservations", res_menu.prompt)
menu.new_option("f", "Flights", flight_menu.prompt)


def main():
    print("Welcome to the flight reservation system.")
    try:
        menu.prompt()
    except KeyboardInterrupt:
        pass
    print("\n\nExiting...\n\n")


if __name__ == "__main__":
    main()
Ejemplo n.º 24
0
from lib.menu import Menu

Menu()


Ejemplo n.º 25
0
def account_profile_menu(context):
    """
    Show right menu in profile page
    """
    from lib.menu import Menu
    print 'IN ACCOUNT PROFILE MENU'
    menu = Menu(context.get('current_view_name'))

    # for view_name, verbose_name, attrs in (context['user'].get_profile().is_juridical and PROFILE_MENU_JURIDICAL or PROFILE_MENU_PHISICAL or PROFILE_MENU_CARD):

    profile = context["user"].get_profile()
    clist = []
    if not profile.is_juridical and not profile.is_card:
        context['button_card_get'] = True
    if profile.is_juridical:
#         if settings.CURRENT_SITE in (1,):
#             clist = PROFILE_MENU_JURIDICAL_GLOBALHOME
#         elif settings.CURRENT_SITE in (3,):
#             clist = PROFILE_MENU_JURIDICAL_GLOBALMOBI
#         else:
        clist = PROFILE_MENU_JURIDICAL_MOSCOWHOST

    else:
#         if settings.CURRENT_SITE in (1,):
#             clist = PROFILE_MENU_PHISICAL_GLOBALHOME
#         elif settings.CURRENT_SITE in (3,):
#             clist = PROFILE_MENU_PHISICAL_GLOBALMOBI
#         else:
            #print 'CLIST'
        clist = PROFILE_MENU_PHISICAL_MOSCOWHOST
            #print clist
            
    if profile.is_card:
        clist = PROFILE_MENU_CARD

    #if settings.CURRENT_SITE == 1 or settings.CURRENT_SITE == 2:  #пофик какой current_site
    for view_name, verbose_name, attrs in clist:
        #print 'clist'
        #print clist
        menu.add(view_name, verbose_name, attrs)


    for men in menu:
#        print 'men = %s' % men
        context[men['name']] = men
#        if men["name"] == 'account_phones_list':
#            context["account_phones_list"] = men
#        if men["name"] == 'account_phones_groups':
#            context["account_phones_groups"] = men
#        if men["name"] == 'external_phones_list':
#            context["external_phones_list"] = men
#        if men["name"] == 'callforwarding_rules_list':
#            context["callforwarding_rules_list"] = men
#        if men["name"] == 'account_fax':
#            context["account_fax"] = men
#        if men["name"] == 'list_getfax':
#            context["list_getfax"] = men
#        if men["name"] == 'list_ivr':
#            context["list_ivr"] = men
#        if men["name"] == 'my_data_centr':
#            context["my_data_centr"] = men
#        if men["name"] == 'demands_dc_archive':
#            context["demands_dc_archive"] = men
#        if men["name"] == 'account_data_centr':
#            context["account_data_centr"] = men
#        if men["name"] == 'list_vm':
#            context["list_vm"] = men
#        if men["name"] == 'transfer_call_help':
#            context["transfer_call_help"] = men
#        if men["name"] == 'vpn_users':
#            context["vpn_users"] = men
#        if men["name"] == 'list_record_talk_tariff':
#            context["list_record_talk_tariff"] = men
#        if men["name"] == 'my_inet':
#            context["my_inet"] = men
#        if men["name"] == 'account_show_internet':
#            context["account_show_internet"] = men
#        if men["name"] == 'hotspot_statistic':
#            context["hotspot_statistic"] = men
#        if men["name"] == 'list_gateway':
#            context["list_gateway"] = men
    return context
Ejemplo n.º 26
0
def account_menu(context):
    """
    Show menu for user's "cabinet"
    """
    from lib.menu import Menu, get_reverse_conf
    menu = Menu(context['current_view_name'])
    profile = context["user"].get_profile()

    if not profile.is_card:
        for view_name, verbose_name in PERSONAL_AREA_MENU:

            if view_name[:4] != "slug":
                if view_name != '#':
                    menu.add(view_name, verbose_name)
                else:
                    menu.add('', verbose_name, isCallUs=True)
            else:
                menu.add(get_reverse_conf('article_by_slug', slug=view_name[5:]), verbose_name)
    else:
        for view_name, verbose_name in PERSONAL_AREA_MENU_CARD:

            if view_name[:4] != "slug":
                if view_name != '#':
                    menu.add(view_name, verbose_name)
                else:
                    menu.add('', verbose_name, isCallUs=True)
            else:
                menu.add(get_reverse_conf('article_by_slug', slug=view_name[5:]), verbose_name)

    wip = context.get("window_is_popup", False)
    return { 'menu': menu, "window_is_popup": wip }
Ejemplo n.º 27
0
def account_profile_menu(context):
    """
    Show right menu in profile page
    """
    if settings.CURRENT_SITE == 3:
        request = context['request']
        context.update(reset_sessions_account(request))
    elif settings.CURRENT_SITE == 4:
        request = context['request']
        context.update(phones_list(request))
        context.update(external_list(request))
        context.update(list_gateway(request))

    from lib.menu import Menu
    menu = Menu(context.get('current_view_name'))

    # for view_name, verbose_name, attrs in (context['user'].get_profile().is_juridical and PROFILE_MENU_JURIDICAL or PROFILE_MENU_PHISICAL or PROFILE_MENU_CARD):

    profile = context["user"].get_profile()
    clist = []
    if not profile.is_juridical and not profile.is_card:
        context['button_card_get'] = True
    if profile.is_juridical:
        if settings.CURRENT_SITE in (1,):
            clist = PROFILE_MENU_JURIDICAL_GLOBALHOME
        elif settings.CURRENT_SITE in (3,):
            clist = PROFILE_MENU_JURIDICAL_GLOBALMOBI
        else:
            clist = PROFILE_MENU_JURIDICAL_MOSCOWDATA

    else:
        if settings.CURRENT_SITE in (1,):
            clist = PROFILE_MENU_PHISICAL_GLOBALHOME
        elif settings.CURRENT_SITE in (3,):
            clist = PROFILE_MENU_PHISICAL_GLOBALMOBI
        else:
            clist = PROFILE_MENU_PHISICAL_MOSCOWDATA

    if profile.is_card:
        clist = PROFILE_MENU_CARD

    if settings.CURRENT_SITE == 1 or settings.CURRENT_SITE == 2:
        for view_name, verbose_name, attrs in clist:
            menu.add(view_name, verbose_name, attrs)


    for men in menu:
#        print 'men = %s' % men
        context[men['name']] = men
#        if men["name"] == 'account_phones_list':
#            context["account_phones_list"] = men
#        if men["name"] == 'account_phones_groups':
#            context["account_phones_groups"] = men
#        if men["name"] == 'external_phones_list':
#            context["external_phones_list"] = men
#        if men["name"] == 'callforwarding_rules_list':
#            context["callforwarding_rules_list"] = men
#        if men["name"] == 'account_fax':
#            context["account_fax"] = men
#        if men["name"] == 'list_getfax':
#            context["list_getfax"] = men
#        if men["name"] == 'list_ivr':
#            context["list_ivr"] = men
#        if men["name"] == 'my_data_centr':
#            context["my_data_centr"] = men
#        if men["name"] == 'demands_dc_archive':
#            context["demands_dc_archive"] = men
#        if men["name"] == 'account_data_centr':
#            context["account_data_centr"] = men
#        if men["name"] == 'list_vm':
#            context["list_vm"] = men
#        if men["name"] == 'transfer_call_help':
#            context["transfer_call_help"] = men
#        if men["name"] == 'vpn_users':
#            context["vpn_users"] = men
#        if men["name"] == 'list_record_talk_tariff':
#            context["list_record_talk_tariff"] = men
#        if men["name"] == 'my_inet':
#            context["my_inet"] = men
#        if men["name"] == 'account_show_internet':
#            context["account_show_internet"] = men
#        if men["name"] == 'hotspot_statistic':
#            context["hotspot_statistic"] = men
#        if men["name"] == 'list_gateway':
#            context["list_gateway"] = men
    return context
Ejemplo n.º 28
0
from poorwsgi import app, redirect

from core.login import check_login
from core.render import generate_page

from lib.menu import Menu, isitem, ismenu, correct_menu

# menu for any users: Profile / Logout / Login / Register
user_sections = Menu("User", role="user-menu")
user_menu = user_sections  # back compatibility

user_info_menu = Menu("Info")
user_sections.append(user_info_menu)


@app.pre_process()
def append_menu(req):
    req.menu = user_menu
    req.static_menu = Menu("Menu")  # static menu (from DB for example)


@app.route("/user")
def root(req):
    check_login(req)

    no_section = Menu("")
    no_section.items = list(item for item in user_sections if isitem(item))

    x_menu = Menu(user_sections.label)
    x_menu.append(no_section)
    x_menu.items += [item for item in user_sections if ismenu(item)]
Ejemplo n.º 29
0
    def run_ddrpi(self):
        self.logger.info("Starting DDRPi running at %s" % (time.strftime('%H:%M:%S %d/%m/%Y %Z')))
        config = self.parse_commandline_arguments()
        self.logger.info("%s" % config)

        # Initialise pygame, which we use for the GUI, controllers, rate limiting etc...
        pygame.init()
        # Set up a list of output endpoints, and input adapaters
        output_devices = []
        input_adapters = []

        # Parse the floor layout
        layout = DisplayLayout(config)
        converter = layout.get_converter()

        # Create a suitably sized canvas for the given config
        canvas = FloorCanvas(layout.size_x, layout.size_y)

        # Create a menu object to handle user input
        menu = Menu()

        output_filters = []
        if ("system" in config and "filters" in config["system"]):
            print ("Found filters config: %s" % config["system"]["filters"])
            for filter_number, filter_config in sorted(config["system"]["filters"].items()):
                if ("name" in filter_config and filter_config["name"] == "ClearFilter"):
                    output_filters.append(ClearFilter(filter_config))
                elif ("name" in filter_config and filter_config["name"] == "NegativeFilter"):
                    output_filters.append(NegativeFilter(filter_config))
                elif ("name" in filter_config and filter_config["name"] == "NeutralDensityFilter"):
                    output_filters.append(NeutralDensityFilter(filter_config))

        # Set up the various outputs defined in the config.
        # Known types are the moment are "gui", "serial" and "pipe"
        if ("outputs" in config):
            for output_number, details in config["outputs"].items():
                self.logger.info("%d - %s" % (output_number, details))
                if "enabled" in details:
                    if details["enabled"] is False:
                        self.logger.info("Skipping disabled output %d" % output_number)
                        self.logger.info("%s" % details)
                        continue
                self.logger.info("Configuring output %d" % output_number)
                if details["type"] == "serial":
                    self.logger.info("Creating a SerialOutput class")
                    serial_output = SerialOutput(details)
                    serial_output.set_name("SerialOutput-#%d" % output_number)
                    serial_output.set_output_converter(converter)
                    for output_filter in output_filters:
                        serial_output.append_filter(output_filter)
                    output_devices.append(serial_output)
                elif details["type"] == "gui":
                    # Skip the gui if headless has been specified
                    if "headless" in config["system"] and config["system"]["headless"] is True:
                        continue
                    self.logger.info("Creating a GuiOutput class [There can be only one]")
                    gui_output = GuiOutput()
                    output_devices.append(gui_output)
                    self.gui = gui_output
                elif details["type"] == "pipe":
                    self.logger.info("Creating a PipeOutput class")
                    pipe_output = PipeOutput(details)
                    pipe_output.set_output_converter(converter)
                    output_devices.append(pipe_output)
                else:
                    self.logger.warn("I don't know how to handle an output of type '%s'" % (details["type"]))

        # Initialise any connected joypads/joysticks
        controllers = self.init_joysticks()

        # There can be many plugin directories, and can either be relative (from the directory in which this
        #  script resides), or absolute. All directories are scanned, and the plugins found are added to the
        #  master list. If there are duplicate class names, the last one encountered probably wins silently.
        visualisation_plugin_dirs = ["visualisation_plugins", "game_plugins"]

        # We will store a dict of classname > class object in here
        available_plugins = self.load_plugins(visualisation_plugin_dirs)

        # Add all the available plugins to the menu
        #menu.add_available_plugins(available_plugins)

        # Create a data model that we can use here, and pass to the
        #  menu class to change what is active
        # We should also be able to provide this model to a webservice
        #  class if we chose to add in HTTP control of the floor too
        plugin_model = PluginModel((layout.size_x, layout.size_y))

        # Populate the data model
        plugin_model.add_plugins(available_plugins)

        # Link it up to the menu
        menu.set_plugin_model(plugin_model)

        # If we have defined a specific plugin to run indefinitely on the command line, use that
        specific_plugin = False
        if "plugin" in config["system"]:
            only_plugin = config["system"]["plugin"]
            if plugin_model.set_current_plugin(only_plugin) is not None:
                self.logger.info("Running requested plugin %s" % only_plugin)
                specific_plugin = True
            else:
                self.logger.info("Unable to find requested plugin: %s" % (only_plugin))
                self.logger.info("Available plugins are:")
                for available_plugin in available_plugins:
                    self.logger.info("  %s" % (available_plugin))
                # This is intended as a development debug option, or at the very least the
                #  person using it should know what they are doing, so if it isn't available
                #  for whatever reason, exit.
                exit()

        if "playlist" in config["system"]:

            # Retrieve the list of playlists specified on the command line
            #  or config file
            playlist_list = config["system"]["playlist"]
            self.logger.info(playlist_list)
            if len(playlist_list) > 0:
                for playlist in playlist_list:
                    # Make the playlist an absolute path if it isn't already
                    if not os.path.isabs(playlist):
                        root_directory = os.path.dirname(os.path.realpath(__file__))
                        playlist = os.path.join(root_directory, playlist)
                    # Load the playlist
                    plugin_model.add_playlist_from_file(playlist)
                # Start the first one we added
                self.logger.info("Setting current playlist to the first one we added")
                plugin_model.set_current_playlist_by_index(1)

        if "twitter" in config:

            if "enabled" in config["twitter"] and config["twitter"]["enabled"] is not True:
                # Don't do anything, we don't want it at the moment
                pass

            else:

                # Only bother importing this module if we are going to use it, hence not requiring
                #  an extra dependency on a Twitter library if people don't want to use that
                from lib.twitter import TwitterPlaylist

                # Get the twitter credentials from the configuration file:
                twitter_details = config["twitter"]

                # If we want to limit which plugins can be selected by Twitter, do so here
                plugin_whitelist = available_plugins

                # Create the twitter plugin playlist
                twitter_playlist = TwitterPlaylist(plugins=plugin_whitelist, details=twitter_details)

                playlist_index = plugin_model.add_playlist(twitter_playlist)
                if plugin_model.get_current_playlist() is None:
                    plugin_model.set_current_playlist_by_index(playlist_index)

        # When there is no plugin specified and no user playlists either, make the first
        #  playlist active, and select either the first plugin, or, if it is available,
        #  any of the plugins listed in DEFAULT_STARTUP_PLUGIN

        # .set_current_plugin() is a convenience method to start the all_plugins playlist
        #  with the given plugin name
        self.logger.info("Current playlist: %s" % plugin_model.get_current_playlist())
        have_started_a_plugin = False
        if plugin_model.get_current_playlist() is None:
            for specified_plugin in self.DEFAULT_STARTUP_PLUGIN:
                if plugin_model.set_current_plugin(specified_plugin) is not None:
                    have_start_a_plugin = True
                    self.logger.info("Started default plugin %s" % specified_plugin)
                    break

            # If we still haven't started anything, just start the all_plugins playlist
            if have_started_a_plugin is False:
                plugin_model.set_current_playlist_by_index(0)

        print (plugin_model)
        #
        if self.gui is not None:
            #playlistModel.add_model_changed_listener(self.gui)
            #			self.gui.set_playlist_model(playlistModel)
            self.gui.set_plugin_model(plugin_model)


        # Create an object that can map key events to joystick events
        self.controller_mapper = ControllerInput()

        # The main loop is an event loop, with each part
        #  non-blocking and yields after doing a short bit.
        # Each 'bit' is a frame

        # Check for pygame events, primarily coming from
        #  gamepads and the keyboard

        running = True
        while running:

            current_playlist = plugin_model.get_current_playlist()
            current_plugin = None
            if current_playlist is not None:
                current_plugin = current_playlist.get_current_plugin()

            for e in pygame.event.get():

                if e.type == pygame.QUIT:
                    running = False

                e = self.controller_mapper.map_event(e)

                # Each consumer should return None if the
                #  event has been consumed, or return
                #  the event if something else should
                #  act upon it

                # Check first if the framework is going to
                #  consume this event. This includes heading
                #  into menus, possibly modifying the plugin
                #  model (previous/next plugin)
                #e = self.handle_event(e)
                #if e is None:
                #	continue

                # See if the menu wants to consume this event
                e = menu.handle_event(e)
                if e is None:
                    continue

                #self.print_input_event(e)

                # Next pass it on to the current plugin, if
                #  there is one
                if current_plugin is not None:
                    #					e = current_plugin['instance'].handle_event(e)
                    e = current_plugin.instance.handle_event(e)
                    if e is None:
                        continue

            # Ask the framework if it thinks it is displaying something
            # display_frame = self.draw_frame(canvas)
            # Ask the menu if it wants to draw something
            display_frame = menu.draw_frame(canvas)
            if display_frame is None:
                # If there is nothing to draw from the framework, ask
                #  the current plugin to do something is there is one
                if current_plugin is not None:
                    #					display_frame = current_plugin['instance'].draw_frame(canvas)
                    # There is every chance that the plugin might throw an
                    #  exception as we have no control over the quality of
                    #  external code (or some in-house code!), so catch any
                    #  exception
                    try:
                        display_frame = current_plugin.instance.draw_frame(canvas)
                    except Exception as e:
                        self.logger.warn("Current plugin threw an error whilst running draw_frame()")
                        self.logger.warn(e)
                        display_frame = self.draw_error(canvas)

                else:
                    # If there is no plugin, then the framework should
                    #  do something
                    pass

            # Send the data to all configured outputs if there is any to send
            # TODO: If the plugin doesn't return a canvas for some reason,
            #        then the gui should be updated with a canvas, but the output
            #        plugins need not be informed. The problem is that if the plugin
            #        happens to never return anything, then the gui is never updated
            if display_frame is None:
                canvas.set_colour((0, 0, 0))
                display_frame = canvas

            for output_device in output_devices:
                output_device.send_data(display_frame)

            # Limit the framerate, we need not do it in the plugins - they really shouldn't
            #  mind that we are running at a max of 25fps
            self.clock.tick(25)

        pygame.quit()
        exit()
Ejemplo n.º 30
0
from pygame.locals import *

if __name__ == "__main__":
    pygame.init()
    # create new state machine and register the clock  tick method
    # as our incrementing callback for current ticks in ms.
    clock = pygame.time.Clock()
    statemanager = StateManager(clock.tick)
    pygame.mixer.init()
    statemanager.add(MusicStart("assets/sound/intro.ogg"))
    statemanager.add(Blank(1500))
    statemanager.add(
        Fader("CandL Development Presents", 750, 1500, 3000,
              "1938 STeMPEL.ttf", (196, 56, 21)))
    statemanager.add(Blank(1000))
    statemanager.add(
        Fader("A Peter + Lucy Production", 750, 1500, 3000, "1938 STeMPEL.ttf",
              (171, 252, 251)))
    statemanager.add(Blank(1000))
    statemanager.add(
        Fader("S O L A R  |  F L A I R", 2500, 3000, 9000, "good times rg.ttf",
              (252, 240, 15)))
    statemanager.add(Blank(500))
    statemanager.add(MusicStop())
    statemanager.add(Menu(statemanager))
    statemanager.add(
        Fader("THANKS FOR PLAYING!", 500, 4000, 5000, "good times rg.ttf",
              (171, 252, 251)))
    while statemanager.update():
        pass
Ejemplo n.º 31
0
    def run_ddrpi(self):
        self.logger.info("Starting DDRPi running at %s" %
                         (time.strftime('%H:%M:%S %d/%m/%Y %Z')))
        config = self.parse_commandline_arguments()
        self.logger.info("%s" % config)

        # Initialise pygame, which we use for the GUI, controllers, rate limiting etc...
        pygame.init()
        # Set up a list of output endpoints, and input adapaters
        output_devices = []
        input_adapters = []

        # Parse the floor layout
        layout = DisplayLayout(config)
        converter = layout.get_converter()

        # Create a suitably sized canvas for the given config
        canvas = FloorCanvas(layout.size_x, layout.size_y)

        # Create a menu object to handle user input
        menu = Menu()

        output_filters = []
        if ("system" in config and "filters" in config["system"]):
            print("Found filters config: %s" % config["system"]["filters"])
            for filter_number, filter_config in sorted(
                    config["system"]["filters"].items()):
                if ("name" in filter_config
                        and filter_config["name"] == "ClearFilter"):
                    output_filters.append(ClearFilter(filter_config))
                elif ("name" in filter_config
                      and filter_config["name"] == "NegativeFilter"):
                    output_filters.append(NegativeFilter(filter_config))
                elif ("name" in filter_config
                      and filter_config["name"] == "NeutralDensityFilter"):
                    output_filters.append(NeutralDensityFilter(filter_config))

        # Set up the various outputs defined in the config.
        # Known types are the moment are "gui", "serial" and "pipe"
        if ("outputs" in config):
            for output_number, details in config["outputs"].items():
                self.logger.info("%d - %s" % (output_number, details))
                if "enabled" in details:
                    if details["enabled"] is False:
                        self.logger.info("Skipping disabled output %d" %
                                         output_number)
                        self.logger.info("%s" % details)
                        continue
                self.logger.info("Configuring output %d" % output_number)
                if details["type"] == "serial":
                    self.logger.info("Creating a SerialOutput class")
                    serial_output = SerialOutput(details)
                    serial_output.set_name("SerialOutput-#%d" % output_number)
                    serial_output.set_output_converter(converter)
                    for output_filter in output_filters:
                        serial_output.append_filter(output_filter)
                    output_devices.append(serial_output)
                elif details["type"] == "gui":
                    # Skip the gui if headless has been specified
                    if "headless" in config[
                            "system"] and config["system"]["headless"] is True:
                        continue
                    self.logger.info(
                        "Creating a GuiOutput class [There can be only one]")
                    gui_output = GuiOutput()
                    output_devices.append(gui_output)
                    self.gui = gui_output
                elif details["type"] == "pipe":
                    self.logger.info("Creating a PipeOutput class")
                    pipe_output = PipeOutput(details)
                    pipe_output.set_output_converter(converter)
                    output_devices.append(pipe_output)
                else:
                    self.logger.warn(
                        "I don't know how to handle an output of type '%s'" %
                        (details["type"]))

        # Initialise any connected joypads/joysticks
        controllers = self.init_joysticks()

        # There can be many plugin directories, and can either be relative (from the directory in which this
        #  script resides), or absolute. All directories are scanned, and the plugins found are added to the
        #  master list. If there are duplicate class names, the last one encountered probably wins silently.
        visualisation_plugin_dirs = ["visualisation_plugins", "game_plugins"]

        # We will store a dict of classname > class object in here
        available_plugins = self.load_plugins(visualisation_plugin_dirs)

        # Add all the available plugins to the menu
        #menu.add_available_plugins(available_plugins)

        # Create a data model that we can use here, and pass to the
        #  menu class to change what is active
        # We should also be able to provide this model to a webservice
        #  class if we chose to add in HTTP control of the floor too
        plugin_model = PluginModel((layout.size_x, layout.size_y))

        # Populate the data model
        plugin_model.add_plugins(available_plugins)

        # Link it up to the menu
        menu.set_plugin_model(plugin_model)

        # If we have defined a specific plugin to run indefinitely on the command line, use that
        specific_plugin = False
        if "plugin" in config["system"]:
            only_plugin = config["system"]["plugin"]
            if plugin_model.set_current_plugin(only_plugin) is not None:
                self.logger.info("Running requested plugin %s" % only_plugin)
                specific_plugin = True
            else:
                self.logger.info("Unable to find requested plugin: %s" %
                                 (only_plugin))
                self.logger.info("Available plugins are:")
                for available_plugin in available_plugins:
                    self.logger.info("  %s" % (available_plugin))
                # This is intended as a development debug option, or at the very least the
                #  person using it should know what they are doing, so if it isn't available
                #  for whatever reason, exit.
                exit()

        if "playlist" in config["system"]:

            # Retrieve the list of playlists specified on the command line
            #  or config file
            playlist_list = config["system"]["playlist"]
            self.logger.info(playlist_list)
            if len(playlist_list) > 0:
                for playlist in playlist_list:
                    # Make the playlist an absolute path if it isn't already
                    if not os.path.isabs(playlist):
                        root_directory = os.path.dirname(
                            os.path.realpath(__file__))
                        playlist = os.path.join(root_directory, playlist)
                    # Load the playlist
                    plugin_model.add_playlist_from_file(playlist)
                # Start the first one we added
                self.logger.info(
                    "Setting current playlist to the first one we added")
                plugin_model.set_current_playlist_by_index(1)

        if "twitter" in config:

            if "enabled" in config["twitter"] and config["twitter"][
                    "enabled"] is not True:
                # Don't do anything, we don't want it at the moment
                pass

            else:

                # Only bother importing this module if we are going to use it, hence not requiring
                #  an extra dependency on a Twitter library if people don't want to use that
                from lib.twitter import TwitterPlaylist

                # Get the twitter credentials from the configuration file:
                twitter_details = config["twitter"]

                # If we want to limit which plugins can be selected by Twitter, do so here
                plugin_whitelist = available_plugins

                # Create the twitter plugin playlist
                twitter_playlist = TwitterPlaylist(plugins=plugin_whitelist,
                                                   details=twitter_details)

                playlist_index = plugin_model.add_playlist(twitter_playlist)
                if plugin_model.get_current_playlist() is None:
                    plugin_model.set_current_playlist_by_index(playlist_index)

        # When there is no plugin specified and no user playlists either, make the first
        #  playlist active, and select either the first plugin, or, if it is available,
        #  any of the plugins listed in DEFAULT_STARTUP_PLUGIN

        # .set_current_plugin() is a convenience method to start the all_plugins playlist
        #  with the given plugin name
        self.logger.info("Current playlist: %s" %
                         plugin_model.get_current_playlist())
        have_started_a_plugin = False
        if plugin_model.get_current_playlist() is None:
            for specified_plugin in self.DEFAULT_STARTUP_PLUGIN:
                if plugin_model.set_current_plugin(
                        specified_plugin) is not None:
                    have_start_a_plugin = True
                    self.logger.info("Started default plugin %s" %
                                     specified_plugin)
                    break

            # If we still haven't started anything, just start the all_plugins playlist
            if have_started_a_plugin is False:
                plugin_model.set_current_playlist_by_index(0)

        print(plugin_model)
        #
        if self.gui is not None:
            #playlistModel.add_model_changed_listener(self.gui)
            #			self.gui.set_playlist_model(playlistModel)
            self.gui.set_plugin_model(plugin_model)

        # Create an object that can map key events to joystick events
        self.controller_mapper = ControllerInput()

        # The main loop is an event loop, with each part
        #  non-blocking and yields after doing a short bit.
        # Each 'bit' is a frame

        # Check for pygame events, primarily coming from
        #  gamepads and the keyboard

        running = True
        while running:

            current_playlist = plugin_model.get_current_playlist()
            current_plugin = None
            if current_playlist is not None:
                current_plugin = current_playlist.get_current_plugin()

            for e in pygame.event.get():

                if e.type == pygame.QUIT:
                    running = False

                e = self.controller_mapper.map_event(e)

                # Each consumer should return None if the
                #  event has been consumed, or return
                #  the event if something else should
                #  act upon it

                # Check first if the framework is going to
                #  consume this event. This includes heading
                #  into menus, possibly modifying the plugin
                #  model (previous/next plugin)
                #e = self.handle_event(e)
                #if e is None:
                #	continue

                # See if the menu wants to consume this event
                e = menu.handle_event(e)
                if e is None:
                    continue

                #self.print_input_event(e)

                # Next pass it on to the current plugin, if
                #  there is one
                if current_plugin is not None:
                    #					e = current_plugin['instance'].handle_event(e)
                    e = current_plugin.instance.handle_event(e)
                    if e is None:
                        continue

            # Ask the framework if it thinks it is displaying something
            # display_frame = self.draw_frame(canvas)
            # Ask the menu if it wants to draw something
            display_frame = menu.draw_frame(canvas)
            if display_frame is None:
                # If there is nothing to draw from the framework, ask
                #  the current plugin to do something is there is one
                if current_plugin is not None:
                    #					display_frame = current_plugin['instance'].draw_frame(canvas)
                    # There is every chance that the plugin might throw an
                    #  exception as we have no control over the quality of
                    #  external code (or some in-house code!), so catch any
                    #  exception
                    try:
                        display_frame = current_plugin.instance.draw_frame(
                            canvas)
                    except Exception as e:
                        self.logger.warn(
                            "Current plugin threw an error whilst running draw_frame()"
                        )
                        self.logger.warn(e)
                        display_frame = self.draw_error(canvas)

                else:
                    # If there is no plugin, then the framework should
                    #  do something
                    pass

            # Send the data to all configured outputs if there is any to send
            # TODO: If the plugin doesn't return a canvas for some reason,
            #        then the gui should be updated with a canvas, but the output
            #        plugins need not be informed. The problem is that if the plugin
            #        happens to never return anything, then the gui is never updated
            if display_frame is None:
                canvas.set_colour((0, 0, 0))
                display_frame = canvas

            for output_device in output_devices:
                output_device.send_data(display_frame)

            # Limit the framerate, we need not do it in the plugins - they really shouldn't
            #  mind that we are running at a max of 25fps
            self.clock.tick(25)

        pygame.quit()
        exit()