How can I support other file formats

By default, the HTML window can handle files with the MIME type text/html, text/txt, and image/* (assuming the wxPython image handlers are loaded). When confronted with a file that is not an image or HTML file, the HTML window attempts to display it as plain text. That may not be the behavior you want. If there is some file format that you want displayed in a custom way, you can create a wx.html.HtmlFilter to manage it. For example, you might want XML files to display as a source tree, or you could display Python source files with syntax coloring.

To create a filter, you must build a subclass of wx.html.HtmlFilter. This class has two methods, and you must override both of them. The first method is Can-Read(file). The file parameter is an instance of wx.FSFile—the wxPython representation of an opened file. The wx.FSFile class has two properties that you would use to determine if your filter can read the file. The method GetMimeType() returns the file's MIME type as a string. The mime type is usually determined by the file's extension. The method GetLocation() returns a string with the absolute path or URL to the file location. The CanRead() method should return True if the filter will handle the file, otherwise it returns False. A sample CanRead() to handle Python source files may look like the following.

CanRead(self, file):

return file.GetLocation().endswith('.py')

The second method you need to override is ReadFile(file). This method takes in the same file parameter, and returns a string HTML representation of the file's contents. If you don't want to use the wxWidgets C + + file mechanisms to read the file, you can use the Python file mechanisms by simply opening a Python file at file.GetLocation().

Once the filter has been created, it must be registered with the wx.html.Html-Window using the window's AddFilter(filter) static method. The filter parameter is an instance of your new wx.html.HtmlFilter class. Once it has registered the filter, the window uses it to manage the file objects that pass the CanRead() test.

Was this article helpful?

0 0

Post a comment