Volume Number: 16 (2000)
Issue Number: 8
Column Tag: Programming
HTML Rendering with FutureBASIC^3
By Chris Stasny
How to write a simple HTML Browser with FutureBASIC^3
East Meets South
We had been dealing with our Japanese distributors for about six years when their head honcho asked for a face-to-face. It's true that Thelma and I enjoy a life of bliss in our double wide, but I wasn't sure how these foreigners would take to a genuine Mississippi abode. They would have to circumnavigate several junk cars to reach the front door. They would have to sleep with ol' Blue and a half dozen of his flea-bitten companions who hold the existing claim to our guest bed. After a brief emailed discussion of accommodations, we decided to meet in a neutral country: California.
There was a second introduction stacked in the Tarot cards, but this one was binary. I was prodded into action when I discovered that the in-box had been overrun with requests for some method of displaying HTML code. And both of those emails were strongly worded! It was time for... Drum roll... Use deep voice... "FutureBASIC meets the HTML Renderer."
The first step was to locate documentation of the new manager. Apple's only documentation seems to be a terse little reference called HTML_RenderingLib.pdf. A quick search of the hard drive turned up another necessary component. It is an extension called HTMLRenderingLib, which seems to work well in both Systems 8.x and 9. It took me more than an hour to locate the carbon library on a monthly SDK CD that contained information on the constants and toolboxes. Another few minutes were required for converting the code from C to FB^3. These converted toolbox calls are now placed in a file named Tlbx HTML Rendering.Incl and can be found at stazsoftware.com, on the Release 3 CD, or with electronic versions of this publication. The routines are accessed by your program with the following line of code:
INCLUDE "Tlbx HTML Rendering.Incl"
When Cultures Collide
The whole thing about meeting those foreigners had me on pins and needles. My first faux pas came when they introduced themselves and handed me business cards. They do this by holding the card in both hands and bowing slightly when it is presented. I could tell right off that this was a big deal and I was anxious not to appear uncouth. (These guys were really couth.) I hastily extracted a card from my wallet and smoothed it out against my jeans. (This had the added benefit of wiping away some dirt and a few non-descript chicken parts that had adhered to the card.) I scratched out Bubba's Seafood and Shoe Repair, then carefully printed my name. I bowed and presented it to that foreign guy. Please note here that things did not work out exactly as I had envisioned. I am loath to admit it, but I believe that a recently consumed six pack of Bud may have been responsible for my falling against him and knocking down the entire Japanese contingent like a row of carefully placed dominoes.
The thought of working with the new HTML Rendering library had me on edge too. I soon discovered that a few simple toolbox calls would do the work for me. To simplify this example program, I decided to use the FutureBASIC II runtime (one of the many runtimes available under the Command menu). This allowed me to prune window, menu, and event handling so that the example could concentrate on the concepts of HTML rendering. The entire code set (sans remarks and white space) is just over 100 lines. It was written to work with almost any preference setting, but you will need to uncheck Toolboxes require "CALL" in the preferences window and make sure that you compile in PPC. (This particular set of routines does not include 68K inline code.) The program operates from a single window and contains a small set of globals.
DIM AS LONG gHRref // heavily used HR reference
DIM AS LONG @gPort& // "@" means don't use register
DIM gResizeFlag // bool: window will be resized
DIM gQuit // flag says it's time to terminate
Program brevity may be contributed to the fact that we use only one window. Its pointer is held in gPort&. For non-FBers: You don't have to type class variables in FutureBASIC, though you can if you desire. There is no necessity for setting separate variables for a grafport and a window pointer, as they are (in System 9 and earlier) the same address. Another obvious difference from other languages is that a local function does not have to return a result. Even if it does return something, the caller does not have to accept the result. This makes for a bulletproof environment.
Almost every operation involving the HTML rendering library requires an HTML Rendering (HR) reference number. We start with a single gHRref and use it for the duration. The only remaining globals are two flags that indicate when to resize the rendering area and when to quit the application.
Three utility functions handle most of the work. The first sets the rectangle of the rendering area based on the size of the grafport. This is called when a window is resized and when the window is initially created.
This routine sets the size of the HTML
rendering rect so that it fits in the
DIM AS RECT renderRect
LOCAL FN setHTMLrect
gResizeFlag = _false
renderRect = @gPort&.portRect%
err = FN HRSetRenderingRect(gHRref,renderRect)
Because of automatic colorization and things not used in the formatting of code for this publication, you will see a significant difference in appearance (though not in content) between the printed code and the screen version.
The FB^3 Editor Window.
In FB^3, bookmarks are visible lines instead of obscure selection ranges. Indention and capitalization are automatic. Font, size, style, capitalization, and fore/background colors are user selectable for remarks, bookmarks, keywords, toolbox calls, quoted strings, constants and more. There are several ways of sorting the function menu and you may command-double-click a word to be transported to its definition.
The most important routine calls the toolbox rendering library and handles necessary set up. In FN showLocalURL, we insure that the library is available, create the new HR reference, and open the file specified by name and volume reference number. Note that this particular example works on local files rather than web based files. This lends itself more readily to building HTML based help systems and handling local tests of a web site before uploading. I tested the project by opening a local copy of the STAZ web site and navigating hither and yon. Amazingly, clicking mail links launched my email program. Clicking links to remote locations opened the Netscape browser and took me to the site. If you wish to work from downloaded web pages instead of local files, you will need to review FN HRGoToURL.
Check to see if rendering is available.
Create a new HR reference.
Build a file spec to an HTML file.
Render the file.
DIM spec AS fsspec
LOCAL FN showLocalURL(theURL$,vRef%)
LONG IF FN HRHTMLRenderingLibAvailable
LONG IF gHRref = 0
err = FN HRNewReference(gHRref,¬
LONG IF FN FSMAKEFSSPEC(vRef%,0,theURL$,spec) = _noErr
LONG IF FN HRGoToFile(gHRref,spec,_false,¬
_zTrue) = _noErr
LONG IF FN HRGetTitle(gHRref,wTitle$) = _noErr
A final library call performs the simple task of closing down the HR reference. It is called when the application quits.
On exit, dispose of the HR reference.
LOCAL FN terminate
err = FN HRDisposeReference(gHRref)
This Is My Gift to You
Excuse my digression. Only moments ago, we were deeply involved in the tale of an important business meeting. During the last episode, the hero's (that would be me) denim-clad torso was sprawled across a pile of tailored Japanese suits. They declined my offer to help them back to a standing position and proceeded with the next part of eastern culture where we exchanged gifts. They presented a towel thing that had a bunch of that funny looking writing and a small collapsible fan. I wiped sweat from my brow, fanned myself, (to show appreciation) and donned a very large grin with a very small number of teeth. It was then that I realized I was not in possession of a reciprocating gift.
I had to think fast - like the time that Thelma found me in the barn with... (Never mind. I'll save that for another article.) Anyhow, luck was with me because I had just emptied and flattened a perfectly good spit cup prior to the meeting. I turned around, removed it from my shirt pocket, and stretched it back out. I did a perfect military about face in accordance with the pomp and circumstance of the occasion. (Unfortunately, the aforementioned six pack caused me to turn a lot farther than 180 degrees and took a significant number of tiny little baby steps to realign.) I bowed, and presented the head guy with a slightly used (but still perfectly good) spit cup.
The many runtimes of FB^3 are a gift that we programmers may accept without reciprocation. I mentioned earlier that I used the FBII emulation for this project. It allowed me to build and maintain a window with a single line of code. My total set is held in this simple fragment:
_fileMenu = 1
BEGIN ENUM 1
MENU _fileMenu,0 ,_enable,"File"
The next task involves event handling. The program accepts the default behaviors for most user interaction, but process a few window message items specific to this type of application. During update events, a region is created and HRdraw is used to redraw the rendered area. When the window is activated or deactivated, HRactivate and HRdeactivate are called into action. When the window is closed, the gQuit Boolean is set and when it is about to be resized, gResizeFlag is set.
Handle window refresh, activate, deactivate,
grow, and close.
LOCAL FN doDialog
act = DIALOG(0)
ref = DIALOG(act)
CASE _wndRefresh // update
rgn& = FN NEWRGN
err = FN HRdraw(gHRref,rgn&)
CASE _wndActivate // activate/deactivate
LONG IF ref > 0
err = FN HRactivate(gHRref)
err = FN HRdeactivate(gHRref)
CASE _wndClose // close
gQuit = _zTrue
CASE _preview // grow
LONG IF ref = _preWndGrow
gResizeFlag = _zTrue
The HR library is intelligent enough to handle its own events. We pass these through a raw event vector which receives events before FB^3 acts upon them.
Handle raw events before FB has a
opportunity to process them
LOCAL FN doEvent
LONG IF FN HRIsHREvent(EVENT)
IF gResizeFlag THEN FN setHTMLrect
Menu events are vectored to a single routine. The Quit item does nothing more than set a flag. The Open item displays a dialog, then vectors to the previously defined FN showLocalURL. Two things are noteworthy.
Noteworthy thing 1: FB^3 places variables in registers until all registers are used. This is an operation that is paramount for PPC speed and is OK until you encounter a parameter that is passed as a pointer to a variable. Registers are not memory locations and cannot themselves be passed as variable addresses. Earlier, we dimensioned @gPort& so that we could use GETPORT(gPort&) because gPort& is a variable that receives information. Similarly, vRef% is dimensioned with the @ symbol because it is a variable that will receive information from the FILES$ routine.
Noteworthy thing 2: Basic users normally use the LEN function to determine the length of a string. In FB^3, you may look at any character in a string by wrapping its offset in brackets. The use of fName$ accomplishes the same thing as LEN by extracting the length byte from a Pascal string.
Handle menu events
LOCAL FN doMenu
LONG IF MENU(_menuID) = _fileMenu
fName$ = FILES$(_fOpen,"TEXT",,vRef%)
LONG IF fName$
gQuit = _zTrue
The final code fragment sets up vectors for those events that interest us, then falls into the event loop.
' Event loop
ON DIALOG FN dodialog
ON EVENT FN doEvent
ON MENU FN doMenu
A Lean, Mean Rendering Machine
I tested the code by opening the index page in my local copy of a web site. The rendering was clean and generally fast, though background patterns seem to be imaged a bit slower in Apple's library than in Netscape's. Nevertheless, the rendering was exact. No pictures disappeared. No text or formatting was lost. Clicking a graphic or link worked just as it would in Netscape. I had never dreamed that the functionality of a browser could be reduced to a few lines of code just as I never dreamed that meeting a few guys from the other side of the pond would be so unnerving.
Screen Shot of FB^3 Simple Browser.
We have put on the blinders and walked a straight and simple path to the completion of this project. And while it is not your Father's Oldsmobrowser, it is certainly an exciting start into untested waters. Good luck in your quest.
The only things that Chris Stasny (a.k.a. The STAZ) enjoys more than sitting on the front porch of his trailer are programming his Mac and finding a good place to spit. He has several commercial products under his ample belt which include Classroom Publisher, FutureBASIC^3, and RedNeck Publisher. You can reach the STAZ tech team at email@example.com or visit their web site at http://www.stazsoftware.com.