Exemplo n.º 1
0
    def navigate(data, x, y, screen):
        if x == 0 and y == 0:
            ScreenManager.throw(screen, "Naviagte with arrow keys and press q to exit")

        screen.clear()
        screen.keypad(1)
        active = tableDisplay.organize(data, x, y, screen)
        dim = screen.getmaxyx()
        screen.addstr(0, 0, active[0], curses.A_BOLD)
        for i in range(dim[0]-1):
            try:
                screen.addstr(i+1, 0, active[i+1])
            except:
                pass
        screen.refresh()
        choice = screen.getch()
        if choice == curses.KEY_LEFT:
            if x != 0:
                return tableDisplay.navigate(data, x-1, y, screen)
            else:
                return tableDisplay.navigate(data, x, y, screen)
        if choice == curses.KEY_RIGHT:
            return tableDisplay.navigate(data, x+1, y, screen)
        if choice == curses.KEY_DOWN:
            return tableDisplay.navigate(data, x, y+1, screen)
        if choice == curses.KEY_UP:
            if y != 0:
                return tableDisplay.navigate(data, x, y-1, screen)
            else:
                return tableDisplay.navigate(data, x, y, screen)
        if choice == ord('q'):
            return
        else:
            return tableDisplay.navigate(data, x, y, screen)
Exemplo n.º 2
0
    def __init__(self, window, size, options):
        """ Initialise and start the snackspace application """

        self.inittime = int(time.time())

        self.options = options

        self.input_handler = InputHandler()

        self.task_handler = TaskHandler(self)
        self.task_handler.add_function(self.rfid_task, 500, True)

        self.logger = logging.getLogger("snackspace")

        self.rfid = RFIDReader(self.options.rfid_port)

        self.is_fullscreen = True
        self.cursor_visible = False

        self.window_size = size
        self.screen_manager = ScreenManager(self, window, size)

        self.user = None
        self.products = []

        self.reply_queue = Queue.Queue()

        self.dbaccess = DbClient(self.options.hostip, self.task_handler,
                                 self.db_state_callback)
        self.dbaccess.daemon = True
        self.dbaccess.start()
Exemplo n.º 3
0
 def __init__(self, stdscreen, userpass):
     self.username = userpass['user']
     self.password = userpass['pass']
     self.screen = stdscreen
     self.dimensions = self.screen.getmaxyx() 
     self.screen_manager = ScreenManager(self.screen)
     self.all_databases_query = "SELECT pg_catalog.pg_database.datname FROM pg_catalog.pg_database WHERE pg_catalog.pg_get_userbyid(pg_catalog.pg_database.datdba) = \'%s\';" % (self.username)
     self.all_tables_query = "SELECT table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;"
     self.current_database = None
Exemplo n.º 4
0
 def create_database(self, name):
     to_query = "SELECT 1 FROM pg_database WHERE datname = \'%s\'" % (name)
     database_exists = query.query(to_query, 'postgres', self.screen, None, None, self.username, self.password)
     if database_exists[1]:
         ScreenManager.throw(self.screen, 'Database already exists.')
         return False
     else:
         db_creation_query = "CREATE DATABASE " + name 
         if query.query(db_creation_query, 'postgres', self.screen, 0, None, self.username, self.password) == -1:
             ScreenManager.throw(self.screen, "An error prevented database creation.")
             return False
         return True
Exemplo n.º 5
0
 def createTable(self, dbname):
     self.screen_manager.set_cursor_visible()
     curses.echo()
     self.screen_manager.display_mid("Please enter a name for the new table: ")
     new_table_name = self.screen_manager.screen.getstr()
     self.screen.clear()
     
     table_creation_query = "CREATE TABLE IF NOT EXISTS " + new_table_name + "(ID INT PRIMARY KEY      NOT NULL);" 
     if query.query(table_creation_query, dbname, self.screen, 0, None, self.username, self.password) == -1:
         ScreenManager.throw(self.screen, "An error prevented table creation.")
     else:
         self.screen_manager.display_mid("Table successfully created!")
         self.screen_manager.screen.getstr()
     self.screen.clear()
