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

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.