Example #1
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self,
                        bd=0,
                        highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=NW)
        self.canv = canvas  # @UndefinedVariable
        self.scroller = vscrollbar

        def _configure_interior(event):
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.config(width=interior.winfo_reqwidth())

        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())

        canvas.bind('<Configure>', _configure_canvas)
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(
            self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=NW)
        self.canv = canvas  # @UndefinedVariable
        self.scroller = vscrollbar

        def _configure_interior(event):
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)
Example #3
0
class MapRenderer:
    def __init__(self, config=config, **kwargs):
        self.config = config
        self.__dict__.update(kwargs)
        self.map = Map(**kwargs)

    @property
    def canvas_width(self):
        return self.map.width * self.map.block_width

    @property
    def canvas_height(self):
        return self.map.height * self.map.block_height

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if hasattr(self, 'canvas'):
            pass
        else:
            self.canvas = Canvas(parent)
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def draw(self):
        self.canvas.configure(width=self.canvas_width, height=self.canvas_height)
        for i in xrange(len(self.map.blockdata)):
            block_x = i % self.map.width
            block_y = i / self.map.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.map.blockdata[block_y * self.map.width + block_x]

        # Ignore nonexistent blocks.
        if block >= len(self.map.tileset.blocks): return

        for j, tile in enumerate(self.map.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * self.map.block_width + (j % 4) * 8
                tile_y = block_y * self.map.block_height + (j / 4) * 8
                self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile])
            except:
                pass

    def crop(self, *args, **kwargs):
        self.map.crop(*args, **kwargs)
        self.draw()
class MapRenderer:
    def __init__(self, config=config, **kwargs):
        self.config = config
        self.__dict__.update(kwargs)
        self.map = Map(**kwargs)

    @property
    def canvas_width(self):
        return self.map.width * self.map.block_width

    @property
    def canvas_height(self):
        return self.map.height * self.map.block_height

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if hasattr(self, 'canvas'):
            pass
        else:
            self.canvas = Canvas(parent)
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def draw(self):
        self.canvas.configure(width=self.canvas_width, height=self.canvas_height)
        for i in xrange(len(self.map.blockdata)):
            block_x = i % self.map.width
            block_y = i / self.map.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.map.blockdata[block_y * self.map.width + block_x]

        # Ignore nonexistent blocks.
        if block >= len(self.map.tileset.blocks): return

        for j, tile in enumerate(self.map.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * self.map.block_width + (j % 4) * 8
                tile_y = block_y * self.map.block_height + (j / 4) * 8
                self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile])
            except:
                pass

    def crop(self, *args, **kwargs):
        self.map.crop(*args, **kwargs)
        self.draw()
Example #5
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=Tkinter.VERTICAL)
        vscrollbar.pack(fill=Tkinter.Y,
                        side=Tkinter.RIGHT,
                        expand=Tkinter.FALSE)

        hscrollbar = Scrollbar(self, orient=Tkinter.HORIZONTAL)
        hscrollbar.pack(fill=Tkinter.X,
                        side=Tkinter.BOTTOM,
                        expand=Tkinter.FALSE)

        canvas = Canvas(self,
                        bd=0,
                        highlightthickness=0,
                        yscrollcommand=vscrollbar.set,
                        xscrollcommand=hscrollbar.set)
        canvas.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=Tkinter.TRUE)
        vscrollbar.config(command=canvas.yview)
        hscrollbar.config(command=canvas.xview)

        # reset the view

        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it

        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0,
                                           0,
                                           window=interior,
                                           anchor=Tkinter.NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar

        def _configure_interior(event):
            '''
            update the scrollbars to match the size of the inner frame
            '''
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion='0 0 %s %s' % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())

        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            '''
            _configure_canvas is used to resize the window size to fit content.
            Can be used when changing window.
            '''

            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
Example #6
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)
        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event=None):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event=None):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)
Example #7
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=Tkinter.VERTICAL)
        vscrollbar.pack(fill=Tkinter.Y, side=Tkinter.RIGHT, expand=Tkinter.FALSE)

        hscrollbar = Scrollbar(self, orient=Tkinter.HORIZONTAL)
        hscrollbar.pack(fill=Tkinter.X, side=Tkinter.BOTTOM, expand=Tkinter.FALSE)

        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set)
        canvas.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=Tkinter.TRUE)
        vscrollbar.config(command=canvas.yview)
        hscrollbar.config(command=canvas.xview)


        # reset the view

        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it

        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=Tkinter.NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar

        def _configure_interior(event):

            '''
            update the scrollbars to match the size of the inner frame
            '''
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion='0 0 %s %s' % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):

            '''
            _configure_canvas is used to resize the window size to fit content.
            Can be used when changing window.
            '''

            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
