The WCK HexView Widget

September 7, 2003 | Fredrik Lundh

 

This class implements a simple “hexdump” viewer, based on the ListView classes introduced in the Displaying Large Amounts of Data article.

File: wckHexView.py
from ListView import ListView

import re

##
# Model class

class HexModel:
    # turns a file into a list of (offset, 16-byte chunk) items

    def __init__(self, file):
        self.file = open(file, "rb")
        self.file.seek(0, 2) # seek to end of file
        self.size = self.file.tell()

    def __getitem__(self, index):
        offset = index * 16
        self.file.seek(offset)
        return offset, self.file.read(16)

    def __len__(self):
        return (self.size + 15) / 16

##
# View class

class HexView(ListView):
    # simple viewer

    ui_option_width = 8 + 1 + 16*3 + 16

    ui_option_font = "courier"

    def repair_item(self, draw, xy, item):
        offset, data = item
        # build hexdump string
        text = ["%08x" % offset]
        for char in data:
            text.append("%02x" % ord(char))
        if len(text) < 17:
            text.extend(["  "]*(17-len(text)))
        text.append(re.sub("[\x00-\x1f\x7f-\xbf]", ".", data))
        draw.text(xy, " ".join(text), self.font)

Here’s how to use this class:

from Tkinter import *

root = Tk()
root.title("WCK")

scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = HexView(root, yscrollcommand=scrollbar.set)
listbox.pack(expand=1, fill=BOTH)

scrollbar.config(command=listbox.yview)

model = HexModel("bigfile.dat")

listbox.setdata(model)

mainloop()

Note that the file must be wrapped in a HexModel class; you can create your own model class if you want to dump data from other sources.

Notes

To simplify usage, you could add a setfile helper method to the HexView class:

    def setfile(self, file):
        self.setdata(HexModel(file))

Alternatively, you can override and extend the ui_handle_config method to add support for a file option. Don’t forget to call the ui_handle_config implementation in the parent class before returning control to the WCK.

For a more extensive hex viewer/editor widget, see Michael Peuser’s wckhex (dead link) widget class.

 

A Django site. rendered by a django application. hosted by webfaction.