Exemplo n.º 6
0
    def create_user(self):
        self.screen_manager.display_mid('Please enter your desired Username: '******'Please enter your desired Password: '******'%s\'" % self.username
        rows = query.query(to_query, 'postgres', self.screen)

        if rows[1]:
            ScreenManager.throw(self.screen, 'Username already in use.')
            return LoginScreen.create_user(self)
        else:
            to_query = "CREATE USER %s WITH CREATEDB PASSWORD \'%s\'" % (
                self.username, self.password)
            if query.query(to_query, 'postgres', self.screen) == -1:
                ScreenManager.throw(self.screen,
                                    "An error prevented user creation.")
                return False
            to_query = "CREATE DATABASE %s_default" % (self.username)
            if query.query(to_query, 'postgres', self.screen, 0) == -1:
                ScreenManager.throw(
                    self.screen,
                    "An error occured during user default database creation.")
                return False
            to_query = "ALTER DATABASE %s_default owner to %s" % (
                self.username, self.username)
            if query.query(to_query, 'postgres', self.screen) == -1:
                ScreenManager.throw(
                    self.screen,
                    "An error occured while assigning new user to default database."
                )
                return False

            return True
Exemplo n.º 7
0
    def create_user(self):
        self.screen_manager.display_mid('Please enter your desired Username: '******'Please enter your desired Password: '******'%s\'" % self.username
        rows = query.query(to_query, 'postgres', self.screen)
        
        if rows[1]:
            ScreenManager.throw(self.screen, 'Username already in use.')
            return LoginScreen.create_user(self)
        else:
            to_query = "CREATE USER %s WITH CREATEDB PASSWORD \'%s\'" % (self.username, self.password)
            if query.query(to_query, 'postgres', self.screen) == -1:
                ScreenManager.throw(self.screen, "An error prevented user creation.")
                return False
            to_query = "CREATE DATABASE %s_default" % (self.username)
            if query.query(to_query, 'postgres', self.screen, 0) == -1:
                ScreenManager.throw(self.screen, "An error occured during user default database creation.")
                return False
            to_query = "ALTER DATABASE %s_default owner to %s" % (self.username, self.username)
            if query.query(to_query, 'postgres', self.screen) == -1:
                ScreenManager.throw(self.screen, "An error occured while assigning new user to default database.")
                return False

            return True
Exemplo n.º 8
0
    def createTable(self, dbname):
        self.screen_manager.set_cursor_visible()
        curses.echo()
        self.screen_manager.display_mid(
            "Please enter a name for the new table: ")
        new_table_name = self.screen_manager.screen.getstr()
        self.screen.clear()

        table_creation_query = "CREATE TABLE IF NOT EXISTS " + new_table_name + "(ID INT PRIMARY KEY      NOT NULL);"
        if query.query(table_creation_query, dbname, self.screen, 0, None,
                       self.username, self.password) == -1:
            ScreenManager.throw(self.screen,
                                "An error prevented table creation.")
        else:
            self.screen_manager.display_mid("Table successfully created!")
            self.screen_manager.screen.getstr()
        self.screen.clear()
Exemplo n.º 9
0
	def run_game(self):
		master_screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
		pygame.display.set_caption("RM RPG")
		timer = pygame.time.Clock()

		#TEMP
		world = World()
		player = Player(world)
		world.add_player(player, 35, 20)
		#TEMP

		game_controls = WorldControls(player) # TODO: specify what kind of controls should be used at the start of the game and use a different constructor.
		control_manager = ControlManager(game_controls)
		main_screen = WorldScreen(control_manager, player) #TODO: specify type of screen
		screen_manager = ScreenManager(master_screen, main_screen, player)

		world.initialize_screen(screen_manager, main_screen)

		while 1:
			timer.tick(FRAMES) # make this value lower to make the game run slowly for testing. (use about 40-50 I think)
 			for e in pygame.event.get():
				screen_manager.process_event(e)
			screen_manager.update_current_screen()
			self.draw_screen(screen_manager)
			pygame.display.update()
			"""
			timer.tick(100)
			for e in pygame.event.get():
				if e.type == QUIT: raise SystemExit, "QUIT"
			screen.blit(player.image, (0, 0))
			pygame.display.update()
			"""
		"""GM.runGame (...) -> None

		Run the game using a pygame screen.

		Attributes:
		master_screen: the pygame screen onto which everything will be displayed
		during the game.
		"""

		"""
		start_dungeon, dungeon_name, master_screen = self.build_dungeon_and_screen() 
		world = World(start_dungeon) # TODO: implement world (contains all dungeons, along with other global data-- how to do this?)
		"""
		"""
Exemplo n.º 10
0
    def __init__(self):
        print("[APP ] Initialized\n")
        self.d = Display()
        self.ds = DataStore()
        self.sett = AppSettings()
        self.keypad = Keypad()
        self.sensors = Sensors()
        self.lightc = LightController(self.ds, self.sett)
        self.condc = CondController(self.ds, self.sett)
        self.fanc = FanController(self.ds, self.sett)
        self.evc = EVController(self.ds, self.sett)
        self.screenMngr = ScreenManager(self.d, self.ds, self.sett,
                                        self.keypad)
        self.screenMngr.update()

        self.processStart = 0
        self.screensStart = 0
Exemplo n.º 11
0
 def copy_database(self, database):
     db_name = database[0]
     
     self.screen_manager.set_cursor_visible()
     curses.echo()
     self.screen_manager.display_mid("Please enter a name for the new database: ")
     new_db_name = self.screen_manager.screen.getstr()
     self.screen.clear()
     
     db_copy_query = "CREATE DATABASE " + new_db_name + " WITH TEMPLATE " + db_name
     if query.query(db_copy_query, 'postgres', self.screen, 0, None, self.username, self.password) == -1:
         ScreenManager.throw(self.screen, "An error prevented database creation.")
     else:
         self.screen_manager.display_mid("The database " + new_db_name + " has been copied from " + db_name)
         self.screen.getstr()
     self.screen.clear()
     self.screen_manager.set_cursor_invisible()
Exemplo n.º 12
0
    def login(self):
        self.screen_manager.display_mid('Please enter your Username: '******'Please enter your Password: '******'root\'"
        rows = query.query(to_query, 'postgres', None, None, None, self.username, self.password)
        
        if rows != -1 and rows != -2:
            return True
        elif rows == -1:
            ScreenManager.throw(self.screen, "Couldn't sign in. Please ensure your system is set up correctly.")
            return False
        else:
            ScreenManager.throw(self.screen, "Incorrect Username or Password.")
            return False
Exemplo n.º 13
0
 def drop_database(self, database):
     db_name = database[0]
     
     self.screen_manager.set_cursor_visible()
     curses.echo()
     self.screen_manager.display_mid("Are you sure you want to delete " + db_name + "? (Y/N): ")
     confirmation = self.screen_manager.screen.getstr()
     if confirmation == 'Y':
         db_delete_query = "DROP DATABASE " + db_name
         if query.query(db_delete_query, 'postgres', self.screen, 0, None, self.username, self.password) == -1:
             ScreenManager.throw(self.screen, "An error prevented database creation.")
         else:
             self.screen_manager.display_mid("The database " + db_name + " has been deleted")
             self.screen.getstr()
     else:
         self.screen_manager.display_mid(db_name + " will not be deleted")
         self.screen_manager.screen.getstr()
     self.screen.clear()
     self.screen_manager.set_cursor_invisible()            
Exemplo n.º 14
0
    def login(self):
        self.screen_manager.display_mid('Please enter your Username: '******'Please enter your Password: '******'root\'"
        rows = query.query(to_query, 'postgres', None, None, None,
                           self.username, self.password)

        if rows != -1 and rows != -2:
            return True
        elif rows == -1:
            ScreenManager.throw(
                self.screen,
                "Couldn't sign in. Please ensure your system is set up correctly."
            )
            return False
        else:
            ScreenManager.throw(self.screen, "Incorrect Username or Password.")
            return False
Exemplo n.º 15
0
class App:
    def __init__(self):
        print("[APP ] Initialized\n")
        self.d = Display()
        self.ds = DataStore()
        self.sett = AppSettings()
        self.keypad = Keypad()
        self.sensors = Sensors()
        self.lightc = LightController(self.ds, self.sett)
        self.condc = CondController(self.ds, self.sett)
        self.fanc = FanController(self.ds, self.sett)
        self.evc = EVController(self.ds, self.sett)
        self.screenMngr = ScreenManager(self.d, self.ds, self.sett,
                                        self.keypad)
        self.screenMngr.update()

        self.processStart = 0
        self.screensStart = 0

    def process(self):
        delta = time.time() - self.processStart
        if (delta > 1.0):
            self.ds.add_humidity(self.sensors.humidity())
            self.ds.add_temperature(self.sensors.temperature())
            self.ds.add_lux(self.sensors.lux())

            if (self.lightc != None):
                self.lightc.process()
            if (self.condc != None):
                self.condc.process()
            if (self.fanc != None):
                self.fanc.process()
            if (self.evc != None):
                self.evc.process()

            self.processStart = time.time()

    def handleScreens(self):
        delta = time.time() - self.screensStart
        if (delta > 1.0):
            self.screenMngr.update()
            self.screensStart = time.time()

        self.screenMngr.process()
Exemplo n.º 16
0
class Snackspace:  # pylint: disable=R0902
    """ Implements the main snackspace class. Responsible for:
    DB and screen managers
    RFID and barcode scanners
    UI interaction via pygame
    pylint R0902 disabled: too many instance attributes
    """
    def __init__(self, window, size, options):
        """ Initialise and start the snackspace application """

        self.inittime = int(time.time())

        self.options = options

        self.input_handler = InputHandler()

        self.task_handler = TaskHandler(self)
        self.task_handler.add_function(self.rfid_task, 500, True)

        self.logger = logging.getLogger("snackspace")

        self.rfid = RFIDReader(self.options.rfid_port)

        self.is_fullscreen = True
        self.cursor_visible = False

        self.window_size = size
        self.screen_manager = ScreenManager(self, window, size)

        self.user = None
        self.products = []

        self.reply_queue = Queue.Queue()

        self.dbaccess = DbClient(self.options.hostip, self.task_handler,
                                 self.db_state_callback)
        self.dbaccess.daemon = True
        self.dbaccess.start()

    def start(self):
        """ The main snackspace event loop """
        ticks = 0

        while (1):
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.quit()
                if event.type == pygame.MOUSEBUTTONUP:
                    self.logger.debug("GUI Event")
                    self.screen_manager.current.on_gui_event(event.pos)

                if event.type == pygame.KEYDOWN:
                    self.keypress(event)

            try:
                packet = self.reply_queue.get(False)
                self.handle_new_packet(packet)

            except Queue.Empty:
                pass

            if (pygame.time.get_ticks() - ticks) > 0:

                ticks = pygame.time.get_ticks()

                self.task_handler.tick()

    def quit(self):

        #Request the DB client thread stop and wait for it to stop
        self.dbaccess.stop()
        while self.dbaccess.is_alive():
            pass
        sys.exit()

    def set_fullscreen(self, fullscreen):

        screen = pygame.display.get_surface()
        tmp = screen.convert()
        caption = pygame.display.get_caption()

        flags = screen.get_flags()

        if fullscreen:
            flags = flags | pygame.FULLSCREEN
        else:
            flags = flags & ~pygame.FULLSCREEN

        bits = screen.get_bitsize()

        #pygame.display.quit()
        #pygame.display.init()

        screen = pygame.display.set_mode(self.window_size, flags, bits)
        screen.blit(tmp, (0, 0))
        pygame.display.set_caption(*caption)

        self.is_fullscreen = fullscreen

    def handle_new_packet(self, packet):
        if packet.type == PacketTypes.ProductData:
            self.on_db_got_product_data(packet)
        elif packet.type == PacketTypes.UnknownProduct:
            self.on_db_got_unknown_product(packet)
        elif packet.type == PacketTypes.UserData:
            self.on_db_got_user_data(packet)
        elif packet.type == PacketTypes.RandomProduct:
            self.on_db_random_product_callback(packet)
        elif packet.type == PacketTypes.Result:
            if packet.data['action'] == PacketTypes.Transaction:
                self.charge_all_handler.on_db_send_transactions_callback(
                    packet)
            elif packet.data['action'] == PacketTypes.AddCredit:
                self.charge_all_handler.on_db_add_credit_callback(packet)
            elif packet.data['action'] == PacketTypes.AddProduct:
                self.on_db_add_product_callback(packet)

    def keypress(self, event):
        """ Handle a keyboard press or barcode scan character """
        # Push keypress to the current screen
        self.screen_manager.current.on_key_event(event.dict['unicode'])

        # Then do our own handling via the input handler
        result = self.input_handler.new_event(event)

        if result == InputHandler.FAKE_BAD_PRODUCT:
            # # Fake a bad product scan
            self.on_scan_event('BADBARCODE')

        elif result == InputHandler.FAKE_GOOD_PRODUCT:
            # # Fake a good product scan
            self.dbaccess.get_random_product(self.reply_queue)

        elif result == InputHandler.FAKE_RFID:
            # # Fake an RFID swipe
            self.rfid.set_fake_rfid()

        elif result == InputHandler.NEW_SCANNED_INPUT:
            # # Buffer is complete, process it
            scanned_input = self.input_handler.scanned_input
            self.input_handler.scanned_input = ''
            self.logger.debug("Got raw input '%s'" % scanned_input)
            self.on_scan_event(scanned_input)

        elif result == InputHandler.PRODUCT_ENTRY:
            # # Go to product entry screen
            self.screen_manager.req(Screens.PRODUCTENTRY)

        elif result == InputHandler.FULLSCREEN_TOGGLE:
            self.set_fullscreen(not self.is_fullscreen)
            self.screen_manager.req(self.screen_manager.currentscreen, True)

        elif result == InputHandler.CURSOR_TOGGLE:
            self.cursor_visible = not self.cursor_visible
            pygame.mouse.set_visible(self.cursor_visible)

        elif result == InputHandler.QUIT:
            self.quit()

    def rfid_task(self):
        """ To be run periodically to check for an RFID swipe """
        rfid = self.rfid.poll()

        if rfid is not None:
            self.on_swipe_event(self.rfid.mangle_rfid(rfid))

    def db_state_callback(self, old_state, new_state, first_update):
        """ Callback when database state changes """

        if old_state != new_state or first_update:
            self.screen_manager.get(
                Screens.INTROSCREEN).set_db_state(new_state)
            if not new_state:
                self.screen_manager.get(Screens.MAINSCREEN).clear_all()
                self.forget_products()
                self.forget_user()

    def on_swipe_event(self, cardnumber):
        """ When an RFID swipe is made, gets user from the database """
        if not self.dbaccess.found_server:
            return
        else:
            self.dbaccess.get_user_data(cardnumber, self.reply_queue)

    def on_scan_event(self, barcode):
        """ When a barcode scan is made, pulls product from the database """
        if not self.dbaccess.found_server or len(barcode) == 0:
            return

        self.add_product_to_basket(barcode)

    def charge_all(self, callback):
        """ Charge the current user for the current set of products """
        self.charge_all_handler = ChargeAllHandler(self.dbaccess, self.user,
                                                   self.products, callback,
                                                   self.reply_queue)

    def credit_user(self, amount):
        """ Adds credit to a user's account """
        self.user.add_credit(amount)

    def forget_user(self):
        """ Clear the user """
        self.user = None

    def total_price(self):
        """ Get the total price of the basket """
        return sum([product.total_price for product in self.products])

    def remove_product(self, product_to_remove):
        """ Remove a product from the basket """

        # First reduce the count of this product.
        # If zero, the product itself can be removed from the list
        if product_to_remove.decrement() == 0:
            self.products = [
                product for product in self.products
                if product != product_to_remove
            ]

        return product_to_remove.count

    def forget_products(self):
        """ Delete the product basket """
        self.products = []

    def new_product(self, barcode, description, priceinpence, callback):
        """ Add a new product to the database """
        self.dbaccess.add_product(barcode, description, priceinpence, callback)

    def add_product_to_basket(self, barcode):
        """ Adds a new scanned product to the list ('basket') of scanned products """
        product = next(
            (product
             for product in self.products if barcode == product.barcode), None)

        if product is not None:
            product.increment(
            )  # Product already exists once, so just increment its count
            self.screen_manager.current.on_scan(product)
        else:
            # Otherwise need to get product info from the database
            self.dbaccess.get_product(barcode, self.reply_queue)

    def on_db_random_product_callback(self, packet):
        """ Callback when random product data is returned from the database """
        barcode = packet.data['barcode']
        self.on_scan_event(barcode)

    def on_db_got_user_data(self, packet):
        """ Callback when user data returned """

        member_id = packet.data['memberid']
        username = packet.data['username']
        balance = packet.data['balance']
        credit_limit = packet.data['limit']

        self.user = User(member_id, username, balance, credit_limit,
                         self.options)
        self.logger.debug("Got user %s" % self.user.name)
        self.screen_manager.current.on_rfid()

    def on_db_got_unknown_user(self, packet):
        self.logger.debug("Bad RFID %s" % packet.data['rfid'])
        self.screen_manager.current.OnBadRFID()

    def on_db_got_product_data(self, packet):
        """ Called when product data returned """
        barcode = packet.data['barcode']
        description = packet.data['description']
        priceinpence = packet.data['priceinpence']

        product = Product(barcode, description, priceinpence)  # pylint: disable=W0142

        if product.valid:
            self.products.append(product)
            self.screen_manager.current.on_scan(product)

    def on_db_got_unknown_product(self, packet):
        """ Called when user data request failed """
        barcode = packet.data['barcode']
        self.screen_manager.current.on_bad_scan(barcode)
Exemplo n.º 17
0
class DatabaseManager(object):       
    def __init__(self, stdscreen, userpass):
        self.username = userpass['user']
        self.password = userpass['pass']
        self.screen = stdscreen
        self.dimensions = self.screen.getmaxyx() 
        self.screen_manager = ScreenManager(self.screen)
        self.all_databases_query = "SELECT pg_catalog.pg_database.datname FROM pg_catalog.pg_database WHERE pg_catalog.pg_get_userbyid(pg_catalog.pg_database.datdba) = \'%s\';" % (self.username)
        self.all_tables_query = "SELECT table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;"
        self.current_database = None
        
    #Database query methods
    def fetch_all_databases(self):
        databases = query.query(self.all_databases_query, 'postgres', self.screen, None, None, self.username, self.password)
        return databases[1]
        
    def create_database(self, name):
        to_query = "SELECT 1 FROM pg_database WHERE datname = \'%s\'" % (name)
        database_exists = query.query(to_query, 'postgres', self.screen, None, None, self.username, self.password)
        if database_exists[1]:
            ScreenManager.throw(self.screen, 'Database already exists.')
            return False
        else:
            db_creation_query = "CREATE DATABASE " + name 
            if query.query(db_creation_query, 'postgres', self.screen, 0, None, self.username, self.password) == -1:
                ScreenManager.throw(self.screen, "An error prevented database creation.")
                return False
            return True
    
    #Display methods
    def display_all_databases(self):   
        parsed_dbs = []
        databases = self.fetch_all_databases()
        if databases is not None:
            for db in databases:
                lst = list(db)
                lst.append(curses.flash)
                parsed_dbs.append(tuple(lst))
            headeroptions = {'title':"List of Databases",'user':self.username}
            displayDatabasesMenu = Menu(parsed_dbs, self.screen, headeroptions)
            displayDatabasesMenu.display()

    #Display methods
    def display_all_databases_opt(self, action):   
        parsed_dbs = []
        databases = self.fetch_all_databases()
        if databases is not None:
            for db in databases:
                lst = (str(db[0]),action,str(db[0]))
                parsed_dbs.append(tuple(lst))
            headoptions = {'title':"Select Database",'user':self.username}
            displayDatabasesMenu = Menu(parsed_dbs, self.screen, headoptions)
            displayDatabasesMenu.display()
    
    def display_all_copy_database(self):   
        parsed_dbs = []
        databases = self.fetch_all_databases()
        if databases is not None:
            for db in databases:
                lst = list(db)
                lst.append(self.copy_database)
                lst.append(db)
                parsed_dbs.append(tuple(lst))
            headoptions = {'title':"Select Database to Copy",'user':self.username}
            displayDatabasesMenu = Menu(parsed_dbs, self.screen, headoptions)
            displayDatabasesMenu.display()
    
    def display_all_delete_database(self):   
        parsed_dbs = []
        databases = self.fetch_all_databases()
        if databases is not None:
            for db in databases:
                lst = list(db)
                lst.append(self.drop_database)
                lst.append(db)
                parsed_dbs.append(tuple(lst))
            headoptions = {'title':"Select Database to delete",'user':self.username}
            displayDatabasesMenu = Menu(parsed_dbs, self.screen, headoptions)
            displayDatabasesMenu.display()
            
    def copy_database(self, database):
        db_name = database[0]
        
        self.screen_manager.set_cursor_visible()
        curses.echo()
        self.screen_manager.display_mid("Please enter a name for the new database: ")
        new_db_name = self.screen_manager.screen.getstr()
        self.screen.clear()
        
        db_copy_query = "CREATE DATABASE " + new_db_name + " WITH TEMPLATE " + db_name
        if query.query(db_copy_query, 'postgres', self.screen, 0, None, self.username, self.password) == -1:
            ScreenManager.throw(self.screen, "An error prevented database creation.")
        else:
            self.screen_manager.display_mid("The database " + new_db_name + " has been copied from " + db_name)
            self.screen.getstr()
        self.screen.clear()
        self.screen_manager.set_cursor_invisible()
        
    def drop_database(self, database):
        db_name = database[0]
        
        self.screen_manager.set_cursor_visible()
        curses.echo()
        self.screen_manager.display_mid("Are you sure you want to delete " + db_name + "? (Y/N): ")
        confirmation = self.screen_manager.screen.getstr()
        if confirmation == 'Y':
            db_delete_query = "DROP DATABASE " + db_name
            if query.query(db_delete_query, 'postgres', self.screen, 0, None, self.username, self.password) == -1:
                ScreenManager.throw(self.screen, "An error prevented database creation.")
            else:
                self.screen_manager.display_mid("The database " + db_name + " has been deleted")
                self.screen.getstr()
        else:
            self.screen_manager.display_mid(db_name + " will not be deleted")
            self.screen_manager.screen.getstr()
        self.screen.clear()
        self.screen_manager.set_cursor_invisible()            
    
    def create_new_database(self):
        self.screen_manager.set_cursor_visible()
        curses.echo()
        self.screen_manager.display_mid("Please enter a name for the new database: ")
        database_name = self.screen_manager.screen.getstr()
        self.screen.clear()
        try:
           did_create_database = self.create_database(database_name)
        except RuntimeError as rt_error:
           self.screen_manager.display_mid("Error with the database creation query")
        else:
            if did_create_database is True:
                self.screen_manager.display_mid("The database " + database_name + " has been created")
                self.screen.getstr()
        self.screen.clear()
        self.screen_manager.set_cursor_invisible()
Exemplo n.º 18
0
 def __init__(self):
     self.username = ''  #username we will store from the user input
     self.password = ''
     self.screen = curses.initscr()
     self.screen_manager = ScreenManager(self.screen)
Exemplo n.º 19
0
class LoginScreen:
    def __init__(self):
        self.username = ''  #username we will store from the user input
        self.password = ''
        self.screen = curses.initscr()
        self.screen_manager = ScreenManager(self.screen)

    #recursive function used to select either create account or login
    def selector(self, location):
        self.screen.keypad(1)
        dimensions = self.screen.getmaxyx()
        self.screen.clear()
        message = "Select Using ->, <-, and Enter:"
        self.screen.addstr(dimensions[0] / 3,
                           dimensions[1] / 2 - len(message) / 2, message)
        if (location):
            message = 'Login'
            self.screen.addstr(dimensions[0] / 2,
                               dimensions[1] / 3 - len(message) / 2, message,
                               curses.A_DIM)
            message = 'Create User'
            self.screen.addstr(dimensions[0] / 2,
                               2 * dimensions[1] / 3 - len(message) / 2,
                               message, curses.A_STANDOUT)
            self.screen.refresh()
        else:
            message = 'Login'
            self.screen.addstr(dimensions[0] / 2,
                               dimensions[1] / 3 - len(message) / 2, message,
                               curses.A_STANDOUT)
            message = 'Create User'
            self.screen.addstr(dimensions[0] / 2,
                               2 * dimensions[1] / 3 - len(message) / 2,
                               message, curses.A_DIM)
            self.screen.refresh()

        choice = self.screen.getch()
        if choice == ord('\n'):
            return location
        elif choice == curses.KEY_LEFT:
            return LoginScreen.selector(self, 0)
        elif choice == curses.KEY_RIGHT:
            return LoginScreen.selector(self, 1)
        else:
            return LoginScreen.selector(self, location)

    #function used to insert a new user into the databse:
    def create_user(self):
        self.screen_manager.display_mid('Please enter your desired Username: '******'Please enter your desired Password: '******'%s\'" % self.username
        rows = query.query(to_query, 'postgres', self.screen)

        if rows[1]:
            ScreenManager.throw(self.screen, 'Username already in use.')
            return LoginScreen.create_user(self)
        else:
            to_query = "CREATE USER %s WITH CREATEDB PASSWORD \'%s\'" % (
                self.username, self.password)
            if query.query(to_query, 'postgres', self.screen) == -1:
                ScreenManager.throw(self.screen,
                                    "An error prevented user creation.")
                return False
            to_query = "CREATE DATABASE %s_default" % (self.username)
            if query.query(to_query, 'postgres', self.screen, 0) == -1:
                ScreenManager.throw(
                    self.screen,
                    "An error occured during user default database creation.")
                return False
            to_query = "ALTER DATABASE %s_default owner to %s" % (
                self.username, self.username)
            if query.query(to_query, 'postgres', self.screen) == -1:
                ScreenManager.throw(
                    self.screen,
                    "An error occured while assigning new user to default database."
                )
                return False

            return True

    def login(self):
        self.screen_manager.display_mid('Please enter your Username: '******'Please enter your Password: '******'root\'"
        rows = query.query(to_query, 'postgres', None, None, None,
                           self.username, self.password)

        if rows != -1 and rows != -2:
            return True
        elif rows == -1:
            ScreenManager.throw(
                self.screen,
                "Couldn't sign in. Please ensure your system is set up correctly."
            )
            return False
        else:
            ScreenManager.throw(self.screen, "Incorrect Username or Password.")
            return False

    #function that prints a flowing welcome message
    def welcome(self):
        anim = Animators()
        anim.enter_down(self.screen, "Welcome!")
        time.sleep(.25)
        anim.exit_up(self.screen, "Welcome!")
        self.screen.clear()
Exemplo n.º 20
0
 def __init__(self, stdscreen, userpass):
     self.username = userpass['user']
     self.password = userpass['pass']
     self.screen = stdscreen
     self.dimensions = self.screen.getmaxyx() 
     self.screen_manager = ScreenManager(self.screen)
Exemplo n.º 21
0
def main():
    """Application entry point"""

    global running

    num_array = []
    last_added = time.monotonic()
    ignore_quit = False

    if not platform.system() == "Linux":
        sys.exit("'%s' OS not supported!" % platform.system())

    if os.geteuid() == 0:
        sys.exit("Camplayer is not supposed to be run as root!")

    GLOBALS.PYTHON_VER = sys.version_info
    if GLOBALS.PYTHON_VER < CONSTANTS.PYTHON_VER_MIN:
        sys.exit("Python version '%i.%i' or newer required!"
                 % (CONSTANTS.PYTHON_VER_MIN[0], CONSTANTS.PYTHON_VER_MIN[1]))

    # Started with arguments?
    if len(sys.argv) > 1:
        for idx, arg in enumerate(sys.argv):

            # 1st argument is application
            if idx == 0:
                continue

            # Help info
            if arg == "-h" or arg == "--help":
                print("         -h  --help                  Print this help")
                print("         -v  --version               Print version info")
                print("         -c  --config                Use a specific config file")
                print("             --rebuild-cache         Rebuild cache on startup")
                print("             --rebuild-cache-exit    Rebuild cache and exit afterwards")
                print("         -d  --demo                  Demo mode")
                print("             --ignorequit            Don't quit when the 'Q' key is pressed")
                sys.exit(0)

            # Run in a specific mode
            if arg == "--rebuild-cache" or arg == "--rebuild-cache-exit":

                # Clearing the cache
                clear_cache()

                # Rebuild cache only and exit
                if arg == "--rebuild-cache-exit":

                    # Exit when reaching the main loop
                    running = False

            # Run with a specific config file
            if arg == "-c" or arg == "--config" and (idx + 1) < len(sys.argv):
                CONSTANTS.CONFIG_PATH = sys.argv[idx + 1]

            # Display version info
            if arg == "-v" or arg == "--version":
                print("version " + __version__)
                sys.exit(0)

            # Run demo mode
            if arg == "-d" or arg == "--demo":
                CONSTANTS.CONFIG_PATH = CONSTANTS.DEMO_CONFIG_PATH

            # Ignore keyboard 'quit' command
            if arg == "--ignorequit":
                ignore_quit = True

    # Load settings from config file
    CONFIG.load()

    # Signal handlers
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

    LOG.INFO(_LOG_NAME, "Starting camplayer version %s" % __version__)
    LOG.INFO(_LOG_NAME, "Using config file '%s' and cache directory '%s'"
             % (CONSTANTS.CONFIG_PATH, CONSTANTS.CACHE_DIR))

    # Cleanup some stuff in case something went wrong on the previous run
    utils.kill_service('omxplayer.bin', force=True)
    utils.kill_service('vlc', force=True)
    utils.kill_service('pipng', force=True)

    # OMXplayer is absolutely required!
    if not utils.os_package_installed("omxplayer.bin"):
        sys.exit("OMXplayer not installed but required!")

    # ffprobe is absolutely required!
    if not utils.os_package_installed("ffprobe"):
        sys.exit("ffprobe not installed but required!")

    # Get system info
    sys_info = utils.get_system_info()
    gpu_mem = utils.get_gpu_memory()
    hw_info = utils.get_hardware_info()

    # Set some globals for later use
    GLOBALS.PI_SOC          = hw_info.get("soc")    # Not very reliable, usually reports BCM2835
    GLOBALS.PI_MODEL        = hw_info.get("model")
    GLOBALS.PI_SOC_HEVC     = hw_info.get('hevc')
    GLOBALS.NUM_DISPLAYS    = 2 if hw_info.get('dual_hdmi') else 1
    GLOBALS.VLC_SUPPORT     = utils.os_package_installed("vlc")
    GLOBALS.PIPNG_SUPPORT   = utils.os_package_installed("pipng")
    GLOBALS.FFMPEG_SUPPORT  = utils.os_package_installed("ffmpeg")
    GLOBALS.USERNAME        = os.getenv('USER')

    # Log system info
    LOG.INFO(_LOG_NAME, "********************** SYSTEM INFO **********************")
    LOG.INFO(_LOG_NAME, str("Camplayer version             = %s" % __version__))
    LOG.INFO(_LOG_NAME, str("Operating system              = %s" % sys_info))
    LOG.INFO(_LOG_NAME, str("Raspberry Pi SoC              = %s" % hw_info.get("soc")))
    LOG.INFO(_LOG_NAME, str("Raspberry Pi revision         = %s" % hw_info.get("revision")))
    LOG.INFO(_LOG_NAME, str("Raspberry Pi model name       = %s" % hw_info.get("model")))
    LOG.INFO(_LOG_NAME, str("GPU memory allocation         = %i MB" % gpu_mem))
    LOG.INFO(_LOG_NAME, str("Python version                = %s MB" % sys.version.splitlines()[0]))
    LOG.INFO(_LOG_NAME, str("VLC installed                 = %s" % GLOBALS.VLC_SUPPORT))
    LOG.INFO(_LOG_NAME, str("pipng installed               = %s" % GLOBALS.PIPNG_SUPPORT))
    LOG.INFO(_LOG_NAME, str("ffmpeg installed              = %s" % GLOBALS.FFMPEG_SUPPORT))
    LOG.INFO(_LOG_NAME, "*********************************************************")

    # Register for keyboard 'press' events, requires root
    # TODO: check privileges?
    keyboard = InputMonitor(event_type=['press'])

    # Log overwrites for debugging purpose
    for setting in CONFIG.advanced_overwritten:
        LOG.INFO(_LOG_NAME, "advanced setting overwritten for '%s' is '%s'" % (setting[0], setting[1]))

    # Does this system fulfill the minimal requirements
    if CONFIG.HARDWARE_CHECK:
        if not hw_info.get("supported"):
            sys.exit("Unsupported hardware with revision %s ..." % hw_info.get("revision"))

        if gpu_mem < CONSTANTS.MIN_GPU_MEM:
            sys.exit("GPU memory of '%i' MB insufficient ..." % gpu_mem)

    # Auto detect screen resolution
    # For the raspberry pi 4:
    #   both HDMI displays are supposed to have the same configuration
    if CONFIG.SCREEN_HEIGHT == 0 or CONFIG.SCREEN_WIDTH == 0:
        display_conf = utils.get_display_mode()
        CONFIG.SCREEN_HEIGHT = display_conf.get('res_height')
        CONFIG.SCREEN_WIDTH = display_conf.get('res_width')
        LOG.INFO(_LOG_NAME, "Detected screen resolution for HDMI0 is '%ix%i@%iHz'" % (
            CONFIG.SCREEN_WIDTH, CONFIG.SCREEN_HEIGHT, display_conf.get('framerate')))

        if CONFIG.SCREEN_HEIGHT <= 0:
            CONFIG.SCREEN_HEIGHT = 1080
        if CONFIG.SCREEN_WIDTH <= 0:
            CONFIG.SCREEN_WIDTH = 1920

    # Are we sure the 2nd HDMI is on for dual HDMI versions?
    if GLOBALS.NUM_DISPLAYS == 2:
        # Check for resolution instead of display name as the latter one is empty with force HDMI hotplug
        if not utils.get_display_mode(display=7).get('res_height'):
            GLOBALS.NUM_DISPLAYS = 1

    # Calculate the virtual screen size now that we now the physical screen size
    CONSTANTS.VIRT_SCREEN_WIDTH = int(CONFIG.SCREEN_WIDTH * (100 - CONFIG.SCREEN_DOWNSCALE) / 100)
    CONSTANTS.VIRT_SCREEN_HEIGHT = int(CONFIG.SCREEN_HEIGHT * (100 - CONFIG.SCREEN_DOWNSCALE) / 100)
    CONSTANTS.VIRT_SCREEN_OFFSET_X = int((CONFIG.SCREEN_WIDTH - CONSTANTS.VIRT_SCREEN_WIDTH) / 2)
    CONSTANTS.VIRT_SCREEN_OFFSET_Y = int((CONFIG.SCREEN_HEIGHT - CONSTANTS.VIRT_SCREEN_HEIGHT) / 2)
    LOG.INFO(_LOG_NAME, "Using a virtual screen resolution of '%ix%i'" %
             (CONSTANTS.VIRT_SCREEN_WIDTH, CONSTANTS.VIRT_SCREEN_HEIGHT))

    # Workaround: srt subtitles have a maximum display time of 99 hours
    if CONFIG.VIDEO_OSD and (not CONFIG.REFRESHTIME_MINUTES or CONFIG.REFRESHTIME_MINUTES >= 99 * 60):
        CONFIG.REFRESHTIME_MINUTES = 99 * 60
        LOG.WARNING(_LOG_NAME, "Subtitle based OSD enabled, forcing 'refreshtime' to '%i'" % CONFIG.REFRESHTIME_MINUTES)

    # Show 'loading' on master display
    BackGroundManager.show_icon_instant(BackGround.LOADING, display_idx=0)

    # Initialize screens and windows
    screenmanager = ScreenManager()
    if screenmanager.valid_screens < 1:
        sys.exit("No valid screen configuration found, check your config file!")

    # Hide 'loading' message on master display
    BackGroundManager.hide_icon_instant(display_idx=0)

    # Working loop
    while running:

        # Trigger screenmanager working loop
        screenmanager.do_work()

        for event in keyboard.get_events():
            last_added = time.monotonic()

            if event.code in KEYCODE.KEY_NUM.keys():
                LOG.DEBUG(_LOG_NAME, "Numeric key event: %i" % KEYCODE.KEY_NUM.get(event.code))

                num_array.append(KEYCODE.KEY_NUM.get(event.code))

                # Two digit for numbers from 0 -> 99
                if len(num_array) > 2:
                    num_array.pop(0)
            else:

                # Non numeric key, clear numeric num_array
                num_array.clear()

                if event.code == KEYCODE.KEY_RIGHT:
                    screenmanager.on_action(Action.SWITCH_NEXT)

                elif event.code == KEYCODE.KEY_LEFT:
                    screenmanager.on_action(Action.SWITCH_PREV)

                elif event.code == KEYCODE.KEY_UP:
                    screenmanager.on_action(Action.SWITCH_QUALITY_UP)

                elif event.code == KEYCODE.KEY_DOWN:
                    screenmanager.on_action(Action.SWITCH_QUALITY_DOWN)

                elif event.code == KEYCODE.KEY_ENTER or event.code == KEYCODE.KEY_KPENTER:
                    screenmanager.on_action(Action.SWITCH_SINGLE, 0)

                elif event.code == KEYCODE.KEY_ESC or event.code == KEYCODE.KEY_EXIT:
                    screenmanager.on_action(Action.SWITCH_GRID)

                elif event.code == KEYCODE.KEY_SPACE:
                    screenmanager.on_action(Action.SWITCH_PAUSE_UNPAUSE)

                elif event.code == KEYCODE.KEY_D:
                    screenmanager.on_action(Action.SWITCH_DISPLAY_CONTROL)

                elif event.code == KEYCODE.KEY_Q and not ignore_quit:
                    running = False

                break

        # Timeout between key presses expired?
        if time.monotonic() > (last_added + (CONSTANTS.KEY_TIMEOUT_MS / 1000)):
            num_array.clear()

        # 1 second delay to accept multiple digit numbers
        elif time.monotonic() > (last_added + (CONSTANTS.KEY_MULTIDIGIT_MS / 1000)) and len(num_array) > 0:

            LOG.INFO(_LOG_NAME, "Process numeric key input '%s'" % str(num_array))

            number = 0
            number += num_array[-2] * 10 if len(num_array) > 1 else 0
            number += num_array[-1]

            if number == 0:
                num_array.clear()
                screenmanager.on_action(Action.SWITCH_GRID)
            else:
                num_array.clear()
                screenmanager.on_action(Action.SWITCH_SINGLE, number - 1)

        time.sleep(0.1)

    # Cleanup stuff before exit
    keyboard.destroy()
    BackGroundManager.destroy()
    utils.kill_service('omxplayer.bin', force=True)
    utils.kill_service('vlc', force=True)
    utils.kill_service('pipng', force=True)

    LOG.INFO(_LOG_NAME, "Exiting raspberry pi camplayer, have a nice day!")
    sys.exit(0)
Exemplo n.º 22
0
class TableManager(object):
    def __init__(self, stdscreen, userpass):
        self.username = userpass['user']
        self.password = userpass['pass']
        self.screen = stdscreen
        self.dimensions = self.screen.getmaxyx() 
        self.screen_manager = ScreenManager(self.screen)

    def listTables(self, dbname):
        table_query = "SELECT table_name FROM information_schema.tables where table_schema = 'public'"
        rows = query.query(table_query, dbname, self.screen, None, None, self.username, self.password)
        parsed_table_menu = []
        for datas in rows[1]:
            opts = {'table':str(datas[0]), 'db':dbname}
            lst = (str(datas[0]), self.showTable, opts)
            parsed_table_menu.append(tuple(lst))
        headeropts = {'db':dbname,'title':"Select Table to Display",'user':self.username}
        table_menu = Menu(parsed_table_menu,self.screen, headeropts)
        table_menu.display()
    
    def showTable(self, options):
        table = options['table']
        db = options['db']
        display_query = "SELECT * from " + table
        rows = query.query(display_query, db, self.screen, None, None, self.username, self.password)
        tableDisplay.navigate(rows,0,0,self.screen)
        self.screen.clear()

    def createTable(self, dbname):
        self.screen_manager.set_cursor_visible()
        curses.echo()
        self.screen_manager.display_mid("Please enter a name for the new table: ")
        new_table_name = self.screen_manager.screen.getstr()
        self.screen.clear()
        
        table_creation_query = "CREATE TABLE IF NOT EXISTS " + new_table_name + "(ID INT PRIMARY KEY      NOT NULL);" 
        if query.query(table_creation_query, dbname, self.screen, 0, None, self.username, self.password) == -1:
            ScreenManager.throw(self.screen, "An error prevented table creation.")
        else:
            self.screen_manager.display_mid("Table successfully created!")
            self.screen_manager.screen.getstr()
        self.screen.clear()

    def drop_table(self, options):
        table = options['table']
        db = options['db'] 
        self.screen_manager.display_mid("Are you sure you want to delete "+ table + "? (y/n)")
        confirmation = self.screen_manager.screen.getstr()
        if confirmation == 'y' or confirmation == "Y":
            tbl_delete_query = "DROP TABLE " + table + " CASCADE"
            if query.query(tbl_delete_query, db, self.screen, 0) == -1:
                self.screen_manager.display_mid("ERROR deleting table")
                self.screen.getch()
                self.screen.clear()
            else:
                self.screen_manager.display_mid("Table " + table + " deleted.")
                self.screen.getch()
                self.screen.clear()
        else:
            self.screen_manager.display_mid("Table " + table + " will not be deleted.")
            self.screen.getch()
            self.screen.clear()
        self.screen.clear()


    def list_drop_tables(self, dbname):
        table_query = "SELECT table_name FROM information_schema.tables where table_schema = 'public'"
        rows = query.query(table_query, dbname, self.screen, None, None, self.username, self.password)
        parsed_table_menu = []
        for datas in rows[1]:
            opts = {'db':dbname,'table':str(datas[0])}
            lst = (str(datas[0]),self.drop_table, opts)
            parsed_table_menu.append(tuple(lst))
        headeropts = {'db':dbname,'title':"Select Table to Drop",'user':self.username}
        table_menu = Menu(parsed_table_menu,self.screen, headeropts)
        table_menu.display()
Exemplo n.º 23
0
    def __init__(self, stdscreen, userpass):
        self.screen = stdscreen
        self.username = userpass['user']
        self.password = userpass['pass']
        self.database_manager = DatabaseManager(self.screen, userpass)
        self.screen_manager = ScreenManager(self.screen)
        self.table_manager = TableManager(self.screen, userpass)
        self.query_manager = queryDB(self.screen, userpass)
        headeroptions = {'user': self.username}

        #I ran into an error here when trying to set cursur to invisible
        #this if/try makes sure that both the version of curses and the
        #terminal support this functionality
        if hasattr(curses, 'curs_set'):
            try:
                curses.curs_set(0)
            except:
                pass
        importer = impexp(self.screen, userpass)
        data_items = [
            ('Import', self.database_manager.display_all_databases_opt,
             importer.list_sql_files),
            ('Export', self.database_manager.display_all_databases_opt,
             importer.export)
        ]
        data = Menu(data_items, self.screen, headeroptions)

        browse_database_items = [
            ('List Databases', self.database_manager.display_all_databases),
            ('Create', self.database_manager.create_new_database),
            ('Copy', self.database_manager.display_all_copy_database),
            ('Drop', self.database_manager.display_all_delete_database)
        ]
        browse_database = Menu(browse_database_items, self.screen,
                               headeroptions)

        browse_table_items = [
            ('List Tables', self.database_manager.display_all_databases_opt,
             self.table_manager.listTables),
            ('Create', self.database_manager.display_all_databases_opt,
             self.table_manager.createTable),
            ('Delete', self.database_manager.display_all_databases_opt,
             self.table_manager.list_drop_tables)
        ]
        browse_table = Menu(browse_table_items, self.screen, headeroptions)

        query_items = [
            ('Enter A Query', self.database_manager.display_all_databases_opt,
             self.query_manager.do), ('Save A Query', self.query_manager.save),
            ('View Past Queries',
             self.database_manager.display_all_databases_opt,
             self.query_manager.get_history),
            ('View Saved Queries',
             self.database_manager.display_all_databases_opt,
             self.query_manager.get_saved)
        ]
        query = Menu(query_items, self.screen, headeroptions)

        main_menu_items = [('Data Management', data.display),
                           ('Browse Databases', browse_database.display),
                           ('Browse Tables', browse_table.display),
                           ('Query', query.display)]

        main_menu = Menu(main_menu_items, self.screen, headeroptions)

        main_menu.display()
Exemplo n.º 24
0
class TableManager(object):
    def __init__(self, stdscreen, userpass):
        self.username = userpass['user']
        self.password = userpass['pass']
        self.screen = stdscreen
        self.dimensions = self.screen.getmaxyx()
        self.screen_manager = ScreenManager(self.screen)

    def listTables(self, dbname):
        table_query = "SELECT table_name FROM information_schema.tables where table_schema = 'public'"
        rows = query.query(table_query, dbname, self.screen, None, None,
                           self.username, self.password)
        parsed_table_menu = []
        for datas in rows[1]:
            opts = {'table': str(datas[0]), 'db': dbname}
            lst = (str(datas[0]), self.showTable, opts)
            parsed_table_menu.append(tuple(lst))
        headeropts = {
            'db': dbname,
            'title': "Select Table to Display",
            'user': self.username
        }
        table_menu = Menu(parsed_table_menu, self.screen, headeropts)
        table_menu.display()

    def showTable(self, options):
        table = options['table']
        db = options['db']
        display_query = "SELECT * from " + table
        rows = query.query(display_query, db, self.screen, None, None,
                           self.username, self.password)
        tableDisplay.navigate(rows, 0, 0, self.screen)
        self.screen.clear()

    def createTable(self, dbname):
        self.screen_manager.set_cursor_visible()
        curses.echo()
        self.screen_manager.display_mid(
            "Please enter a name for the new table: ")
        new_table_name = self.screen_manager.screen.getstr()
        self.screen.clear()

        table_creation_query = "CREATE TABLE IF NOT EXISTS " + new_table_name + "(ID INT PRIMARY KEY      NOT NULL);"
        if query.query(table_creation_query, dbname, self.screen, 0, None,
                       self.username, self.password) == -1:
            ScreenManager.throw(self.screen,
                                "An error prevented table creation.")
        else:
            self.screen_manager.display_mid("Table successfully created!")
            self.screen_manager.screen.getstr()
        self.screen.clear()

    def drop_table(self, options):
        table = options['table']
        db = options['db']
        self.screen_manager.display_mid("Are you sure you want to delete " +
                                        table + "? (y/n)")
        confirmation = self.screen_manager.screen.getstr()
        if confirmation == 'y' or confirmation == "Y":
            tbl_delete_query = "DROP TABLE " + table + " CASCADE"
            if query.query(tbl_delete_query, db, self.screen, 0) == -1:
                self.screen_manager.display_mid("ERROR deleting table")
                self.screen.getch()
                self.screen.clear()
            else:
                self.screen_manager.display_mid("Table " + table + " deleted.")
                self.screen.getch()
                self.screen.clear()
        else:
            self.screen_manager.display_mid("Table " + table +
                                            " will not be deleted.")
            self.screen.getch()
            self.screen.clear()
        self.screen.clear()

    def list_drop_tables(self, dbname):
        table_query = "SELECT table_name FROM information_schema.tables where table_schema = 'public'"
        rows = query.query(table_query, dbname, self.screen, None, None,
                           self.username, self.password)
        parsed_table_menu = []
        for datas in rows[1]:
            opts = {'db': dbname, 'table': str(datas[0])}
            lst = (str(datas[0]), self.drop_table, opts)
            parsed_table_menu.append(tuple(lst))
        headeropts = {
            'db': dbname,
            'title': "Select Table to Drop",
            'user': self.username
        }
        table_menu = Menu(parsed_table_menu, self.screen, headeropts)
        table_menu.display()
Exemplo n.º 25
0
from animationAggregator import aggregateAnim
from displayableElement import DisplayableElement
from inputManager import processInputs
from screenmanager import ScreenManager
from textElement import TextElement

from room import Room
from player import Player
from backwall import BackWall
from diedmenu import DiedMenu

pygame.init()
pygame.font.init()
# Vars
size = width, height = 1024, 576
SM = ScreenManager(size)
clock = pygame.time.Clock()
time = 180
roomNumber = 0
floorNumber = 1
#roomNumber = 0
#floorNumber = 1
pygame.key.set_repeat(1, 200)
# Music
pygame.mixer.music.load("music.wav")
pygame.mixer.music.set_volume(0.1)

gameObjects = []
for x in range(16):
    for y in range(9):
        gameObjects.append(BackWall((x, y)))
Exemplo n.º 26
0
 def __init__(self, stdscreen, userpass):
     self.username = userpass['user']
     self.password = userpass['pass']
     self.screen = stdscreen
     self.dimensions = self.screen.getmaxyx()
     self.screen_manager = ScreenManager(self.screen)
Exemplo n.º 27
0
class LoginScreen:       
    def __init__(self):
        self.username = '' #username we will store from the user input
        self.password = ''
        self.screen = curses.initscr()
        self.screen_manager = ScreenManager(self.screen)
    #recursive function used to select either create account or login
    def selector(self, location):
        self.screen.keypad(1)
        dimensions = self.screen.getmaxyx()
        self.screen.clear()
        message = "Select Using ->, <-, and Enter:"
        self.screen.addstr(dimensions[0]/3, dimensions[1]/2 - len(message)/2, message)
        if(location):
            message = 'Login'
            self.screen.addstr(dimensions[0]/2, dimensions[1]/3 - len(message)/2, message, curses.A_DIM)
            message = 'Create User'
            self.screen.addstr(dimensions[0]/2, 2 * dimensions[1]/3 - len(message)/2, message, curses.A_STANDOUT)  
            self.screen.refresh()
        else:
            message = 'Login'
            self.screen.addstr(dimensions[0]/2, dimensions[1]/3 - len(message)/2, message, curses.A_STANDOUT)
            message = 'Create User'
            self.screen.addstr(dimensions[0]/2, 2 * dimensions[1]/3 - len(message)/2, message, curses.A_DIM)  
            self.screen.refresh()         
    
        choice = self.screen.getch()
        if choice == ord('\n'):
            return location
        elif choice == curses.KEY_LEFT:
            return LoginScreen.selector(self, 0)
        elif choice == curses.KEY_RIGHT:
            return LoginScreen.selector(self, 1)
        else:
            return LoginScreen.selector(self, location)         

    #function used to insert a new user into the databse:
    def create_user(self):
        self.screen_manager.display_mid('Please enter your desired Username: '******'Please enter your desired Password: '******'%s\'" % self.username
        rows = query.query(to_query, 'postgres', self.screen)
        
        if rows[1]:
            ScreenManager.throw(self.screen, 'Username already in use.')
            return LoginScreen.create_user(self)
        else:
            to_query = "CREATE USER %s WITH CREATEDB PASSWORD \'%s\'" % (self.username, self.password)
            if query.query(to_query, 'postgres', self.screen) == -1:
                ScreenManager.throw(self.screen, "An error prevented user creation.")
                return False
            to_query = "CREATE DATABASE %s_default" % (self.username)
            if query.query(to_query, 'postgres', self.screen, 0) == -1:
                ScreenManager.throw(self.screen, "An error occured during user default database creation.")
                return False
            to_query = "ALTER DATABASE %s_default owner to %s" % (self.username, self.username)
            if query.query(to_query, 'postgres', self.screen) == -1:
                ScreenManager.throw(self.screen, "An error occured while assigning new user to default database.")
                return False

            return True

    def login(self):
        self.screen_manager.display_mid('Please enter your Username: '******'Please enter your Password: '******'root\'"
        rows = query.query(to_query, 'postgres', None, None, None, self.username, self.password)
        
        if rows != -1 and rows != -2:
            return True
        elif rows == -1:
            ScreenManager.throw(self.screen, "Couldn't sign in. Please ensure your system is set up correctly.")
            return False
        else:
            ScreenManager.throw(self.screen, "Incorrect Username or Password.")
            return False

    #function that prints a flowing welcome message
    def welcome(self):
        anim = Animators()
        anim.enter_down(self.screen, "Welcome!")
        time.sleep(.25)
        anim.exit_up(self.screen, "Welcome!")
        self.screen.clear()
Exemplo n.º 28
0
 def __init__(self):
     self.username = '' #username we will store from the user input
     self.password = ''
     self.screen = curses.initscr()
     self.screen_manager = ScreenManager(self.screen)