Example #8
0
class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!

    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling
    
    """
    def _configure_interior(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.interior.winfo_reqwidth(),
                self.interior.winfo_reqheight())
        self.canvas.config(scrollregion="0 0 %s %s" % size)
        if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canvas.config(width=self.interior.winfo_reqwidth())
        self.interior.bind('<Configure>', _configure_interior)

    def _configure_canvas(self, event):
        if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
            # update the inner frame's width to fill the canvas
            self.canvas.itemconfigure(self.interior_id,
                                      width=self.canvas.winfo_width())
        self.canvas.bind('<Configure>', _configure_canvas)
        return

    def configure_scrolling(self):
        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient='vertical')
        vscrollbar.grid(row=0, column=1, sticky='nsw')
        self.canvas = Canvas(self,
                             bd=0,
                             highlightthickness=0,
                             yscrollcommand=vscrollbar.set)
        self.canvas.grid(row=0, column=0, sticky='nsew')
        vscrollbar.config(command=self.canvas.yview)

        # reset the view
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(self.canvas)
        self.interior.grid(row=0, column=0, sticky='nsew')
        self.interior_id = self.canvas.create_window(0,
                                                     0,
                                                     window=interior,
                                                     anchor='nw')
Example #9
0
class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!

    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling
    
    """
    def _configure_interior(self,event):
        # update the scrollbars to match the size of the inner frame
        size = (self.interior.winfo_reqwidth(), self.interior.winfo_reqheight())
        self.canvas.config(scrollregion="0 0 %s %s" % size)
        if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canvas.config(width=self.interior.winfo_reqwidth())
        self.interior.bind('<Configure>', _configure_interior)

    def _configure_canvas(self,event):
        if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
            # update the inner frame's width to fill the canvas
            self.canvas.itemconfigure(self.interior_id, width=self.canvas.winfo_width())
        self.canvas.bind('<Configure>', _configure_canvas)
        return

    def configure_scrolling(self):
        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient='vertical')
        vscrollbar.grid(row=0,column=1,sticky='nsw')
        self.canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        self.canvas.grid(row=0,column=0,sticky='nsew')
        vscrollbar.config(command=self.canvas.yview)

        # reset the view
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(self.canvas)
        self.interior.grid(row=0,column=0,sticky='nsew')
        self.interior_id = self.canvas.create_window(0, 0, window=interior,
                                           anchor='nw')
