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

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.