lecture 4 oxo for palmmobile and handheld applications1 programming of mobile and handheld devices...
TRANSCRIPT
Lecture 4 OXO for Palm Mobile and Handheld Applications 1
Programming of Mobile and Handheld Devices
Lecture 4: Programming OXO for Palm OS
Rob Pooley
Lecture 4 OXO for Palm Mobile and Handheld Applications 2
Designing and programming a new application
• This lecture describes the design and implementation of the second game we set out in lecture 4.
• This time we are building a noughts and crosses (tic-tac-toe) game.
• Here is the statechart that we defined previously.
X to MoveX has moved
O has moved O to move
moveMessage
[valid ]
moveMessage
[valid]
[Win or draw]
[Win or draw]
[invalid]
[invalid]
Lecture 4 OXO for Palm Mobile and Handheld Applications 3
The design and implement process
• The design of a Palm OS application from a statechart follows the steps below:1. Each state defines a distinct point in the evolution of
the application and needs a screen (Form) which corresponds to it;
2. Each form needs an event handler function;3. For each successor state, each form needs one
mechanism which triggers a move to that state;4. Update the AppHandleEvent function to deal with
the Form types and their handlers defined above;5. Work out what information needs to exist across
states;6. Set up the project and its makefile.
Lecture 4 OXO for Palm Mobile and Handheld Applications 4
Initial state – black filled circle
Welcome to noughts and crosses.Would you like to play a game?
Play Exit
Lecture 4 OXO for Palm Mobile and Handheld Applications 5
X to move state – buttons only
Click on a square to plant a cross
Done
Lecture 4 OXO for Palm Mobile and Handheld Applications 8
X has moved state
Your X move was valid/invalid
OK
Show an alert?
Lecture 4 OXO for Palm Mobile and Handheld Applications 9
Notes as we go
• The state to date must be remembered across states for checking and display updating.
• The text should be different depending on the validity of the move made.
• That is not a user determined outcome, but is triggered by an internal check.
• The grid is displayed with a cross if the move was valid, maybe with some indication of where the invalid move appeared otherwise?
Lecture 4 OXO for Palm Mobile and Handheld Applications 10
Winning state
• Alerts are for grabbing attention and giving information.
• Do we need separate forms or alerts for each outcome?
• We can use a Field and set its text if we want to.
Congratulations to X/OYou won!
Done
Lecture 4 OXO for Palm Mobile and Handheld Applications 11
Control Resources
• Different resources are associated with different controls, as follows:
Button Button Resource (tBTN)
Popup trigger Popup Trigger Resource (tPUT)
Selector trigger Selector Trigger Resource (tSLT)
Repeat control Repeating Button Resource (tREP)
Push button Push Button Resource (tPBN)
Check box Check Box Resource (tCBX)
Slider Slider Resource (tsld)
Feedback sliderFeedback Slider Resource (tslf)
Lecture 4 OXO for Palm Mobile and Handheld Applications 12
FldInsert Function • Replace the current selection if any with the specified string and
redraw the field. • Declared In Field.h • Prototype Boolean FldInsert(FieldType
*fldP,const Char *insertChars, UInt16 insertLen) Parameters • fldPPointer to the field object (FieldType structure) into which to insert.• insertCharsText string to be inserted.• insertLenLength in bytes of the text string to be inserted, not counting the trailing
null character.• Returns Returns true if string was successfully inserted. Returns false if:
Lecture 4 OXO for Palm Mobile and Handheld Applications 14
Edit the makefile to reflect this
## --------------------------------------------------------------------# Sources and Resources# List all the sources (.c/.cpp) and resources (.xrd) in your project# Use project relative path names with forward slashes (src/code.cpp).# Please do not use spaces in directory names.# A note about XRD resource files: If you have existing .rsrc or .rcp, # files refer to the documentation for the GenerateXRD tool to convert # them into XRD files for use with all Palm OS SDKs.## --------------------------------------------------------------------# TODO: Update all sources and resourcesSOURCES = src/AppMain.cRESOURCES = rsc/OXO.xrdSLIB_DEF_FILE =
Lecture 4 OXO for Palm Mobile and Handheld Applications 16
Programming a new application
• Now we describe the implementation of the game.
• We will look at some of the code for the game.
• Here is the statechart that we defined previously.
X to MoveX has moved
O has moved O to move
moveMessage
[valid ]
moveMessage
[valid]
[Win or draw]
[Win or draw]
[invalid]
[invalid]
Lecture 4 OXO for Palm Mobile and Handheld Applications 17
The design and implement process
• The design of a Palm OS application from a statechart follows the steps below:
1. Each state defines a distinct point in the evolution of the application and needs a screen (Form) which corresponds to it;
2. Each form needs an event handler function;3. For each successor state, each form needs one
mechanism which triggers a move to that state;4. Update the AppHandleEvent function to deal with
the Form types and their handlers defined above;5. Work out what information needs to exist across
states;6. Set up the project and its makefile.
Lecture 4 OXO for Palm Mobile and Handheld Applications 18
Pilot Main stays unchanged
UInt32 PilotMain (UInt16 cmd, void *cmdPBP, UInt16 launchFlags)
{ UInt32 error = StartOXOApp(); if(error) return error; OXOAppEventLoop(); EndOXOApp(); return errNone; }
As before we do not worry about non-standard launchcodes
Lecture 4 OXO for Palm Mobile and Handheld Applications 19
Start and Stop functions are unchanged
St
PilotMain
StartOXOAppOXOAppEventLoopEndOXOApp
StartOXOApp
OXOAppEventLoop
EndOXOApp
do getEvent try in turn SysHandleEvent MenuHandleEvent AppHandleEvent FrmDispatchEventwhile not appStopEvent
FrmGotoForm(MainForm)
Lecture 4 OXO for Palm Mobile and Handheld Applications 20
Code for start and stop
static UInt16 StartOXOApp(void)
{
UInt16 error = 0;
FrmGotoForm(MainForm);
return errNone;
}
static void EndOXOApp(void)
{
FrmCloseAllForms( );
}
Lecture 4 OXO for Palm Mobile and Handheld Applications 21
Event loop is unchanged
static void OXOAppEventLoop(void){ Err error; EventType event; do { EvtGetEvent(&event, evtWaitForever); if (! SysHandleEvent(&event)) if (! MenuHandleEvent(0, &event, &error)) if (! AppHandleEvent(&event)) FrmDispatchEvent(&event); } while (event.eType != appStopEvent);}
Lecture 4 OXO for Palm Mobile and Handheld Applications 22
AppHandleEvent is different
static Boolean AppHandleEvent(EventType* pEvent)
{uint16_t formId;FormType* pForm;
UInt16 formId; FormPtr pForm;
if (event->eType == frmLoadEvent) { // Load the form resource. formId = event->data.frmLoad.formID; pForm = FrmInitForm(formId); ErrFatalDisplayIf(!form, "Can't initialize
form"); FrmSetActiveForm(form);
// Set the event handler for the form.// The handler of the currently active form// is called by FrmHandleEvent each time// it receives an event.switch (formId) {case MainForm:FrmSetEventHandler(pForm,
MainFormHandleEvent);break;
case XtoMoveForm:FrmSetEventHandler(pForm,
XtoMoveFormHandleEvent);break;
case OtoMoveForm:FrmSetEventHandler(pForm,
OtoMoveFormHandleEvent);break;
/* Add a case for each type of form here */
default:ErrFatalDisplay("Invalid Form Load Event");break;}
return true;}
return false;}
Lecture 4 OXO for Palm Mobile and Handheld Applications 23
Make a handy function to aid logic
int CheckGrid(int x; int y){/* Checks the grid after a move and returns * 0 if the game is not over * 1 if X has won * 2 if O has won * 3 if it is a draw * 4 if it is an invalid move */ int i, j; if (grid[x][y]!='\0') return 4; for (i=0;i<7;i+=3) if ((grid[i]==grid[i+1])&&(grid[i]==grid[i+2])) if (grid[i]=='X') return 1; else if (grid[i]=='O') return 2; else return 0; /* Need more checking here */}
Lecture 4 OXO for Palm Mobile and Handheld Applications 24
Write the event handlers
Boolean XtoMoveFormHandleEvent(EventType *event){// Find which event type and handle it Boolean handled = false; FormPtr form; int i;
switch (event->eType) { case frmOpenEvent: form = FrmGetActiveForm(); FrmDrawForm(form); // here's where you'd add a call to FrmSetFocus handled = true; break;
Lecture 4 OXO for Palm Mobile and Handheld Applications 25
If it is a ctl type event, find the button
case ctlSelectEvent:// Find which ctl caused this and handle
it switch (event->data.ctlSelect.controlID)
{
case TLButton: /* Top left button of grid */
outcome = CheckGrid(); switch (outcome) { case 0: /* No result yet */ { break; } case 1: { i = FrmAlert(WinAlert); FrmGotoForm(MainForm); break; }
case 3: /* Draw */ { i = FrmAlert(DrawAlert); FrmGotoForm(MainForm); break; } case 4: /* Illegal move */ { i = FrmAlert(CheatAlert); break; } default: break; }
Lecture 4 OXO for Palm Mobile and Handheld Applications 26
Summary
• When we are writing an application, we can often follow this simple pattern
• The main structure remains the same• The detail of forms requires a handler for each
type of form• The detail of a form’s handler comes from the
types of event which can occur while it is active• Outcomes usually result in forms being updated
or a new form becoming active
Lecture 4 OXO for Palm Mobile and Handheld Applications 27
Memory, databases and files on Palm OS
Tidying up some further details.
Lecture 4 OXO for Palm Mobile and Handheld Applications 28
Application memory management
• In Palm OS the Memory Manager APIs exist mainly for use by the Data Manager to manage storage heaps.
• Application developers can use the standard C library functions such as malloc() and free() to manage dynamic memory.
Lecture 4 OXO for Palm Mobile and Handheld Applications 29
Chunks, pointers and handles
• When an application requests an immovable chunk it receives a pointer to that chunk.
• The pointer is simply that chunk’s address in memory. – Because the chunk cannot move, its pointer remains valid for the
chunk’s lifetime; thus, the pointer can be passed “as is” to the caller that requested the allocation.
• When an application requests a movable chunk, the operating system generates a pointer to that chunk, just as it did for the immovable chunk, but it does not return the pointer to the caller.– Instead, it
• stores the pointer to the chunk, called the master chunk pointer, in a master pointer table that is used to track all of the movable chunks in the heap, and
• returns a reference to the master chunk pointer. – This reference to the master chunk pointer is known as a handle.
• It is this handle that the operating system returns to the caller that requested the allocation of a movable chunk.
Lecture 4 OXO for Palm Mobile and Handheld Applications 30
Allocating and Freeing Memory Chunks
• To allocate a movable chunk, call MemHandleNew()
and pass the desired chunk size. • To free a memory chunk given its handle, call
MemHandleFree(). • The Memory Manager provides similar functions that
work with immovable chunks: MemPtrNew()
allocates a memory chunk and returns a pointer to it, whileMemPtrFree()
frees a chunk given its pointer.
Lecture 4 OXO for Palm Mobile and Handheld Applications 31
Locking movable memory chunks
• Before you can read or write data to a movable chunk you must call MemHandleLock() to lock it and get a pointer to it.
• Then, when you no longer need direct access to the chunk’s contents, call MemHandleUnlock().
• (Note that after a call to MemHandleUnlock, the pointer your application was using to access the chunk’s contents is no longer valid.)
Lecture 4 OXO for Palm Mobile and Handheld Applications 32
Manipulating Chunk Contents
• The Memory Manager provides three utility functions that you can use when working with the contents of a chunk:– MemMove() moves memory from one place to
another.– MemSet() fills memory with a specific value.– MemCmp() compares two regions of memory.
Lecture 4 OXO for Palm Mobile and Handheld Applications 33
Databases
• Palm OS doesn’t make use of a traditional file system. Instead of files, Palm OS applications work with databases.
• Databases organize related rows (for schema databases) or records (for non-schema databases); each belongs to one and only one database.
• A database may be a collection of all address book entries, all datebook entries, and so on.
• A Palm OS application can create, delete, open, and close databases as necessary, just as a traditional file system can create, delete, open, and close a traditional file
Lecture 4 OXO for Palm Mobile and Handheld Applications 34
Types of database in Palm OS
• Schema databases, which were introduced in Palm OS Cobalt, bear a strong resemblance to relational databases.
• Data is organized into tables, which consist of rows and columns.
• Schema databases use the concept of a schema to define the structure of a table row.
• Unlike relational databases, however, schema databases don’t allow you to perform joins and other complex operations.
Lecture 4 OXO for Palm Mobile and Handheld Applications 35
Types of database in Palm OS - 2
• Classic databases are supported for compatibility with earlier versions of Palm OS.
All versions of Palm OS back to Palm OS 1.0 support this database format,
this is the format used by applications running on Palm OS Cobalt through PACE.
Lecture 4 OXO for Palm Mobile and Handheld Applications 36
Types of database in Palm OS - 3
• Extended databases are an “extended” version of classic databases.
• There are three primary differences between classic and extended databases:
1. extended databases records can exceed 64K in length (classic records cannot);
2. Extended databases are uniquely identified by a combination of name and creator ID (classic databases are uniquely identified by name alone);
3. extended databases can store data using the processor’s native endianness – (classic databases must store record data using big-
endianness, for compatibility with the 68K-based Dragonball CPU used in the early Palm OS devices)
Lecture 4 OXO for Palm Mobile and Handheld Applications 37
Summary of Palm OS section
• Palm OS is widely used and works well on Palm devices• Palm OS has some good tools• Palm OS Developer Kit is not really “finished”• There is a lack of really good, simple to understand
documentation on Palm OS programming• It seems likely that J2ME will displace Palm OS as the
most widely used application development for Palm devices
• J2ME also runs on phones etc.
Lecture 4 OXO for Palm Mobile and Handheld Applications 38
References
• The full documentation for Palm tools is available online at:– www.palmos.com/dev/support/docs/
• Note that there are two documentation sets, one for the simpler 68k systems and one for more recent RISC based systems, called protein systems by Palm.
• A somewhat limited tutorial can be found in • Palm OS Programming 2nd Edition, Rhodes and
McKeehan, O’Reilly Books
• O’Reilly also produce:• Palm OS Network Programming Writing Connected
Applications for the Palm By Greg Winton