Java under PowerPlant
Volume Number: 13 (1997)
Issue Number: 9
Column Tag: Javatech
Putting Java Under PowerPlant
by Danny Swarzman, Stow Lake Software
Building a strategic game application with a C++ engine and a Java user interface
Preface
With Mac OS Runtime for Java(tm)(MRJ) (Pronounced 'marge') you can use C++ to develop a Macintosh application which runs Java code. The Java part could be an applet, an application or neither. MRJ is delivered as shared libraries. The program interface, JManager, is supplied in the MRJ SDK. Both are available from Apple's Java website http://appleJava.apple.com/.
With MRJ you create a custom Java runner. It could be general-purpose or, as described here, designed to run a particular Java program. There are many reasons why you may want to do this. For example, you may have some legacy code in C or C++, such as an engine which performs some abstract task. You want to develop a user interface that will easily migrate. You also would like to deliver an application that will work on a PPC Macintosh. This article shows how this can be done.
TicTacPPC is an application that runs a particular Java program, TicTacApp. TicTacApp contains a call to a native function which is defined in C++ in TicTacPPC. From the perspective of the Java program, the C++ application is virtually the virtual machine. The application fulfills this role with the help of JManager.
TicTacApp
The CodeWarrior project, TicTacApp.java.n, creates a Java bytecode file, TicTacApp.zip. This sets up a Tic Tac Toe game on the screen. The user plays X and the program responds O.
The project has three files:
- TicTacApp.java which contains main().
- TicTacCanvas.java which handles the user interface.
- classes.zip, the Java libraries.
Since it contains a main()function, TicTacApp is a Java application. Since it refers to a native function, it can run only when that native function is defined and available to the Java runner.
TicTacPPC
The CodeWarrior project, TicTacPPC.n creates a Macintosh application, TicTacPPC which will run only if MRJ has been installed in the system. The folder containing TicTacPPC should also contain TicTacApp.zip.
TicTacPPC.n contains all the usual PowerPlant stuff plus MRJ stuff:
- JMSessionStubs.PPC
- NativeLibSupport.PPC
And the application specific files:
- CTicTacApplication.cp -- the application object calls CJManager.cp to respond to New command.
- CFrameWindow.cp -- support for Java AWT frames.
- CJManager.cp -- communicates with the virtual machine through a JManager session and implements the native function.
- CTicTacEngine.cp -- the class so smart that it never loses at TicTacToe.
The focus of this article is the work done by CJManager.cp and CFrameWindow.cp. CJManager.cp opens the file TicTacApp.zip and supports the native function. CJManager.cp is specific to this application.
CFrameWindow.cp is relay service passing events between PowerPlant and JManager without regard for their contents. CFrameWindow.cp is a rudimentary version of a general class to support Java frames.
Figure 1 shows how the various pieces of this hybrid application fit together.
Figure 1. How the pieces of this hybrid application fit together.
Running Java Programs
Starting up the session
The application starts up the virtual machine by opening a session with JManager. The session is the structure through which JManager keeps track of the Runtime Instance, that particular virtual machine which will run our collection of threads of Java execution.
JManager uses a JMSession data structure to keep track of the session. The application has no access to the internals of the JMSession. It does provide JManager with a set of callback functions to handle standard files, stdin, stdout and stderr. The application also specifies security options, telling JManager how to limit what the Java program will be able access in the local system.
Since TicTacPPC will run only one Java program, TicTacApp, we don't worrry about security and don't need to support standard files. All these are set to default values.
CJManager.cp
CJManager
The constructor sets up the JManager session.
CJManager :: CJManager ( LCommander *inSuperCommander )
// Set up a session with JManager. Setup a context for the frames.
{
// This is an app that will run locally so security is not used.
// To run apps, you might want to put sensible values here.
static JMSecurityOptions securityOptions = {
kJMVersion, eCheckRemoteCode,
false, { 0 }, 0, false, { 0 }, 0,
eUnrestrictedAccess, true };
// If you want to implement standard files you must create functions
// for stderr, stdout, stdin and put pointers to the functions into this
// JMSessionCallbacks structure
static JMSessionCallbacks sessionCallbacks =
{ kJMVersion, nil, nil, nil };
// Create the session
ThrowIfOSErr_ ( JMOpenSession ( &sSession, &securityOptions, &sessionCallbacks, 0 ) );
// Create the context for frames to support the AWT. These will be discussed later.
sContext = CFrameWindow :: CreateContext ( sSession, inSuperCommander );
}
Idling to give Java some time
The application gives the virtual machine time to service its threads by calling JMIdle. It is recommended that JMIdle be called at each cycle of the event loop. PowerPlant provides a convenient way to do that by subclassing from LPeriodical and overriding its SpendTime method.
CJManager.cp
SpendTime
The application calls this at idle time. It gives MRJ a chance to
attend to its threads.
void CJManager :: SpendTime ()
{
JMIdle ( sSession, kDefaultJMTime);
}
Finding Java Entities with JRI
The Java Runtime Interface is the standard for a C++ program to access Java entities used with MRJ 1.x. It was developed by Netscape to support code that works with their Navigator(tm) product. JRI allows the C++ program to find Java objects and contains specifications for conversion from Java types to C++ types.
The runtime stack and other data used by the virtual machine to keep track of the execution of a thread is the thread's environment. Calls to JRI pass an opaque structure representing the current environment. Through it, JRI locates objects, classes and methods.
Calling Java functions from C++
Through JManager calls, the application can virtually call Java functions. First the application uses JRI to locate the function and then uses JManager to invoke the function.
In RunApp() JManager is asked to execute the main() function of class TicTacApp in file TicTacApp.zip. First JManager calls are used to make the file available to the virtural machine. JRI calls locate the class. Finally the JManager call JMExecStaticMethodInContext() starts the process.
JRI specifies an encoding scheme to represent Java function signatures as strings. There are macros in JRI.h to construct them. Search for JRISig. Look at the macro definitions and the accompanying comments. You can infer the coding scheme, as is done here, or use the macros.
Actually JMExecStaticMethodInContext() tells the virtual machine to queue a request. TicTacApp's main() is not interpreted until the virtual machine gets around to it. The virtual machine runs when it is given time, that is when the application calls JMIdle().
Don't let your threads get tangled
Because the execution of the Java function is not immediate, the C++ program should not depend on the results being valid at a particular time. Deadlock will occur if the C++ program waits for a variable that is changed by the called Java function.
Multi-threaded or concurrent programming presents its own challanges. In this kind of application, there are extra opportunities for chaos. A good strategy would be to keep only one thread of C++ execution. Let the virtual machine manage multiple threads of Java. Keep the native functions short and fast.
CJManager.cp
CJManager
void CJManager :: RunApp ()
// Open file and call main in class appName.
{
// Find the file.
FSSpec fileSpec;
JRIMethodID method;
char *fileURL = "file:///$APPLICATION/TicTacApp.zip";
ThrowIfOSErr_ ( JMURLToFSS ( sSession,
fileURL, &fileSpec ) );
ThrowIfOSErr_ ( JMAddToClassPath ( sSession, &fileSpec ) );
// Find the class.
JRIEnv* environment = nil;
Assert_ ( environment = JMGetCurrentEnv ( sSession ) );
JRIClassID appClass;
char *appName = "TicTacApp";
Assert_ ( appClass =
JRI_FindClass ( environment, appName ) );
// Run main. The third argument of JRI_GetStaticMethodID
// specifies a signature of a Java function.
// "([LJava/lang/String;)V" Specifies a function with
// a single argument which is an array of references to objects
// of class Java/lang/String. It returns type void.
Assert_ ( method = JRI_GetStaticMethodID(environment,
appClass, "main", "([LJava/lang/String;)V" ) );
ThrowIfOSErr_ ( JMExecStaticMethodInContext( sContext,
appClass, method, 0, nil) );
}
Providing Support for AWT
When the user does something, such as pressing a the mouse button, a chain of program activity starts. Here's what happens:
- The user does something. The operating system reads the hardware and makes the information available for the next call to WaitNextEvent().
- PowerPlant passes the event to the appropriate method in a class descended from a PowerPlant class. In our case it will be an event handler in CFrameWindow.
- CFrameWindow passes the event to JManager.
- JManager passes the event to the virtual machine which interprets the appropriate Java function.
- The Java program responds to the event and creates visual feedback in a frame.
- To provide the drawing environment for the Java frame, JManager calls callback functions in CFrameWindow.
- The CFrameWindow callback manipulates the real windows with the help of PowerPlant.
The job of the application, handled by CFrameWindow, is to provide the event handler for step 3 and the callback for step 7.
Frames and windows
An object of the Java Class Frame is implemented in this application as a CFrameWindow object. CFrameWindow descends from the PowerPlant class, LWindow.
JManager passes a reference to a structure, JMFrameRef, to identify a frame. Through JManager calls, the application stashes a reference to its CFrameWindow inside the JMFrameRef structure. CFrameWindow maintains a pointer to finds its JMFrameRef.
Event handlers
Most events are passed on to JManager for the Java program to handle and respond as described above. For the activate and deactivate events, the event handler changes the appearance of the window itself because there is no provision for a callback to do it.
CFrameWindow.cp
DoSetBounds
This is called when the user resizes the window. It changes the
bounds of the window and of the Java frame.
void CFrameWindow :: DoSetBounds ( const Rect &inBounds )
{
JMSetFrameSize ( mFrame, &inBounds );
}
DrawSelf
When this is called, the window is being updated and the port is set
up. It calls JManager to set up the process of drawing by the Java code.
void CFrameWindow :: DrawSelf ()
{
JMFrameUpdate ( mFrame, GetMacPort()->visRgn );
}
HandleKeyPress
A key has been pressed when the window is in command. Forward the
event to Java.
Boolean CFrameWindow :: HandleKeyPress( const EventRecord &inKeyEvent)
{
if ( inKeyEvent.modifiers & cmdKey ){
JMFrameKey ( mFrame, inKeyEvent.message &charCodeMask,
inKeyEvent.message >> 8, inKeyEvent.modifiers );
return true;
}
else
return false;
}
ObeyCommand
PowerPlant has detected a menu or key equivalent command when the window
is in command. Forward the event to the Java program.
Boolean CFrameWindow :: ObeyCommand ( CommandT inCommand, void *ioParam )
{
switch ( inCommand )
{
case cmd_Close :
JMFrameGoAway ( mFrame );
return true;
}
return mSuperCommander->ObeyCommand ( inCommand, ioParam );
}
ClickSelf
PowerPlant has detected a click in the active window. Forward the event
to the Java program.
void CFrameWindow :: ClickSelf ( const SMouseDownEvent &inMouseDown )
{
JMFrameClick ( mFrame,
inMouseDown.whereLocal,
inMouseDown.macEvent.modifiers );
}
ActivateSelf
This is called when an activate event is received by the window. The
Java frame is activated and the window is activated.
void CFrameWindow :: ActivateSelf ()
{
JMFrameActivate ( mFrame, true );
LWindow :: ActivateSelf ();
}
DeactivateSelf
This is called when an deactivate event is received by the window.
The Java frame is deactivated and the window is deactivated.
void CFrameWindow :: DeactivateSelf ()
{
JMFrameActivate ( mFrame, false );
LWindow :: DeactivateSelf ();
}
Frame callbacks
JManager calls these to do the actual work for the Java Frame object.
They are declared static.
FindFrameWindow
Retrieve the reference to the CFrameWindow object from the client
data field of the frame structure.
CFrameWindow *CFrameWindow ::
FindFrameWindow ( JMFrameRef frame )
{
CFrameWindow *result = nil;
if ( frame )
if ( JMGetFrameData (
frame, (JMClientData*) &result ) == noErr )
return result;
return nil;
}
SetupPortCallback
This frame callback sets the port for drawing. The application
can use the return value of this function to pass an old port
reference that can be later retrieved by RestorePortCallback()
as a form of client data. The value is given back to the application
in the callback to restore the port. This application doesn't
need to do this.
void *CFrameWindow :: SetupPortCallback ( JMFrameRef frame )
{
OutOfFocus ( nil );
CFrameWindow *window = FindFrameWindow ( frame );
if ( window )
window->FocusDraw();
return nil;
}
RestorePortCallback
This callback is provided so that the application can save data,
like a port, with the setup callback and restore it here. This
application doesn't do that.
void CFrameWindow :: RestorePortCallback (
JMFrameRef /*frame*/, void */*param*/ )
{
}
ResizeRequestCallback
This frame callback resizes the window.
Boolean CFrameWindow :: ResizeRequestCallback
( JMFrameRef frame, Rect *desired )
{
CFrameWindow *pane = FindFrameWindow ( frame );
if ( pane && desired )
{
Rect r = pane->mUserBounds;
r.bottom = r.top + desired->bottom - desired->top;
r.right = r.left + desired->right - desired->left;
pane->LWindow :: DoSetBounds ( r );
return true;
}
return false;
}
InvalRectCallback
This frame callback marks a rectangle as needing to be updated.
void CFrameWindow :: InvalRectCallback ( JMFrameRef frame, const Rect *r )
{
CFrameWindow *pane = FindFrameWindow ( frame );
if ( pane )
pane->InvalPortRect ( r );
}
ShowHideCallback
This frame callback shows or hides the window.
void CFrameWindow :: ShowHideCallback ( JMFrameRef frame,
Boolean showFrameRequested )
{
CFrameWindow *pane = FindFrameWindow ( frame );
WindowPtr window = pane->GetMacPort();
if ( pane )
if ( showFrameRequested )
ShowWindow ( window );
else
HideWindow ( window );
}
SetTitleCallback
This frame callback changes the window title.
void CFrameWindow :: SetTitleCallback ( JMFrameRef frame, Str255 title )
{
CFrameWindow *pane = FindFrameWindow ( frame );
if ( pane )
pane->SetDescriptor ( title );
}
CheckUpdateCallback
If the update region isn't empty start the update process.
void CFrameWindow :: CheckUpdateCallback ( JMFrameRef frame )
{
CFrameWindow *pane = FindFrameWindow ( frame );
if ( window && !EmptyRgn(
((WindowPeek)(window>GetMacPort()))->updateRgn))
window->UpdatePort();
}
Creating and destroying frames
When the virtual machine needs to create a new frame, JManager calls an application callback function to create the Macintosh structures needed for the frame. A group of functions is identified to JManager as a context. These functions create and destroy frames and provide for exception notification.
TicTacPPC maintains only one context. The callback functions are declared as static in CFrameWindow. In addition to identifying the context callbacks, the application can store data in a field of JManager's context structure, referenced by a JMAWTContextRef.
In this application, the client data of the JMAWTContextRef structure is used to store a reference to the commander object which will eventually be the super commander of the CFrameWindow objects used for frames. Later, RequestFrameCallback() will use the commander object to create a new CFrameWindow.
CFrameWindow.cp
CreateContext
Create a context using our context callbacks. Put the reference to
the super commander into context structure as client data.
JMAWTContextRef CFrameWindow :: CreateContext ( JMSessionRef inSession,
LCommander *inSuperCommander )
{
static JMAWTContextCallbacks contextCallbacks =
{
kJMVersion, // always this constant.
RequestFrameCallback,
ReleaseFrameCallback,
UniqueMenuIDCallback,
nil // No exception handling - you may want to add it.
};
JMAWTContextRef context;
ThrowIfOSErr_ ( JMNewAWTContext ( &context, inSession,
&contextCallbacks, 0 ) );
ThrowIfOSErr_ ( JMSetAWTContextData ( context, (JMClientData)inSuperCommander ) );
ThrowIfOSErr_ ( JMResumeAWTContext ( context ) );
return context;
}
RequestFrameCallback
This context callback creates a new CFrameWindow for the new frame.
This implementation ignores all the characteristics requested in the
call because it will be used only with one particular Java program.
To make this function more general, use these to set the window
parameters.
OSStatus CFrameWindow :: RequestFrameCallback (
JMAWTContextRef context, JMFrameRef newFrame,
JMFrameKind /* kind */, UInt32 /*width*/,
UInt32 /*height*/, Boolean /* resizable */, JMFrameCallbacks *callbacks )
{
callbacks->fVersion = kJMVersion;
callbacks->fSetupPort = SetupPortCallback;
callbacks->fRestorePort = RestorePortCallback;
callbacks->fResizeRequest = ResizeRequestCallback;
callbacks->fInvalRect = InvalRectCallback;
callbacks->fShowHide = ShowHideCallback;
callbacks->fSetTitle = SetTitleCallback;
callbacks->fCheckUpdate = CheckUpdateCallback;
// The context client data contains a reference to a LCommander object.
JMClientData data;
JMGetAWTContextData ( context, &data );
CFrameWindow *window = (CFrameWindow*)CreateWindow (
kFrameWindowResID, (LCommander*)data );
// Identify the frame structure with the window.
window->mFrame = newFrame;
// The frame's client data points to the window.
JMSetFrameData ( newFrame, (JMClientData*)window );
window->Show();
return noErr;
}
ReleaseFrameCallback
JManager is done with the frame. Destroy its CFrameWindow object
OSStatus CFrameWindow :: ReleaseFrameCallback (
JMAWTContextRef /* context */, JMFrameRef oldFrame )
{
CFrameWindow *pane = FindFrameWindow ( oldFrame );
delete pane;
return noErr;
}
UniqueMenuIDCallback
This context callback isn't used because the Java app that we're
running doesn't create any menus. This code was copied from Apple
sample code.
SInt16 CFrameWindow :: UniqueMenuIDCallback ( JMAWTContextRef /*context*/, Boolean isSubmenu )
{
static SInt16 theFirstHierMenu = 1;
static SInt16 theFirstNormalMenu = 500;
if (isSubmenu )
return theFirstHierMenu++;
return theFirstNormalMenu++;
}
Implementing a Native Function
The Java class TicTacCanvas contains an interface for a function:
static native void DoOMove(char[]board);
The keyword native tells the compiler that the function is defined by the local system. In this case, it is defined in the application.
A C++ function will take an Java array representing the position on the board when it is O's turn to play. After the native function executes, the array will contain the new O move.
The C++ program must tell JManager which function will implement the native. To identify the Java funtion, the program uses signatures as discussed in the JRI documentation. The signature for this function is "DoOMove([C)V".
CJManager.cp
RegisterNative
Identify CJManager::DoOMove() as the C++ function that handles the Java
native call to TicTacCanvas.DoOMove().
void CJManager :: RegisterNative ()
{
// Find the class.
JRIEnv* environment = nil;
Assert_ ( environment = JMGetCurrentEnv ( sSession ) );
JRIClassID canvasClass;
static char *canvasClassName = "TicTacCanvas";
Assert_ ( canvasClass = JRI_FindClass ( environment,
canvasClassName ) );
// Create signatures for all the native functions. We have only one function.
// The signatures include the function name. This function
// passes one argument which is an array of the Java type char. It returns void.
static char *signatures = "DoOMove([C)V";
// To support the one native function, there is one C++ function.
// Pass a pointer to an array with one element.
static void *procArray[] = { DoOMove };
JRI_RegisterNatives ( environment, canvasClass,
&signatures, procArray );
}
The implementation of the native function
The array passed to JRI_RegisterNatives contains pointers to functions defined as:
typedef void (*JRI_NativeMethodProc)(JRIEnv* env,
jref classOrObject, ...);
The first parameter identifies the thread of Java execution invoking the function. The second is the Java object for which the function is called. If the function is a class function, the second parameter is the class for which the function is defined.
Succeeding parameters are the parameters in the original Java call. Each of these is of type jref, the general-purpose JRI type.
In the case of Java function, DoOMove(), there is one parameter which is a reference to a Java array of Java type char. The type jchar is defined in JRI to represent Java type char. The reference to a Java array is not the same as a pointer. The Java specifications say that an array of a primitive type is represented as a series of contiguous storage locations. The actual data is located somewhere in the stack of the Java thread. For this purpose, DoOMove must call GetScalarArrayElement().
Included in Sun's JDK there is a utility, javah, to help set up prototypes for native functions. Using it is more work than writing your own prototype for one function. It will be obsolete with the next version of Java.
DoOMove
This function supports the Java native function void DoOMove(char[]ioBoard);
Find the pointer to the data in an array of java char. Call the engine
to make the move in the C++ array whose elements are jchar.
void CJManager :: DoOMove ( JRIEnv *env,
jref /*JavaObject*/, jref ioBoard )
{
jchar *board = (jchar*) env->GetScalarArrayElements ( ioBoard );
CTicTacEngine :: BestOPossible ( board );
}
The Application Class
CTicTacApplication is an PowerPlant LApplication subclass. It calls CJManager to start up, to spend idle time and to respond to New menu commands.
CTicTacApplication.cp
CTicTacApplication
Register the class PowerPlant class which handles Java frames. Start
up JManager. Start recieving idle events.
CTicTacApplication :: CTicTacApplication()
{
RegisterClass_(CFrameWindow);
CJManager startupASession ( this );
StartIdling();
}
SpendTime
Forward idle event to JManager. Overrides LPeriodical function.
void CTicTacApplication :: SpendTime()
{
CJManager :: SpendTime();
}
MakeNewDocument
Respond to New.
LModelObject *CTicTacApplication :: MakeNewDocument()
{
CJManager :: OpenApp ();
CJManager :: RegisterNative();
return nil;
}
Building and Debugging The Application
First install all the MRJ stuff and read the MRJ docs and the JRI docs.
To build TicTacPPC, start with the usual PowerPlant stuff.
Add MRJ libraries to the project. For PPC they're JMSessionStubs.PPC and NativeLibSupport.
Add access paths for the includes in the MRJ SDK.
Add an access path for the Metrowerks Standard Library C includes.
Set in the C/C++ Language settings "Enums Always Int".
This line in JRI.h causes a problem:
void Throw(JRIThrowableID throwableID)
{ interface->ThrowProcPtr(this, throwableID); }
I commented it out. You may choose a more elegant solution, especially if you want your callback to be able to throw a Java exception.
Build the project and start debugging. Debug the application in the usual way. If you need to step through the Java app at the same time, there is an extra step. Open the .zip file in the debugger and set a breakpoint where you want it. Now you can debug the application in the usual way. It will stop at your Java breakpoint as well as those in the application.
Conclusions and Future Directions
MRJ, in conjunction with CodeWarrior and PowerPlant provides an excellent environment for developing an application with parts in Java and parts in C++.
There are some pitfalls for developing larger projects. The most apparent problem is the delay in the sequence of upgrades in the long trek from Mountain View to Cupertino. It gets to Washington several months earlier. MRJ 2.0 corresponding to Sun's SDK 1.1 lags behind other platforms by many months. There's the additional lag for a version for 68k Macs. This is pioneering stuff and it is reasonable to expect that there be some retrofitting between the beginning of development and release time for a product using MRJ.
If your application permits, it would be best to confine the interface between the C++ application and the Java code to something very simple. Here we just invoke the main() and let the Java program take it from there. Instead of making many prototypes and signatures, implement one native and avoid the mess. The bulk of the work that you put into a project of this nature will endure.
Bibliography and References
The MRJ package is available from Apple's web site at http://appleJava.apple.com/.
Documentation on the Java Runtime Interface (JRI) is available at http://home.netscape.com/eng/jri/.
Another example of using PowerPlant with MRJ: http://www.fullfeed.com/~lorax/powerplant.html.
Credits
Thanks to Victoria Leonard for the artwork. Thanks to Mark Terry and Bob Ackerman for reviewing work in progress.
Danny Swarzman develops software for fun and games. Fun for the users that is -- he does it to earn money as a consultant. He also works to improve his game-playing skills at the San Francisco Go Club. He has been sited at http://www.stowlake.com. Send comments, questions and job offers to dannys@stowlake.com.