Example #10
0
class TutorWindow( Toplevel ):
    """
    Window for displaying a basic help
    """
    labels      = {}            # Dictionary for keeping clickable labels
    size_x      = 600           # horizontal size of canvas
    size_y      = 800           # vertical size of canvas
    last_images = []            # handle on images currently on the canvas
    images      = []            # new images to go on the canvas
    curr_key    = None          # Current key that is looked at
    
    # Names of label links and list of pictures to load. These pictures are generated from a pdf by save as, type .png
    help_dict = { "Get Pictures"    : [ "Get_Pictures_Page_1.png" , "Get_Pictures_Page_2.png" , "Get_Pictures_Page_3.png"  ],
                  "Save Pictures"   : [ "Save_Pictures_Page_1.png", "Save_Pictures_Page_2.png", "Save_Pictures_Page_3.png" ],
                  "Pictures Effects": [ "Pic_Effects_Page_1.png"  , "Pic_Effects_Page_2.png"                               ],
                  "Options"         : [ "Options.png"                                                                      ],
                }

    def __init__( self ):
        """
        Initialize window settings
        """
        
        Toplevel.__init__( self )
        self.title( "Tutorial" )
        self.iconbitmap( ICON_FILENAME )
        self.geometry( "+100+50" )
        
        # init frames for window. This window contains complicated frames. i.e. frames with frames inside them.
        fr11 = Frame( self )
        fr1  = Frame( fr11 )
        fr2  = Frame( fr11 )
        fr3  = Frame( self )
        
        # create labels links for displaying different help information
        for name in self.help_dict:
            self.labels[ name ] = Label( fr1, text=name, fg="blue" ) 
            self.labels[ name ].bind( "<ButtonPress-1>", lambda e, arg=name: self.HandleLB( e, arg ) )
            self.labels[ name ].pack( fill=X )
        fr1.pack( side=LEFT )
        
        # create/configure canvas and scrollbar for displaying help pictures
        self.canv = Canvas( fr2, width=self.size_x, height=self.size_y, scrollregion=( 0, 0, 300, 0 ) )
        self.sbar = Scrollbar( fr2 )
        self.sbar.config( command=self.canv.yview )
        self.canv.config( yscrollcommand=self.sbar.set )
        self.canv.focus_set()
        self.sbar.pack( side=RIGHT, fill=Y )
        self.canv.pack( side=LEFT, fill=Y )

        fr2.pack( side=LEFT )
        fr11.pack()
    
        # create ok button for closing the window
        btn = Button( fr3, text="Ok", width=10, command=self.quit )
        btn.pack( side=LEFT )
        fr3.pack()
        
        self.mainloop()
        self.destroy()
        
    def HandleLB( self, event, key ):
        """
        handle clicking a label link
        """
        
        if( key != self.curr_key ):
        
        
            # reset the position of the scrollbar to the top
            self.canv.yview_moveto( 0.0 )

            # load new images
            print "Key: ", key
            self.LoadImages( key )
            
            # change formatting on labels, color red for current one clicked
            self.FormatLabels( key )
            
            # remove old pictures from the canvas before adding new ones
            if( len( self.last_images ) != 0 ):
                for image in self.last_images:
                    self.canv.delete( image )
            self.last_images = []
    
            # There's an offset required in order to show everything correctly, don't know why...
            image_y = 390
    
            # change scrollable area for the canvas to be exact size of all pictures
            self.canv.config( scrollregion=( 0, 0, 300, 776*len( self.images ) ) )
            
            # add new pictures to canvas stacking them on top of each other and making them seamless
            for i in range( len( self.images ) ):
                self.last_images.append( self.canv.create_image( ( self.size_x/2, image_y ), image=self.images[ i ] ) )
                image_y += self.images[ i ].height()
                
            self.curr_key = key
            
    def LoadImages( self, key ):
        """
        load new inmages into class storage
        """
        self.images = []
        print "help_dict: ", self.help_dict        
        # get images from hardcoded array
        for image in self.help_dict[ key ]:
            
            # open PIL image
            print "image: ", path.join( HELP_DIR, image )

            image1 = PILopen( path.join( HELP_DIR, image ) )
    
            # resize to fit canvas area
            image1 = image1.resize( ( self.size_x , self.size_y ), ANTIALIAS )
            
            # make into a tkimage
            im = PhotoImage( image1 )
             
            # add to list of images to display 
            self.images.append( im )
    
    def FormatLabels( self, key ):
        for name in self.labels:
            self.labels[ name ].config( fg="blue" )
            
        self.labels[ key ].config( fg="red" )
