TweetFollow Us on Twitter

HTML Rendering 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.

BEGIN 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
END GLOBALS

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.

FN setHTMLrect

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 
	current grafport.
*/
LOCAL
DIM AS RECT renderRect
DIM err
LOCAL FN setHTMLrect
  gResizeFlag = _false
  renderRect  = @gPort&.portRect%
  OFFSETRECT(renderRect,1,0)
  INSETRECT(renderRect,0,-1)
  err = FN HRSetRenderingRect(gHRref,renderRect)
END FN

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.

FN showLocalURL

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.
*/
LOCAL 
DIM spec AS fsspec
DIM err,wTitle$
LOCAL FN showLocalURL(theURL$,vRef%)
	LONG IF FN HRHTMLRenderingLibAvailable
		
		LONG IF gHRref = 0
			err = FN HRNewReference(gHRref,¬
							_kHRRendererHTML32Type,¬
							gPort&)
			FN setHTMLrect
		END IF

		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
					SETWTITLE(gPort&,wTitle$)
				END IF
			END IF
		END IF
	END IF
END FN

FN terminate

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
DIM err
LOCAL FN terminate
	err = FN HRDisposeReference(gHRref)
END FN

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.

Init Routines

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:

/*
	Init Everything
*/

_fileMenu = 1

BEGIN ENUM 1
	_openItem
	_quitItem
END ENUM

MENU _fileMenu,0        ,_enable,"File"
MENU _fileMenu,_openItem,_enable,"Open/O"
MENU _fileMenu,_quitItem,_enable,"Quit/Q"

WINDOW 1
GETPORT(gPort&)

Dialog Routines

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
DIM act,ref,err
LOCAL FN doDialog
	act = DIALOG(0)
	ref = DIALOG(act)

	SELECT act 

		CASE _wndRefresh			// update
			DIM rgn&
			rgn& = FN NEWRGN
			rectrgn(rgn&,gPort&.portRect%)
			err = FN HRdraw(gHRref,rgn&)
			DISPOSERGN(rgn&)

		CASE _wndActivate			// activate/deactivate
			LONG IF ref > 0
				err = FN HRactivate(gHRref)
			XELSE
				err = FN HRdeactivate(gHRref)
			END IF

		CASE _wndClose				// close
			gQuit = _zTrue

		CASE _preview				// grow
			LONG IF ref = _preWndGrow 
				gResizeFlag = _zTrue
			END IF
	END SELECT

END FN

FN doEvent

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
DIM err
LOCAL FN doEvent
	LONG IF FN HRIsHREvent(EVENT) 
		% EVENT,0
	XELSE
		IF gResizeFlag THEN FN setHTMLrect
	END IF
END FN

FN doMenu

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$[0] accomplishes the same thing as LEN by extracting the length byte from a Pascal string.

/*
	Handle menu events
*/
LOCAL
DIM fName$
DIM @vRef%
LOCAL FN doMenu
	LONG IF MENU(_menuID) = _fileMenu
		SELECT MENU(_itemID)

			CASE _openItem
				fName$ = FILES$(_fOpen,"TEXT",,vRef%)
				LONG IF fName$[0]
					FN showLocalURL(fName$,vRef%)
				END IF

			CASE _quitItem
				gQuit = _zTrue

		END SELECT
	END IF
MENU
END FN

Event Loop

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

DO
	HANDLEEVENTS
UNTIL gQuit

FN terminate

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 tech@stazsoftware.com or visit their web site at http://www.stazsoftware.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.