Chapter 4 , Cross-Platform Application Development REALbasic gives you the capability to create applications forWindows, Macintosh, and Linux operating systems.. REALBASIC IS A MODERN, O
Trang 1By Mark Choate
Publisher: Sams Pub Date: April 12, 2006 Print ISBN-10: 0-672-32813-5 Print ISBN-13: 978-0-672-32813-8 Pages: 672
out there Get inside this development environment with REALbasic Cross-Platform
Application Development.
Trang 2By Mark Choate
Publisher: Sams Pub Date: April 12, 2006 Print ISBN-10: 0-672-32813-5 Print ISBN-13: 978-0-672-32813-8 Pages: 672
Trang 6REALbasic CrossPlatform Application Development
Copyright © 2006 by Sams Publishing
All rights reserved No part of this book shall be reproduced,stored in a retrieval system, or transmitted by any means,
electronic, mechanical, photocopying, recording, or otherwise,without written permission from the publisher No patent
liability is assumed with respect to the use of the informationcontained herein Although every precaution has been taken inthe preparation of this book, the publisher and author assume
no responsibility for errors or omissions Nor is any liabilityassumed for damages resulting from the use of the informationcontained herein
regarded as affecting the validity of any trademark or servicemark REAL Software, REALbasic and the REAL Software cubelogo are registered trademarks of REAL Software, Inc
Trang 7Every effort has been made to make this book as complete and
as accurate as possible, but no warranty or fitness is implied.The information provided is on an "as is" basis
Bulk Sales
Sams Publishing offers excellent discounts on this book whenordered in quantity for bulk purchases or special sales For
Trang 9REALbasic to develop cross-platform tools for use in online
publishing
Trang 10
I would be remiss if I also did not mention two people to whom
I am particularly indebted Both Connor Choate and ChristineGoertz Choate provided patient support while I wrote the book.They gave up more than a few weekends and vacations, andwithout their help I would not have been able to complete thisbook They both have my heartfelt thanks and sincere
appreciation
Trang 11
As the reader of this book, you are our most important critic
and commentator We value your opinion and want to know
what we're doing right, what we could do better, what areasyou'd like to see us publish in, and any other words of wisdomyou're willing to pass our way
You can email or write me directly to let me know what you did
or didn't like about this bookas well as what we can do to makeour books stronger
Please note that I cannot help you with technical problems
related to the topic of this book, and that due to the high
volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book's title andauthor as well as your name and phone or email address I willcarefully review your comments and share them with the authorand editors who worked on the book
Trang 12Visit our website and register this book at
www.samspublishing.com/register for convenient access to anyupdates, downloads, or errata that might be available for thisbook
Trang 13
IN A WORLD OF OPEN SOURCE OR FREELY available
programming languages and integrated development
environments, you might be wondering why you would want topurchase REALbasic, a proprietary language that is closed-
source and definitely not free I think there is a very good
reason to do sobecause REALbasic offers some unique
characteristics that cannot be found anywhere else First of all,it's remarkably easy to use It also compiles into native
machine code for three operating systems: Windows,
Macintosh, and Linux
REALbasic is a dynamic language REAL Software, the companythat produces REALbasic, releases a new version every six
months This means that new features are being added (and oldbugs are being fixed) all the time There is so much you can dowith REALbasic that it is impossible to cover it in one book, so Ihave tried to focus on the primary features of the language thatmost programmers will use Rest assured, however, that by thetime you read this, there will be more features available andstill plenty more to learn about
REALbasic also has a very active and friendly user community
If you have not done so already, it's a good idea to sign up forone of the mailing lists where users post questions and get
answers from other users as well as REALbasic engineers
themselves Throughout the years, I have been an avid reader
of the messages from these lists, and this book owes a debt ofgratitude to everyone who has participated
In the coming pages, you will read about what you will find inthe rest of the book Wherever possible I have used real-worldexamples that you can use in your own development I havetried to present the information in such a way that it is useful toboth first-time and experienced programmers
Trang 14Chapter 3 , Classes and Objects
REALbasic is an object-oriented programming language, andthis chapter delves into object-oriented programming conceptsand how they are implemented in REALbasic
Chapter 4 , Cross-Platform Application
Development
REALbasic gives you the capability to create applications forWindows, Macintosh, and Linux operating systems This chapterprovides you with some basic information about the differencesamong the platforms that will help you to write quality
applications on all of them
Chapter 5 , Designing a Desktop Application
Desktop applications are applications that make use of a
graphical user interface The REALbasic IDE lets you use thedrag-and-drop feature to design your user interface, and thischapter shows you how
Trang 15Chapter 6 , XML and Advanced Text Processing
XML, regular expressions, and styled text are discussed in thischapter
Chapter 7 , Console Programming and the Shell
You can also create programs in REALbasic that run on thecommand line, without a graphical user interface You can
interact with the Shell programmatically through REALbasic'sShell class, and you can also write your own console
applications that can be run from within the shell on each
platform
Chapter 8 , Databases
You can design a graphical front-end to your database withoutwriting a single line of code This chapter shows you how
Chapter 9 , Networking and Internet
Programming
Read about REALbasic's networking classes and learn how towrite your very own web server
Chapter 10 , Graphics
This chapter delves into REALbasic's Graphics class and showsyou how to manipulate graphics and draw to the screen
Chapter 11 , Scripting and Extending REALbasic
Trang 16to make your REALbasic application scriptable You'll also begiven an overview on how you can extend REALbasic by usingshared libraries and writing plug-ins in C++
Appendix
Read about where you can go online to find additional
information and how to get copies of the sample code
referenced in the book
Trang 17REALBASIC IS A MODERN, OBJECT-ORIENTED DESCENDENT ofthe venerable Basic programming language that I first
encountered in my high school computer programming class,whose code I laboriously typed out on a dot-matrix terminal
The original version of the language was developed in 1964 Itwas designed to be a good language for beginning
programmers to learn, which is the very reason I learned to use
it In fact, the name "Basic" means Beginners All-purpose
Symbolic Instruction Code
1970s New life was breathed into the language in 1991, whenMicrosoft released Visual Basic 1.0 (the latest iteration of VisualBasic is known as Visual Basic NET, or Visual Basic 7.0, whichwas first released in 2001) Visual Basic was a modern version
Microsoft released its first version of the language in the mid-of Basic that made it much easier to develop programs withgraphical user interfaces Because it is a highly accessible
it was released in 1998 as a tool for rapid application
development on the Macintosh platform Although AppleScriptwas an easy-to-use language for scripting applications, it wasnot usable at that time as a tool for developing applications As
a result, REALbasic established itself as the perfect entry-levelapplication development environment for the Macintosh
The language has its roots in the Macintosh environment, butthe plan from the beginning was to develop a cross-platform
Trang 18The next real step forward came in 2003, when REAL Softwareadded a Windows version of the IDE with the release of
REALbasic 5.0 The 5.0 release was an important one for
REALbasic and also included the addition of new features thatmade it a much more viable programming language for seriousapplication developers It included the capability to write
command-line applications and support for XML (which was afeature surprisingly late in arriving) Although you had beenable to compile Windows apps since 1999, this was the firsttime you could develop them in Windows Version 5.5, released
in 2004, added the capability to compile Linux apps
Trang 19An easier question to answer would be what isn't new in
REALbasic 2005 With the release of this version, the integrateddevelopment environment (IDE) has been totally overhauledand much improved, especially if you have used the Windowsversion of REALbasic 5.5 which, well, let's just let bygones bebygones
With the 2005 release, REAL Software offers integrated
development environments for Macintosh, Windows, and Linux.The IDE was written in REALbasic, which means that the
interface is now consistent across platforms Although you couldcreate cross-platform apps with REALbasic prior to this, the
actual IDE was quite different between the Windows and
Macintosh versions If you are a Windows developer who tried
RB 5.0 and was disappointed with it, you should give RB 2005 achance Your experience will be totally different
The IDE makes it extremely easy to develop applications withgraphical user interfaces (in fact, until RB 5.0, apps with GUIswere all you could create) It provides easy access to databasesand it's possible to write a client app that browses a databasewithout writing a single line of code
There are two versions of REALbasicStandard and Professional.The difference between the two is that with the ProfessionalEdition, you can compile your application in all three platforms,whereas in the Standard Edition, you can compile the
application only for the host environment Although it's officiallycapable of compiling on Linux, I've had success running it onFreeBSD, one of the Unix variants
Trang 20
In my opinion, the single most compelling reason to use
REALbasic instead of something like Visual Basic is that you cancompile REALbasic applications to run natively on Windows,
Macintosh, and Linux machines Whereas older versions of Basicwere interpreted, REALbasic is compiled It also makes use ofthe native operating system whenever possible so that
Macintosh programs act like most other Macintosh programsand most Windows programs act like other Windows programs
There are a lot of languages to choose fromsome closed-sourceand others open-source For example, there is that other cross-platform programming language, Java, for which there are high-quality and free IDEs
The advantage of programming in a modern Basic variant istwofold First, an awful lot of us have programmed in Basic
before, so the learning curve won't be too steep Second, Basic
is called Basic because it's supposed to be, well, basic In otherwords, even if you've never heard of Basic before, Basic is agood choice because it is easy to learn
REALbasic has taken a big leap in maturity in recent years, both
as a cross-platform development solution and as a serious toolfor programmers, so don't let the word "basic" fool you You canwrite very complex programs with it Although the best of
REALbasic is the cross-platform application development
potential, it also lets you pop the hood and get deep into theunderlying system and do whatever you want This book willfocus on the cross-platform aspects of REALbasic, but I will giveyou enough information to get you started in the more single-platform topics If you're a VB developer, you'll be familiar withDeclares; if you code in C++, you'll be interested in hearingabout writing plug-ins for REALbasic
Trang 21I'm not the type to gush I'm not an ideological platform freak
or a disciple for some clever and deliciously quirky scriptinglanguage somewhere All languages are good in their own way.Some are better than others at particular tasks In a lot of
situations, which language you use doesn't matter at all
Scrimping on allocating space in your brain to learn yet anotherlanguage is a perfectly acceptable reason to avoid learning anew language After all, learning is a good thing, but so is
spending time with your children
scale enterprise applications It if sits on the server, stick withJava If your project needs a responsive cross-platform
REALbasic is not a replacement for Java, especially for large-graphical user interface, REALbasic may be the perfect solution
Although REALbasic is relatively easy to program with, it's alsonot a scripting language It's definitely a programming
language In particular, it's statically typed and compiled Thismeans that there are some quick and dirty scripting tasks thatare better done in Python (or Perl or Ruby)
As for me, I don't like typing, so I am not particularly pleasedwith any extra typing I might have to do I really don't like
brackets of the sort used by JavaScript and Java, although theyare admittedly useful in certain circumstances For this reason,
I prefer Python for scripting and REALbasic for developing clientapplications When developing content management solutions, Iuse Java and Apache Cocoon on the server
If you're learning to program and you need to pick a language
to learn in, I can think of no better language than REALbasic.Java is a lot easier to learn if you already know Basic Python isgood, but it lacks an IDE with the polish of REALbasic;
therefore, it is not as easy to develop GUI applications in
Trang 22to design a user interface to provide a novice programmer withenough psychological gratification and sense of accomplishment
to give them the energy to overcome the obstacles and
challenges that are such an integral part of the programmingchallenge
Trang 23
document in the front-most window of application such-Experienced REALbasic programmers who want an updatedreference on the new features found in REALbasic 2005
A lot has changed with recent releases You need a
reference to guide you through all the new features and tohelp you negotiate the challenges of cross-platform
development
Visual Basic programmers who want to learn about
REALbasic and how to port applications from Visual Basic toREALbasic
If you fall into this category, you may have an existing
Visual Basic project you want to port to REALbasic so that itcan run on Macintosh and Linux machines You also may belooking for an alternative to Visual Basic 6.0 rather than
"upgrading" to the latest NET Microsoft twiddling
Trang 24There are even a few Java developers malingering in theshadows of the bookstore who, while deeply loving the
ever-proper, thoroughly stable and dependable Java, stilllong for something a little easier, a little quicker, maybeeven something with a little more gloss on the old user
interface
I'm sure there's even one or two Linux developers who are
frothing at the mouth at the chance to have a commerciallysupported rapid application development tool so that they canquickly create new Linux apps In fact I think REALbasic could
Trang 25I intend for this book to be helpful to both novice and
experienced programmers alike For the novice, I'll provide
enough background information about programming to get youstarted Although this isn't an introduction-to-programming
book per se, I will certainly keep your interests in mind For theexperienced developer, I will compare and contrast REALbasicwith Java and Visual Basic when it's enlightening to do so, and Iwill highlight any cross-platform "gotchas" you might encounter
Cross-platform application development carries with it someadded complexities that need to be exploredsome features work
in only one of the platforms or work somewhat differently ineach platform It is also likely that many readers will not haveaccess to all three operating systems on their desktop for
thorough cross-platform testing throughout the developmentenvironment As a result, I will provide as much information aspossible about the nuances of cross-platform development withREALbasic and help you avoid lengthy and tedious bug-fixing in
an effort to compile the program on all three platforms
Although REALbasic is flexible enough to let the programmerhave direct access to the underlying operating systems, of
necessity, this is done differently with each respective operatingsystem In many cases, the REALbasic developer will have
relatively deep experience in one platform, but much less
understanding of the others I will provide basic information onhow to use these tools to extend REALbasic, but space and timelimitations mean that I can provide only limited information
about the underlying operating systems and libraries that areavailable to you In other words, this is a book about
programming cross-platform applications in REALbasic It is not
a book about programming Macintosh, Windows, and Linux
operating systems
Trang 26controls available to programmers Because REALbasic is
extensible with plug-ins, there are several commercially
available plug-ins for REALbasic that add valuable functionality
I will also highlight the most useful of these third-party tools sothat you can evaluate them for your own particular
programming needs
Trang 27oriented, and event-driven programming language with singleinheritance Whew That just about sums it up If you knowwhat this chapter's first sentence means, then much of thischapter will be a review of familiar concepts If you have noidea what I'm talking about, read on
REALBASIC IS A LINE-ORIENTED, STATICALLY TYPED, object-If you are new to programming in general, or to object-orientedprogramming in particular, you should read this entire chapter
It will introduce you to the basic concepts and terminology youneed to know to make sense of the rest of the book In addition
to those introductory concepts, this section covers REALbasic'sintrinsic data types, built-in functions, and the steps required tocreate your own modules and classes
There's sort of a chicken-and-egg problem when writing aboutprogramming languages, especially REALbasic To get started,you need to learn some basics about the IDE, but to learn thebasics about the IDE, you'll need to understand some
fundamental programming concepts
In an effort to overcome this obstacle, I'll provide a brief
introduction to the IDE in the next section
Trang 28
The computer itself speaks in a language of numbersones andzeros I still find it remarkable all the things that we can do withones and zeros For a computer to work with these ones andzeros, it needs to be able to represent them, so it must have aplace to store and then find these ones and zeros when it needsthem Then the computer can perform a calculation on them Itcan add them together or subtract them or do some
combination and come up with more ones and zeros Ones andzeros are meaningful and they represent meaningful things Insome cases they represent numbers, whereas in other casesthey represent letters and words Basically, we can say thatcomputers can store information and perform calculations on(or process) information
In a procedural programming language, these two distinct
activities are clearly separated Constants and variables storedata and subroutines, and functions perform some kind of
calculation on the data In object-oriented programming, thisdistinction becomes a little more muddy because a class
represents a collection of constants, variables, subroutines, andfunctions Whereas constants can refer only to values (known
as scalar references), variables can be one of two types: a
scalar, which refers to a value, or the variable can be a
reference to an object (An object is an instance of a class; I'llexplain this in more detail soon.)
When we say that REALbasic is an object-oriented language,what do we mean? A programmer may tell you that it meansthat REALbasic isn't a procedural or imperative programminglanguage, and she would be absolutely right Of course, youmight be saying, "So what does that mean?" The differencebetween object-oriented programming and procedural
programming is twofold In part, it's a different way of
organizing the information and instructions that are used to
Trang 29organizes the instructions and the information into things calledclasses These classes describe the instructions and the
information that go together to get these tasks done
REALbasic takes a practical approach to all of this and it
incorporates procedural-type programming and object-orientedelements In its attitude and the terminology used, it's all
object-oriented
Trang 30
Terminology used to describe programming languages varies bylanguage Although similar concepts exist in all object-orientedlanguages, they don't all share the same set of features andfrom time to time refer to things using different terminology orthe same terminology with a slightly different meaning
REALbasic is no different Before getting started, I want to
provide a quick preview of the terminology I will be discussingthroughout the rest of the chapter
Programming code in REALbasic is organized and presented in ahierarchy When you create an application in REALbasic, youstart with a project All the programming code that you write forthe application is stored in this file A project consists of a
collection of modules and classes
Project
Module
ConstantsPropertiesMethodsSubroutineProgramming codeFunction
Trang 31ConstantsPropertiesEventsProgramming codeMenu handlers
Programming codeMethods
SubroutineProgramming codeFunction
Programming code
In this list, you can see that a project is made up of modulesand classes Modules and classes represent two differentapproaches to programming: procedural and object-oriented.Although REALbasic is a modern, truly object-oriented
programming language, it retains elements of proceduralprogramming features when it makes sense in order to makethe process of writing an application simpler and more
streamlined
Trang 32REALbasic uses what is traditionally thought of as object-oriented terminology to describe modules If we were purists,
we would not say that modules have properties or methods.Instead, we would refer to them as global variables or
subroutines and functions Regardless, the folks at REALbasichave opted to use object-oriented terminology for all aspects ofthe language, so that's what I will do as well
Classes and modules are made up of things such as constants,
properties, and methods, and I will refer to them generically
as members A particular method implemented in a class is a
member of that class, as is a property that has been declaredfor that class
I said earlier that programs can either hold data or process
data Data can be held in memory as a constant or a property.Methods are where the data gets processed
All the programming code you write will be written in a method.Methods come in two flavors: functions and subroutines
Functions and subroutines are composed of a series of
statements, which serve as instructions to the program that tell
it the kind of calculations to perform on data
In addition to methods, classes implement events and menuhandlers, which are basically methods with some special
oriented programming
Trang 33For you to get a sense of how REALbasic works and how
powerful it can be, I want to quickly step you through your firstREALbasic application I am averse to "Hello, World" examples,
so I've come up with a better idea Your first REALbasic
application will be a web browser Don't fret It really is thateasy
When you launch REALbasic, it will launch a new untitled
project by default (see Figure 2.1) In the Project tab of the
main window, you'll see three items listed: App, Window1, and MenuBar1, as shown in Figure 2.1 These are three
classes that are part of every REALbasic application
Figure 2.1 The default "Untitled" project
Window.
[View full size image]
Trang 34programming What's important to understand now is that aclass represents a group of code that performs a specific task
The Window1 class is the programming code that manages the primary window in the application MenuBar1 handles the
Trang 35another for editing the code You can switch between modes bypressing Option=Tab, or clicking the Edit Mode button in the
toolbar for Window1 By default we'll be in the Window
Editor's Layout Mode You'll know you're there if the panel is
Trang 37
so that you can actually do something Controls are user-interface elements that users interact with For this project, wewill need three controls All three of them will be found in the
Controls pane in the left column.
The first thing to do is find the PushButton control in the list,
which is in alphabetical order Click it and drag it to the window.Just drop it anywhere for now
You now have a button on your Window with a caption that
reads Untitled To give it a better caption, look in the
Properties pane and find the Caption property in the
Appearance section Click where it says Untitled, and the EditField will become highlighted Type in the word "Go!" or
whatever word you want to use and press Return
Your button should now say "Go!" You'll want the button
positioned in the upper-right corner of the window, so select itand drag it up and to the right Keep dragging it until you seegreen guidelines You should reach a point where there is ahorizontal guide on the top of the button and a vertical guide tothe right of the button These guidelines help you to positionyour controls consistently, according to design guidelines
established by the operating system It's a good idea to usethem and follow their advice
Now that we have a PushButton on the window, we'll need an
EditField Find the EditField in the list of controls and drag it
onto the window just like the button Drag it to the upper-left
Trang 38will ensure that the EditField is positioned at the same level as the PushButton and that everything looks nice There's no caption to change for the EditField, so we're done with it for
now
Now, find the HTMLViewer control in the list of controls and
drag it to the window Drop it in the center Notice that everytime a control is selected, it is highlighted, and little white
boxes appear in the corners and in the middle of the sides Youcan use these selection boxes to make the control bigger bydragging them around The guides will help you here, too
When it is as big as the guides say it should be, turn to the
Properties pane You will see four CheckBoxes in the
Position section of the Properties pane Check all of them: LockLeft, LockTop, LockRight, and LockBottom This tells
REALbasic that the HTMLViewer should get larger as the
window gets larger Recall that earlier when we were examiningthe window, we made sure that it was expandable and had a
Maximize button.
So far, so good Now for some code
Double-click the PushButton labeled "Go!" and you will be switched to the Code Editor In the left column you'll see the
Code Editor's Browser with a list of all kinds of things You
should see an item called PushButton1, and right beneath it is the word Action, which should be highlighted.
Events
This is the Action event of the PushButton, and we're going
to instruct the PushButton on what it is supposed to do when
someone clicks it REALbasic is an event-driven language Thismeans that much of what your REALbasic program does is inresponse to a user's interaction with your application In this
Trang 39You have just told the HTMLViewer1 control to execute the
method called LoadURL EditField1.Text is a parameter that you
pass to HTMLViewer1 to let it know which page to load In this case, it takes the content of the EditField1 control and uses
that as the URL (web address) of the page to load
Whereas HTMLViewer1.LoadURL refers to a method, EditField1.text
refers to something else, called a property EditField1 is an instance of the class EditField, and EditField1.text is a property
of the class instance Later on in this chapter I'll cover methodsand properties in more detail, but for now let it suffice to saythat a method is an instruction to a computer to perform sometask, and a property represents a value of some sort In thiscase, EditField1.Text represents the value of the text that the
Trang 40Voila! You've created a web browser
If it doesn't work as planned, that's okay Take a look and makesure that you have typed everything exactly the way I said totype it in If the program is generating an error, a small windowwill pop up describing the error Possible errors might include
clicking the "Go!" button when the EditField contains no text,
or your program may generate an error if you try to run it andyou are not connected to the Internet
Now that you've had a taste of how easy it is to write a
REALbasic program, it's time to look at some of the details ofthe REALbasic programming language and how to create classesand modules of your own