Example #11
0
class Map:
    def __init__(self,
                 parent,
                 name=None,
                 width=20,
                 height=20,
                 tileset_id=2,
                 blockdata_filename=None,
                 config=config):
        self.parent = parent

        self.name = name

        self.config = config
        self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__,
                                                      id(self)))

        self.blockdata_filename = blockdata_filename
        if not self.blockdata_filename and self.name:
            self.blockdata_filename = os.path.join(self.config.map_dir,
                                                   self.name + '.blk')
        elif not self.blockdata_filename:
            self.blockdata_filename = ''

        asm_filename = ''
        if self.name:
            if self.config.asm_dir is not None:
                asm_filename = os.path.join(self.config.asm_dir,
                                            self.name + '.asm')
            elif self.config.asm_path is not None:
                asm_filename = self.config.asm_path

        if os.path.exists(asm_filename):
            for props in [
                    map_header(self.name, config=self.config),
                    second_map_header(self.name, config=self.config)
            ]:
                self.__dict__.update(props)
            self.asm = open(asm_filename, 'r').read()
            self.events = event_header(self.asm, self.name)
            self.scripts = script_header(self.asm, self.name)

            self.tileset_id = eval(self.tileset_id, self.config.constants)

            self.width = eval(self.width, self.config.constants)
            self.height = eval(self.height, self.config.constants)

        else:
            self.width = width
            self.height = height
            self.tileset_id = tileset_id

        if self.blockdata_filename:
            self.blockdata = bytearray(
                open(self.blockdata_filename, 'rb').read())
        else:
            self.blockdata = []

        self.tileset = Tileset(self.tileset_id, config=self.config)

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if not hasattr(self, 'canvas'):
            self.canvas_width = self.width * 32
            self.canvas_height = self.height * 32
            self.canvas = Canvas(parent,
                                 width=self.canvas_width,
                                 height=self.canvas_height)
            self.canvas.xview_moveto(0)
            self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def crop(self, x1, y1, x2, y2):
        blockdata = self.blockdata
        start = y1 * self.width + x1
        width = x2 - x1
        height = y2 - y1
        self.blockdata = []
        for y in xrange(height):
            for x in xrange(width):
                self.blockdata += [blockdata[start + y * self.width + x]]
        self.blockdata = bytearray(self.blockdata)
        self.width = width
        self.height = height

    def draw(self):
        for i in xrange(len(self.blockdata)):
            block_x = i % self.width
            block_y = i / self.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.blockdata[block_y * self.width + block_x]
        for j, tile in enumerate(self.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * 32 + (j % 4) * 8
                tile_y = block_y * 32 + (j / 4) * 8
                self.canvas.create_image(index + tile_x,
                                         indey + tile_y,
                                         image=self.tileset.tiles[tile])
            except:
                pass
    def on_show_frame(self):
        self.canvas_wrappers = []
        self.canvases = []
        self.page_num = 0

        if len(self.controller.sr_results) == 0:
            self.controller.show_frame(SrNoFramesFoundScreen)
        else:
            pages = int(ceil(len(self.controller.sr_results) / 10.0))
            for page in range(0, pages):
                canvas_wrapper = Frame(self.content_wrapper,
                                       borderwidth="1",
                                       relief="solid")
                canvas = Canvas(canvas_wrapper,
                                width=int(WINDOW_WIDTH * 7 / 8),
                                height=(WINDOW_HEIGHT * 2 / 3))
                scroll_bar = Scrollbar(canvas_wrapper,
                                       orient=VERTICAL,
                                       command=canvas.yview)
                results_list_frame = Frame(canvas)

                canvas.configure(yscrollcommand=scroll_bar.set)
                canvas.create_window(0, 0, window=results_list_frame)
                canvas.bind_all("<Up>", self.on_up_key)
                canvas.bind_all("<Down>", self.on_down_key)
                canvas.bind_all("<Left>", self.on_left_key)
                canvas.bind_all("<Right>", self.on_right_key)

                canvas.grid(row=0, column=0, sticky="nsew")
                scroll_bar.grid(row=0, column=1, sticky="ns")
                canvas_wrapper.grid(row=2,
                                    column=0,
                                    columnspan=3,
                                    sticky="nsew")

                select_buttons_on_page = []

                for row in range(0, RESULTS_PER_PAGE):
                    result_num = page * RESULTS_PER_PAGE + row
                    if result_num < len(self.controller.sr_results):
                        frame_num = self.controller.sr_results[result_num][
                            FRAME_NUM_LABEL]

                        result_entry = Frame(results_list_frame,
                                             borderwidth="1",
                                             relief="solid")
                        description = PLabel(
                            result_entry,
                            text="Frame #" + str(int(frame_num)) + ", Time: " +
                            str(datetime.timedelta(seconds=frame_num / 30)))
                        preview_wrapper = Frame(result_entry)
                        left_video_preview = Label(
                            preview_wrapper,
                            image=self.controller.sr_results[result_num][LEFT])
                        right_video_preview = Label(
                            preview_wrapper,
                            image=self.controller.sr_results[result_num]
                            [RIGHT])
                        select_button = SrSelectButton(
                            preview_wrapper,
                            self.controller,
                            self.controller.sr_results[result_num]
                            [SR_MAP_LABEL],
                            text="Select")

                        select_buttons_on_page.append(select_button)

                        description.pack()
                        left_video_preview.grid(row=row, column=0)
                        right_video_preview.grid(row=row, column=1)
                        select_button.grid(row=row, column=2)
                        preview_wrapper.pack()
                        result_entry.pack()

                for i in range(0, len(select_buttons_on_page)):
                    select_buttons_on_page[i].configure(
                        command=select_buttons_on_page[i].use_sr_map)

                self.master.update_idletasks()
                canvas.config(scrollregion=canvas.bbox("all"))
                canvas.yview_moveto(0)
                self.canvas_wrappers.append(canvas_wrapper)
                self.canvases.append(canvas)

            self.prev_result_page = Button(
                self.content_wrapper,
                text="<",
                command=lambda: self.prev_page_command())
            self.page_info_label = PLabel(
                self.content_wrapper,
                text=get_page_info_label_message(self.page_num,
                                                 len(self.canvases),
                                                 RESULTS_PER_PAGE))
            self.next_result_page = Button(
                self.content_wrapper,
                text=">",
                command=lambda: self.next_page_command())

            self.prev_result_page.grid(row=3, column=0)
            self.page_info_label.grid(row=3, column=1)
            self.next_result_page.grid(row=3, column=2)
            self.canvas_wrappers[self.page_num].tkraise()
Example #13
0
class TrailUI:
    def __init__(self, parent, trail=None):
        self.parent = parent
        self.trail = trail
        self.alpha_reflection = trail.alpha_reflection
        self.states = []
        self.probabilitylabels = {}
        ## scrollbar
        # create a canvas object and a vertical scrollbar for scrolling it
        self.scrollframe = Frame(parent)
        self.hsb = Scrollbar(self.scrollframe, orient=Tkinter.HORIZONTAL)
        self.hsb.pack(fill=Tkinter.X, side=BOTTOM, expand=Tkinter.FALSE)
        self.scrollcanvas = Canvas(self.scrollframe,
                                   bd=0,
                                   highlightthickness=0,
                                   xscrollcommand=self.hsb.set)
        self.scrollcanvas.pack(side=LEFT, fill=BOTH, expand=Tkinter.TRUE)
        self.hsb.config(command=self.scrollcanvas.xview)

        # reset the view
        self.scrollcanvas.xview_moveto(0)
        self.scrollcanvas.yview_moveto(0)

        # put trailframe into scrollframe and assign configs
        self.trailframe = interior = Frame(self.scrollcanvas)
        self.interior_id = self.scrollcanvas.create_window(10,
                                                           0,
                                                           window=interior,
                                                           anchor=Tkinter.NW)
        interior.bind('<Configure>', self._configure_interior)
        self.scrollcanvas.bind('<Configure>', self._configure_canvas)

        self.scrollframe.pack(fill=Tkinter.X, expand=1)
        self.infoframe = Frame(parent)
        self.infoframe.pack(fill=Tkinter.X, expand=1, side=BOTTOM)
        self.canvas = Canvas(self.infoframe, width=1000, height=200)
        self.canvas.pack()
        self.b = Button(self.infoframe,
                        text='Disable Propagation',
                        command=self.__toggle_prop)
        self.b.pack()
        self.b2 = Button(self.infoframe,
                         text='Make active only',
                         command=self.__activeonly)
        self.b2.pack()
        self.parent.title("ClusterF**k")
        self.enable_propagation = True
        self.trail.updateColorList()
        self.maxgridcol = -1
        self.trail.initUI(self)

        # Multi Cell Selection
        self.multiselection_pressed = False
        self.dynamicselection_pressed = False
        self.selectedcells = []
        self.parent.bind("<Control_L>", self.__selection_start)
        self.parent.bind("<KeyRelease-Control_L>", self.__selection_end)
        self.parent.bind("<Shift_L>", self.__dynamic_selection_start)
        self.parent.bind("<KeyRelease-Shift_L>", self.__dynamic_selection_end)

        self.parent.bind("<Escape>", lambda event: self._clear_selection())
        self.parent.bind("<Return>", lambda event: self.open_cell_dialogue())

    # track changes to the canvas and frame width and sync them,
    # also updating the scrollbar
    # taken from https://gist.github.com/EugeneBakin/76c8f9bcec5b390e45df
    def _configure_interior(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.trailframe.winfo_reqwidth(),
                self.trailframe.winfo_reqheight())
        self.scrollcanvas.config(scrollregion="0 0 %s %s" % size)
        if self.trailframe.winfo_reqwidth() != self.scrollcanvas.winfo_width():
            # update the canvas's width to fit the inner frame
            self.scrollcanvas.config(width=self.trailframe.winfo_reqwidth())

    def _configure_canvas(self, event):
        if self.trailframe.winfo_reqwidth() != self.scrollcanvas.winfo_width():
            # update the inner frame's width to fill the canvas
            self.scrollcanvas.itemconfigure(
                self.trailframe, width=self.scrollcanvas.winfo_width())

    def __selection_start(self, event):
        print "Selection start/continue"
        self.multiselection_pressed = True

    def __dynamic_selection_start(self, event):
        print "Dynamic selection start"
        self.dynamicselection_pressed = True

    def __selection_end(self, event):
        print "Selection end"
        self.multiselection_pressed = False

    def __dynamic_selection_end(self, event):
        print "Dynamic selection end"
        self.dynamicselection_pressed = False

    def open_cell_dialogue(self):
        if len(self.selectedcells) is 0:
            return

        # oldstate = self.__clickedcells[0]["oldstate"]
        # oldstatestr = ",".join(["{:x}".format(x) for x in oldstate])
        oldstatestr = ""

        dialog = StatePopup(
            self, oldstatestr,
            self.selectedcells[0]["state_probs"])  # TODO add probs

        self.trailframe.wait_window(dialog.top)

        newstate = dialog.value
        # set each cell of the selection to the new state
        if newstate is not None:
            for i, cell in enumerate(self.selectedcells):
                cell["stateUI"].state.set(cell["row"], cell["col"],
                                          set(newstate))

        # self._clear_selection()
        self.redraw_all()
        self.redraw_selection()

    def _clear_selection(self):
        for cell in self.selectedcells:
            cell["stateUI"].undraw_selection(cell)

        self.selectedcells = []

    def __toggle_prop(self):
        self.enable_propagation = not self.enable_propagation
        if self.enable_propagation:
            self.b.config(text="Disable Propagation")
            self.redraw_all()
        else:
            self.b.config(text="Enable Propagation")

    def __activeonly(self):
        self.trail.makeActiveOnly()
        self.redraw_all()

    def get_stateui_at(self, row, col):
        # retrieve state from specific grid position
        for state in self.states:
            if state._row is row and state._col is col:
                return state

        return self.get_stateui_at(row, col - 1)

    def redraw_selection(self):
        for cell in self.selectedcells:
            cell["stateUI"].draw_selection(cell)

    def redraw_all(self):
        if self.enable_propagation:
            self.trail.propagate()
            self.trail.getProbability(verbose=True)
        self.redrawColorList()
        self.redraw_states()
        self.redraw_selection()
        if self.enable_propagation:
            self.redraw_probablities()

    def redraw_states(self):
        for state in self.states:
            state.redraw_state()

        if PRINT_PROPS is True:
            for state in self.states:
                state.redraw_propagation()

    def redraw_probablities(self):
        if self.alpha_reflection is True:
            for i, prob in enumerate(self.trail.probabilities):
                overallprob, sboxprob, mixcolprob = prob.getProbability()
                if i < self.trail.rounds:
                    self.probabilitylabels["S" + str(i)].textvar.set(
                        "2^{0:.2f}".format(math.log(sboxprob, 2)))
                    self.probabilitylabels["M" + str(i + 1)].textvar.set(
                        "2^{0:.2f}".format(math.log(mixcolprob, 2)))
                elif i >= self.trail.rounds + 1:
                    self.probabilitylabels["S" + str(i + 2)].textvar.set(
                        "2^{0:.2f}".format(math.log(sboxprob, 2)))
                    self.probabilitylabels["M" + str(i + 1)].textvar.set(
                        "2^{0:.2f}".format(math.log(mixcolprob, 2)))
                else:  # inner round
                    self.probabilitylabels["I"].textvar.set("2^{0:.2f}".format(
                        math.log(overallprob, 2)))
        else:
            for i, prob in enumerate(self.trail.probabilities):
                overallprob, sboxprob, mixcolprob = prob.getProbability()
                self.probabilitylabels["S" + str(i + 1)].textvar.set(
                    "2^{0:.2f}".format(math.log(sboxprob, 2)))
                self.probabilitylabels["M" + str(i + 1)].textvar.set(
                    "2^{0:.2f}".format(math.log(mixcolprob, 2)))

    def redrawColorList(self):
        self.canvas.delete("colorlist")
        self.trail.updateColorList()
        for i, (state, color) in enumerate(self.trail.colorlist.items()):
            statestr = ",".join(["{:x}".format(x) for x in state])
            x = 15 + int(i / 5) * 250
            y = 15 + (i % 5) * 40
            self.canvas.create_rectangle(x,
                                         y,
                                         x + 25,
                                         y + 25,
                                         fill=color,
                                         tags="colorlist")

            textx = x + 40
            texty = y + 12
            self.canvas.create_text(textx,
                                    texty,
                                    text=statestr,
                                    tags="colorlist",
                                    fill="black",
                                    anchor="w")

    def cleanup(self):
        self.infoframe.destroy()
        self.trailframe.destroy()
class Map:
    def __init__(self, parent, name=None, width=20, height=20, tileset_id=2, blockdata_filename=None, config=config):
        self.parent = parent

        self.name = name

        self.config = config
        self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self)))

        self.blockdata_filename = blockdata_filename
        if not self.blockdata_filename and self.name:
            self.blockdata_filename = os.path.join(self.config.map_dir, self.name + '.blk')
        elif not self.blockdata_filename:
            self.blockdata_filename = ''

        asm_filename = ''
        if self.name:
            if self.config.asm_dir is not None:
                asm_filename = os.path.join(self.config.asm_dir, self.name + '.asm')
            elif self.config.asm_path is not None:
                asm_filename = self.config.asm_path

        if os.path.exists(asm_filename):
            for props in [map_header(self.name, config=self.config), second_map_header(self.name, config=self.config)]:
                self.__dict__.update(props)
            self.asm = open(asm_filename, 'r').read()
            self.events = event_header(self.asm, self.name)
            self.scripts = script_header(self.asm, self.name)

            self.tileset_id = eval(self.tileset_id, self.config.constants)

            self.width = eval(self.width, self.config.constants)
            self.height = eval(self.height, self.config.constants)

        else:
            self.width = width
            self.height = height
            self.tileset_id = tileset_id

        if self.blockdata_filename:
            self.blockdata = bytearray(open(self.blockdata_filename, 'rb').read())
        else:
            self.blockdata = []

        self.tileset = Tileset(self.tileset_id, config=self.config)

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if not hasattr(self, 'canvas'):
            self.canvas_width = self.width * 32
            self.canvas_height = self.height * 32
            self.canvas = Canvas(parent, width=self.canvas_width, height=self.canvas_height)
            self.canvas.xview_moveto(0)
            self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def crop(self, x1, y1, x2, y2):
        blockdata = self.blockdata
        start = y1 * self.width + x1
        width = x2 - x1
        height = y2 - y1
        self.blockdata = []
        for y in xrange(height):
            for x in xrange(width):
                self.blockdata += [blockdata[start + y * self.width + x]]
        self.blockdata = bytearray(self.blockdata)
        self.width = width
        self.height = height

    def draw(self):
        for i in xrange(len(self.blockdata)):
            block_x = i % self.width
            block_y = i / self.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.blockdata[block_y * self.width + block_x]
        for j, tile in enumerate(self.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * 32 + (j % 4) * 8
                tile_y = block_y * 32 + (j / 4) * 8
                self.canvas.create_image(index + tile_x, indey + tile_y, image=self.tileset.tiles[tile])
            except:
                pass
Example #15
0
r=Tk() # создаём окно..
r.title(u'Построитель графиков функций')
f=Frame() # фрейм..
c=Canvas(f,width=WW,height=HH,bg='white',scrollregion=(0,0,W,H)) # поверхность..
sX=Scrollbar(r,orient=HORIZONTAL) # скроллбары
sY=Scrollbar(f,orient=VERTICAL)
c['xscrollcommand']=sX.set
c['yscrollcommand']=sY.set
sX['command']=c.xview
sY['command']=c.yview
c.pack(fill=BOTH,side=LEFT,expand='1')
sY.pack(fill=Y,side=RIGHT)
f.pack(expand='1',fill=BOTH)
c.xview_moveto((W/2.0-WW/2.0)/W)
c.yview_moveto((H/2.0-HH/2.0)/H)
sX.pack(fill=X,side=TOP)
form=StringVar()
f=Frame(r)
Label(f,text='y=').pack(side=LEFT) # текстовое поле..
e=Entry(f,textvar=form)
e.pack(fill=X,side=LEFT,expand='1')
noclear=StringVar()
noclear.set('')
Checkbutton(f,onvalue='1',offvalue='',variable=noclear).pack(side=RIGHT)
f.pack(fill=X)
L=[]

# try:import graphmk_f
# except ImportError:print 'wtf'
#----------------------------------------------------------