Windows 7 / interview: alex restrepo / report writers / rectcontrol

Published by DesignWrite U.S. $16.99 NOV/DEC2009 i s s u e 8.1

teaching programming karel: the rb robot by andy dent

Going to Colorado: RB Summit 2009 by geoffrey a. rabe

making rb plugins by christian schmitz 2%!,3ERVERISTHEIDEALDATABASEFOR2%!,BASICDEVELOPERSWHOWANTTOCONVERTASINGLEUSERDATABASETOA MULTI USERONE)TgSFAST HASASMALLFOOTPRINT ISHIGHLYRELIABLE ANDRUNSON7INDOWS -AC/38AND,INUX

4RY2%!,3ERVERTODAY

a"ESTSUPPORT

a4OTALLY#ONSISTENT

a%ASY)NSTALLATION

a3IMPLE0RICING

a%ASY-IGRATION

a#RYSTAL#LEAR,ICENSING

$OYOUFEELTHENEEDFORSPEED &AST EASYINSTALLATION !TITgSCORE 2%!,3ERVERUSES31,ITE THEMOST -OSTDATABASESERVERSREQUIREMODIFYINGCONFIGFILES POPULARDATABASEENGINEINTHEWORLD7HENANEW ANDMESSINGWITHTHECOMMANDLINE.OT2%!, FASTERRELEASEOF31,ITEBECOMESAVAILABLE 2%!, 3ERVER*USTDOUBLE CLICKTHEINSTALLERANDYOURSERVER 3ERVERBENEFITS WILLBEREADYFORUSEINUNDERONEMINUTE

9OURDATAISSAFEANDSOUND &REETO$EVELOPERS 31,ITEISNEARLYINCORRUPTIBLEANDWEHAVENgTHADA 4HE2%!,3ERVER$EVELOPER%DITIONISCOMPLETELY REPORTOFACORRUPTEDDATABASE!ND JUSTINCASE FREEANDENABLESYOUTODEVELOPANAPPLICATIONBASED 2%!,3ERVERHASBOTHAJOURNALENGINEANDAUTO ON2%!,3ERVERWITHOUTPAYINGANYLICENSEFEES MATICBACKUPSYSTEM UNTILYOUDEPLOYYOURAPPLICATION

WWWREALSOFTWARECOMDOWNLOAD NOV/DEC2009 i s s u e 8.1

2%!,3ERVERISTHEIDEALDATABASEFOR2%!,BASICDEVELOPERSWHOWANTTOCONVERTASINGLEUSERDATABASETOA MULTI USERONE)TgSFAST HASASMALLFOOTPRINT ISHIGHLYRELIABLE ANDRUNSON7INDOWS -AC/38AND,INUX

THE MAGAZINE FOR REALBASIC® USERS 4RY2%!,3ERVERTODAY REALbasic Developer is not affiliated with REAL Software, Inc. a"ESTSUPPORT a4OTALLY#ONSISTENT FEATURES a%ASY)NSTALLATION a3IMPLE0RICING 13 RB Summit 2009 by Geoffrey A. Rabe RB Summit 2009 In September Geoffrey attended the RB Summit in Boulder, Colorado, and a%ASY-IGRATION 13 he provides us with his report. a#RYSTAL#LEAR,ICENSING 19 Interview: Meet Alex Restrepo by Marc Zeedar Alex is famous for creating the impressive CustomEditField—a text editor

Interview control built entirely with REALbasic code out of a canvas. 19 23 Making RB Plugins by Christian Schmitz $OYOUFEELTHENEEDFORSPEED &AST EASYINSTALLATION Have you ever wondered how to make a plugin for REALbasic? Christian !TITgSCORE 2%!,3ERVERUSES31,ITE THEMOST -OSTDATABASESERVERSREQUIREMODIFYINGCONFIGFILES adapts his talk from the 2009 RB Summit and provides us with an overview POPULARDATABASEENGINEINTHEWORLD7HENANEW ANDMESSINGWITHTHECOMMANDLINE.OT2%!, of the process. FASTERRELEASEOF31,ITEBECOMESAVAILABLE 2%!, 3ERVER*USTDOUBLE CLICKTHEINSTALLERANDYOURSERVER RB Plugins 3ERVERBENEFITS WILLBEREADYFORUSEINUNDERONEMINUTE 23 30 Karel, the REALbasic Robot by Andy Dent Karel is a virtual robot that has been used for decades to teach 9OURDATAISSAFEANDSOUND &REETO$EVELOPERS programming. Andy created a version of Karel with REALbasic that uses 31,ITEISNEARLYINCORRUPTIBLEANDWEHAVENgTHADA 4HE2%!,3ERVER$EVELOPER%DITIONISCOMPLETELY RBScript to program the robot. REPORTOFACORRUPTEDDATABASE!ND JUSTINCASE FREEANDENABLESYOUTODEVELOPANAPPLICATIONBASED 2%!,3ERVERHASBOTHAJOURNALENGINEANDAUTO ON2%!,3ERVERWITHOUTPAYINGANYLICENSEFEES Karel Robot MATICBACKUPSYSTEM UNTILYOUDEPLOYYOURAPPLICATION 30

REALbasic Developer (ISSN 1540-3122) is the ultimate source for tutorials and advanced techniques for programming with the REALbasic language. REALbasic Developer is published bi-monthly (six times per year) by DesignWrite, PO Box 872, Lafayette, OR 97127. Subscription Rate: Annual subscriptions are $49.99 (order at http://www.rbdeveloper.com/subscribe/). Customer Service: For changes of address, go to . For other customer service issues, see WWWREALSOFTWARECOMDOWNLOAD . Back Issues: Previous issues may be ordered at . Printed Issues: Issues printed in full color may be ordered at .

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 3 THE MAGAZINE FOR REALBASIC® USERS COLUMNS

5 Source Code: A word from the Publisher Marc Zeedar

Year Eight begins.

41 Beginner’s Corner: For those getting started Marc Zeedar

Part 1 of learning about controls, beginning with RectControl, the parent of all other controls.

45 From Scratch: A project from start to finish Brad Rhine

Starting a new project, ClipSaver.

48 BKeeney Briefs: The REALbasic developer’s life Bob Keeney

Exploring database reporting tools.

51 Databases for REAL: Learn to use databases Paul Lefebvre

How to use REALbasic’s new built-in reporting tool.

News, Reviews, Etc. Advertiser Index Hacker (comic) ...... 7 Association of REALbasic Professionals arbp.org 55 REALbasic News ...... 8 ChartDirector Plugin monkeybreadsoftware.de ...... 32 Windows 7 10 DynaPDF Plugin monkeybreadsoftware.de 38 SQLite Migrator 11 Eat Big While Eating Lean eatingbig.com ...... 55 Bento 3.0 12 Monkeybread Software monkeybreadsoftware.de ...... 25 RBDArchive 1-7 rbdeveloper.com 55 REALbasic Developer Magazine rbdeveloper.com ...... 56 REAL Software realsoftware.com 2

4 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Source Code

Thoughts from the Publisher by Marc Zeedar [email protected] Year Eight Begins

This issue marks the beginning arriving to me in a week or so and I’ll begin At a Glance of a new year of REALbasic Developer shipping out orders in mid-November. magazine. I have no more insight into the The 338-page book contains the complete RBD#8100 future than you, but I’m hoping the new contents of Year Seven of the magazine year will bring some fun developments. (issues 7.1-7.6) in print form, so it makes About the Author: For instance, there are some interesting a great archive. When RBD publisher Marc technologies in the works in mobile applica- Zeedar was a kid he used to tions and I would love to see a way to create In This Issue create magazines just for fun. iPhone apps with REALbasic.... Did you miss the REALbasic conference Now he’s doing it for a living! in Colorado? From all reports, it was a Year 7 Printed Book Available success, though of course much smaller If you didn’t pre-order your RBD Archive than the much-missed REALWorld in Volume 7, you can still order it for a 25% Austin (hopefully that will be back once percent subscriber discount. The printed the economy gets better and more people books have been ordered and should be are able to attend). But in the meantime Geoffrey Rabe attended the Colorado summit and writes about what went on so you can live vicariously through his experiences. At the conference MonkeyBread Software’s Christian Schmitz gave a presen- tation on creating plugins for REALbasic and he was kind enough to condense his talk into an article for us. You unfortunately can’t use REALbasic itself to create plugins (that is a much-desired feature request), but if you’re curious about the process, this is an excellent overview. One of my favorite custom controls for REALbasic is Alex Restrepo’s CustomEditField, so I was delighted to interview him for this issue. Of course our main feature is on Andy Dent’s rbKarel program: it’s a REALbasic version of the classic Karel robot, which is designed for teaching programming. Students control the robot with a simple language (implemented via RBScript) and learn about logic. Definitely a fascinating project! In our columns, I begin a series on basic controls in REALbasic, while Paul and Bob write about database reporting, and Brad starts a new clipboard manager project in From Scratch. Figure 1: Volume 7 of RBD Archive is now available in printed book format. Enjoy!

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 5 REALletters o p i n i o n & f e e d b a k is published by DesignWrite, P.O. Box 872, Lafayette, OR 97127-0872 dragging files to open you’ve apparently dragged into the IDE. and has no affiliation with REAL Software, Inc. Did I miss it [in your Beginner’s Corner I’m wondering what other kinds of goodies column in RBD 7.6 covering drag-and-drop] I can drag onto the IDE without causing the Publisher & Editor-in-Chief or did you not cover launching an app by world to slide into the nearest black hole. Marc Zeedar [email protected] dragging a file on top of it? I kept seeing And then, what can I do with them? Does how to accept drops onto controls once the this mean I can skip reading files for small Editorial Board app was launched. I guess, if the app will bits of information I often store in diction- Joe Strout [email protected] accept a dropped file on its icon, one would aries or lists? That would certainly simplify need to check if it were already open and coding, as your line of code illustrates. Erick Tejkowski [email protected] could accept a second (or more) file? Harris Paul Managing Editor It might be worth an article (or maybe Marc Zeedar [email protected] I hadn’t thought of explaining that, but it’s a sidebar) on the Random class. It didn’t easy. But it’s not obvious and should be originally exist as part of REALbasic—but News Editor explained, so here goes. First you go to the they added it and rnd now exists mostly Marc Zeedar [email protected] AcceptFileTypes property of your App and set for compatibility with old programs (and the file types your program will support. other ). Reviews Editor Then, in your App’s event, OpenDocument Dave Mancuso [email protected] you’ll get passed a folderItem pointing to As for my use of the imported text file,Words , any dropped files (they’ll each drop one I should have mentioned that in my expla- Copy Editors at a time, even if multiple are dropped in nation. Importing files into your REALbasic one go). It is up to you to handle the actual project is a terrific way to embed content in Toby Rush [email protected] opening of the files, checking to see if they your application. (You can either drag them Scott Griebel [email protected] are already opened, etc., but that’s fairly into your project window or use the Import simple. In my apps, each window is a docu- command on the File menu.) You can import Advertising Coordinator ment and has a folderItem property that text, sound, or picture files. Just remember Marc Zeedar [email protected] is that file’s location on disk, so it’s just a that the file is not actually embedded in your matter of looping through all your open REALbasic project file—it is onlylinked to Webmaster document windows and comparing the the original. So you still need the original file Marc Zeedar [email protected] dropped folderItem to the each window’s when you compile (important if you move folderItem—if they match, the file’s already your project to a different computer). It is Layout & Design open, so you can just bring that document embedded in your final app, though, so you Marc Zeedar [email protected] to the front (via a window.show command) don’t need to send that file with your app. and you’re all set. Once the file is imported, you can access Cover Art it by name throughout your REALbasic project. Another tip: if this imported file Jeff Quan [email protected] More Drag-and-Drop is something you wish to change periodi- Hi Marc. As usual, I greatly enjoyed your cally, you’ll need to recompile your app Artwork last issue. In particular, my attention was to get the change to pass through, so it’s Dan Wilson (Hacker, Caricatures) [email protected] called to a couple of “throw-away” items in not always ideal. It may seem easier to your Drag-n-Drop article. I’ve used the Rnd import a text configuration file into your Columnists function on many occasions without giving app than messing with reading in a folder- Paul Lefebvre [email protected] it a second thought since it’s used in Fortran, item—but each time you change the config , and many other languages I’ve you’ll need to recompile your app. So you Toby Rush [email protected] used before I became a convert to RBism. I need to decide in advance which method Brad Rhine [email protected] did not realize, however, there was a Random is appropriate for your specific situation. Bob Keeney [email protected] Class. Even though I do read the manuals, I If it’s a file that rarely changes, importing guess I just skipped over it confusing it with it can be easier. the function. The other throw-away was your use of “words” in the code line: Send your Letters to the Editor to REALbasic® is a registered trademark of REAL Software, [email protected]. You must dim text() as string = Inc. It and other trademarks used within this publication are include your full name and valid email the property of their holders and are used only for editorial split(replaceLineEndings(words, endOfLine), purposes with no intent to infringe. REALbasic Developer, endOfLine) address, but we will withhold publishing your name on request. All letters may be the REALbasic Developer logo, and the Arby mascot name This was confusing, since I could not see and icon are trademarks of DesignWrite. edited for content or length, and become where “words” was defined. I opened your Contents Copyright © 2009 by DesignWrite. the property of REALbasic Developer. All Rights Reserved Project file, and lo, I find it’s a text file

6 November/December 2009 | REALbasic Developer | www.rbdeveloper.com How to Download Source Code

Article resources available at: http://www.rbdeveloper.com/browse/ The “browse” website gives every RBD article a permanent web page where you can find links to downloads, updates and corrections, and more. Note that downloads include a modification date. Every article in REALbasic Developer includes an “RBD number” at the beginning presented like this: RBD#1234

To retrieve an article’s resources, follow these steps:

Step 1: Go to the RBD website (http://www.rbdeveloper.com/browse/).

Step 2 (find article by number): In the Get Article search field type in the RBD number of the article you need.

Alternate Step 2a (find article by issue): Find the issue you’d like to Browse and click on the link for that issue’s Table of Contents.

Alternate Step 2b (download all resources): On an issue’s Table of Contents page, there’s a link to a file which includes all the downloads for a particular issue in one large archive.

HACKER by Dan Wilson

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 7 REALBASICNEWS e v e n t s & e l e a s e s

RBD#8101 fp Plugin 2.5 This way you can print files on a The code has been minimally Price: Version 2.5 adds the Beta printer directly. Also we added tested on Windows and $50 Function, the Incomplete Beta several new Cocoa classes but not on any Mac platform. Website: Function, the Error Functions, including a better integration Steve is eager for code or scripts http://ramblings.aaronballman.com/book the Exponential Integral, the in the future Cocoa REALbasic to share in the project and Fresnel Integrals, and the target. For compressions we not asks that you email him about Confluent Hypergeometric only have the zlib compression getting your code added as he REALbasic 2009 Release 4 Function. Using a custom fp engine, but now also the BZip2 hasn’t quite decided exactly REAL Software, creator of multi-precision engine, fp engine. The plug-ins require what checkin access any new REALbasic, a cross-platform Plugin for REALbasic adds two REALbasic 2006r4 or newer. members will have to the software development tool for new data types, BigInteger and Also required are 500 MB hard repository. Currently snippets Mac, Windows and Linux, has BigFloat. Except for available disc space and around 64 MB of of script code such as class announced the availability of memory, there is no limita- RAM in addition to the require- definitions are currently held REALbasic and REAL Studio tion on the size of a BigInteger. ments of REALbasic and your in constants mostly because 2009 Release 4. This release BigFloat is a multi-precision operation system itself. While it’s a nice easy place to edit offers 97 improvements and floating point number. You all plug-in parts compile on them. He hopes to later have 39 new features, including a can set both the internal preci- Mac OS X (universal), Linux, a separate scripts directory new report editor, which will sion and the decimal output and Windows, each function where simple text files can be be included in all versions of precision for BigFloat, with no may depend on additional added. He also points out that REALbasic, and build auto- limitation except for available system requirements to work the project currently uses Edit- mation, a feature exclusive to memory. fp Plugin itself allows successfully. Plugin licenses are Fields and asks that if you check REAL Studio. The new report you to construct programs available for components or for in code not to resolve them to editor allows developers to which can handle the two new the complete collection. If you TextFields and TextAreas as visually create a layout for data types much like doubles buy a current license, you will he’d like to leave them there for printing by dragging and drop- and integers are handled. To a get free updates for one year. backward compatibility until ping labels, fields, images and large extent the new data types After that year, you can update Cocoa comes out. more. Reports can be created to can be freely used with the +, -, your license to cover an addi- print a single page or multiple *, and / operators, and can be tional year. Product: pages. The layout is divided into RBScript Open Source Site used in comparisons. And most sections (header, body, footer of REALbasic’s functions have Product: Platforms: as well as grouping sections Monkeybread Software Plugin for All been overloaded to take the REALBasic for reports that have sorted new data types, where it makes Price: data). “Reporting has been the sense to do so. Also fp Plugin Platforms: Free most requested feature from OSX / WIN supports the Gamma function Website: our users and we are pleased and the Bessel functions. Price: http://code.google.com/p/rbscriptjottings/ to deliver,” commented Geoff 200 Euros (complete set); 20 Euros and up (per component) Perlman, REAL Software Product: Founder and CEO. “The report fp Plugin 2.5 Website: http://www.monkeybreadsoftware.de/realbasic/plugins.shtml Ramblings on REALbasic editor will allow users to print Platforms: Book from any source including All Aaron Ballman has edited and text files, arrays, databases, Price: RBScript Open Source updated a compilation of over etc. and since the interface is Freeware Site 200 of his best blog entries, open any database supported Website: Steve Garman has started including new content that’s by REALbasic can be used.” The http://homepage.mac.com/delaneyrm/fpPlugin.html a new open source site for never been seen before, into a new build automation feature RBScript which he hopes will new book. In it you will find tips of the Project Editor is only become a center for the sharing and tricks for REALbasic that available in the REAL Studio MBS Plugins 9.7 of RBScript context classes are not available in any other Edition. With Build Auto- The MBS plug-in comprises and useful scripts or snip- source. Weighing in at around mation developers can now a collection of several plug-in pets. Currently it consists of 550 pages, Ramblings on automate the most common parts which extend the a single project with a couple REALbasic covers topics such functions of building their REALbasic development envi- of mini-projects inside it. One as the REALbasic language, applications without having to ronment with 1,200 classes demonstrates a context that design patterns, user experi- write IDE scripts. The complete featuring over 26,000 docu- allows access to reading/setting ence, and Windows-specific list of improvements and new mented functions. This release data in ListBoxes and Progress- technologies. features in this release can be adds two new plugin parts. Bars but will later be extended found in the release notes in the One to integrate the mobileMe for lots more types of RectCon- Product: product download section. Book: Ramblings on REALbasic (.mac) features into your appli- trol. The other mini-project cation and another one to showcases a Date class which Platforms: Product: All REALbasic and REAL Studio 2009 control the CUPS printing does many of the things we Release 4 engine on Mac OS X and Linux. expect from a RB Date object.

8 November/December 2009 | REALbasic Developer | www.rbdeveloper.com REALBASICNEWS e v e n t s & r e l e a s e s

Platforms: All re-write of code she wrote and PictureEffects plugin, now Labyrinth, Shape Distort, released almost seven years ago supporting use of up to 8 Bilinear Scaling and Stretch. Price: $1495 (REAL Studio), $299 (Pro), $99 when new to REALbasic. It’s CPU cores at once, allowing (Personal for OSX/Win, free for Linux) main purpose was to provide REALbasic to compete with Product: PictureEffects 6.7 Website: an event that signaled the end best speeds of Image processing http://www.realsoftware.com/download of moving the thumb during that is out there. The Picture- Platforms: LiveScroll, something the RB Effects is a REALbasic plugin All slider does not support. This to do picture manipulation on Price: Dataflow/Graphical useful when you wish to give 32bit images. The plugin is $199 (for all plugins), $45 (upgrade) Programming the user some live numeric or supported on MacOS Classic, Website: Framework visual feedback of the slider’s MacOS X, Win32 and Linux http://www.einhugur.com/ John Balestrieri of Tinrocket, current value but perform a target platforms. Main features: LLC is releasing the first version final action that takes too long Red Eye Reduction, Bright- of a REALbasic framework to perform while the user is ness, Contrast, Sepia, Color instaplaylist 1.0 for creating, editing, and actually moving the slider. This Filter, NTSCColorFilter, Hue, Bains Software, a longtime running dataflow program- version provides a ChangeFin- Saturation, Lightness, Desatu- developer of Mac software, is ming systems—also known ished event that is called when rate, Gamma, Blend, Rotate, proud to announce the release as graphical programming the Mouse button is released Diffuse, Interlace, Flip Hori- of their first iPhone app: insta- systems. Here’s a screenshot after dragging the thumb. This zontal, Flip Vertical, GrayScale, playlist. instaplaylist is the of the framework running event should not break any Invert , Sharpen, Smooth, universal remote for music. It in a REALbasic applica- existing code as for a “dead” Blur, MotionBlur, Gaussian allows users to quickly create tion (http://cargobay.tinrocket.com/Rb/ scroll (LiveScrollChangeFin- Blur, Edge Detect, RankOrder- a playlist of YouTube music Dataflow/Media/Screen-shot-2009-09- shed = false), the ValueChanged Filter, Emboss, Pixelate, Mean videos from their iPhone or 23-at-11.16.49-PM.jpg). This is a event is still called normally, Removal, Invert,Contrast iPod touch and enjoy them similar type of system that’s and then the event immedi- Stretch, Equalize, Replace on any computer on the same used in other software pack- ately afterwards. That event Color, Custom 3x3 matrix WiFi network. The videos play ages, such as Apple’s Quartz order ensures the same code filter, Oil Paint, high quality on the user’s computer while Composer, Cinema 4D’s would work for both live and Bilinear Scaling, Stretch, Polar they control playback from Xpresso, and Prograph CPX. “dead” scrolls. This class also Coordinates, Shape Distort, their iPhone. Videos continue The need for this software arose supports using the Mouse- Barrel Distort, Twirl, Wave, to play even if the user exits from another project John is Wheel to change the slider Water Drops, Surface Wave, instaplaylist or turns off their working on where he needed value on all platforms (it’s not PageCurl, TrimPicture, Create iPhone. With a tap of their to patch together several image normally supported on the Mac Chroma masks, Render Clouds, finger, the user can: Play/pause, processing modules in GUI in the RB Framework). Also Render Wood, Render Marble, Jump to the previous/ environment. This seemed like now holding the shiftkey down Render Textile, Render Laby- video, Add and remove videos, the best solution. Now he can when the arrow key results in rinth, Map, ChannelMixer and Reorder their playlist, Adjust now layout and edit the inter- PageSteps instead of LineSteps a IProgressHandler Interface the volume, and more. No soft- connection of modules. When for the delta. The big change support for every filter. The ware installation is required. a node is selected in the editor with mousewheel support is PictureEffects also supports instaplaylist is compatible view, a page-panel reveals the that the ChangeFinished event masking for most of the effects. with any computer (Mac or configuration options for that will also fire when user stop The following effects have PC) with a modern browser node. He’s releasing this frame- moving the MouseWheel for been accelerated on MacOS installed. Minimum require- work hoping that others will a set time period, unless you X, Windows, and Linux plat- ments: WiFi network, iPhone find it useful as well. turn it off. forms to make use of up to 8 or iPod touch with OS 2.2.1 or CPU cores: Rotate, Bright- later, and Computer capable of Product: Product: ness, Contrast, Sephia, Color visiting YouTube. Dataflow Programming Framework UltimateSlider 2.0 Filter, Grayscale, Desaturate, Platforms: Platforms: Hue, Saturation, Lightness, Product: instaplaylist 1.0 All All Invert,Invert,Contrast Stretch, Price: Price: Equalize, Replace Color,Gamma Platforms: Free Free , Blend, Flip Horizontal, Flip iPhone Website: Website: Vertical, Sharpen, Smooth, Price: http://cargobay.tinrocket.com/Rb/Dataflow/Dataflow_DR25.zip http://mysite.verizon.net/vzezdg8x/sitebuildercontent/ Blur, Edge Detect, Emboss, $0.99 sitebuilderfiles/UltimateSlider2_RBP.zip Interlace, Mean Removal, Website: Custom 3x3 matrix filter, Map, http://www.bainsware.com/instaplaylist/ http://www.itunes.com/app/instaplaylist UltimateSlider 2.0 ChannelMixer, TrimPicture, Karen Atkocius has released PictureEffects 6.7 Create Chroma masks, Render the source for UltimateSlider Einhugur Software has released Clouds, Render Wood, Render 2.0. This Slider Subclass is a a breakthrough update to the Marble, Render Textile, Render

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 9 REALREVIEWS t o o l s & p l u g i n s

Windows 7 Dave Mancuso IN BRIEF Product same slow performance I have with for better contrast on my screen. The Windows 7 Vista. The installation, however, Personalize settings are new, and the Windows Manufacturer Vista was a decent operating system. proceeded cleanly and smoothly. rotating desktops are a nice touch. Microsoft Its bad reputation seems to be a More importantly, it installed more You can set multiple desktop pictures Price lesson to developers: don’t always quickly than previous versions of to change on a timed basis of your Home Premium give users what they want. Vista Windows. I’ve read of issues with choosing. It’s a nice touch, although $109.99, Professional addressed every note, every gripe, and Windows 7 installs, but I experienced changing the screen upon each restart $149.99, Ultimate every bad PR story about Windows no problems at all, even on my virtual would be even nicer. $199.99 (OEM versions) XP. It was made to be safe, sleek, hosted OS. This could be the 4 GB Dragging a window to the side of and sophisticated. Unfortunately, of RAM in my laptop, although my the screen snaps it to a half screen Contact Info http://www.microsoft.com/windows/windows-7/ Microsoft bit off more than it could Parallels virtual machine is config- zoomed window. It’s easy to snap two chew. Vista’s huge development team ured for a recommended 1 GB of windows side by side on the screen, Pros Speed, interface had grand ideas but little substance RAM. Regardless, so far so good. a useful feature that’s surprisingly improvements, to show for it. The new WinFS file The 32 bit version of Windows easy to pick up and make a habit. This addresses most Vista system was dropped, as were other 7 booted in one minute and thirty cannot be understated, especially annoyances major features. The main priority seconds from a cold start. Reports for Mac users. This is the first time Cons became shipping Vista before soft- are that the 64 bit version takes that I’ve used a Windows feature Multiple prices and ware client contracts expired (and longer. More importantly, Vista’s that made me think “Why shouldn’t versions can be confusing, price not renewed by customers who had boot time on my laptop is excruci- it be this way? Why didn’t someone should be lower run out of patience). Vista became a atingly slow. When it does boot, it’s think of this before?” It’s a typical slow, cumbersome OS whose elegant incredibly sluggish for a few minutes Apple move to create a solution to a Rating (1.0-5.0): 4.2 features were buried under the until everything finishes initializing. problem you didn’t know you had, weight of its overhead. More annoy- Windows 7 is ready to use once only now it’s in Windows. Windows ingly, it infamously asked you for the desktop appears. Things don’t 7 developers have obviously made a permission to perform (seemingly) happen instantly, but they’re notice- paradigm shift in their user interface every simple little task you tried to ably snappy and responsive. design. Shaking a window to hide all perform. Vista, the powerful OS that The desktop itself is much lighter other windows is another nice touch. kept you connected and in control, and cleaner. I felt that Vista’s reputa- Information about these features got in your way. Vista was arguably and unfortunately Microsoft’s black sheep of the Windows family. Enter Windows 7. Microsoft’s main goal for Windows 7 was to lighten the load. It trimmed little used features and whole applica- tions like Windows Mail, Photo Gallery, and Movie Maker. It tightened up every performance feature in the OS, notably all Aero interface features. The goal and mantra for Windows 7 was to make it simple, snappy, and light. Users are supposed to get what they need with a minimum of muss and fuss. In a way, Windows 7 is the first real version of Vista, almost as if Vista were an early beta of what has now shipped on October 22. Windows 7 is available in both 32 bit and 64 bit versions. I opted for the 32 bit version (note that this was the Release Candidate from summer 2009, although the current tion was in large part undeserved, but can be found easily by exploring the final shipping version is virtually its dark, thick look certainly didn’t OS, or on the Microsoft website. In identical). I installed Windows 7 in help. Windows 7’s lighter default each case, features are easy to use a new Parallels virtual machine on theme is a huge improvement. In and remember, yet valuable for my . Since I wasn’t running fact, the first thing I did was to set everyday use. Windows natively, I expected the the window theme to be a but darker RBD#8102

10 November/December 2009 | REALbasic Developer | www.rbdeveloper.com REALREVIEWS t o o l s & p l u g i n s

IN BRIEF SQLite Migrator Dave Mancuso Product SQLite Migrator the application on both Mac OS Control Panel for my test database, Migrator, (Snow Leopard) and Windows 7 and then used SQLite to convert the Manufacturer SQLite LogicalVue Software from LogicalVue Software, is essen- (where the installation took less database to SQLite. The original tially a one-stop shop for conversion than six seconds). The interface is database was left untouched, always Price $49.95 of databases into SQLite format. pretty simple, with buttons (and a good thing. The new SQLite data- What kinds of databases? SQLite corresponding menu commands) base was cleanly made and worked Contact Info will transform, Access, FoxPro, to selects a database source and fine. Essentially, that was it. SQLite http://www.logicalvue.com/sqlite/sqlite.html MySql, Postgresql, MS SQL, and the destination. On OS X, I couldn’t get Migrator worked, and it worked Pros list goes on. The reason that SQLite the Source DB command to open simply, quickly, and accurately. Quick, simple, clean, effective Migrator is such a Swiss Army knife a dialog box, either an issue with LogicalVue has an online support kind of tool is that it can connect to Snow Leopard or an issue with my site, and I noticed a few features Cons None to speak of any database format that makes use own machine. On Windows 7, the targeted for future versions, mostly of ODBC for connections. The possi- dialog box opened with no problems. enhancements in how primary Rating (1.0-5.0): 4.5 bilities for this are very impressive. If Choosing commands was a bit slow keys, indexes, views, and tables a client wants you to remake an old but not bad, probably a Windows 7 are handled. The developer (Paul database for them, and the database issue (I’m using the beta). Lefebvre) has an active blog and is in Access, you’re not too far away Converting a database took a online presence, a key necessity for from a quick magic trick. Convert few steps, but went well. The PDF an application of this nature. The the database to SQLite with SQLite documentation, found in the SQLite application is priced at $49.95, and in Migrator and you can start building Migrator application folder, is invalu- demo mode will convert the first three something in REALbasic right away. able for running through the process tables and ten rows of a database. This could be very handy when you the first time. Note that in Windows That’s certainly enough to test a few need something quick. this application folder is in the C databases for conversion in your own Installing the app is pretty stan- drive’s Program Files directory. I situation. SQLite Migrator promises dard on Mac OS and Windows using set up the ODBC data source using to be a valuable tool in a developer’s the standard installers. I installed the Windows ODBC Administrator programming arsenal. RBD#8104

The 7 website deserves ects cleanly. There hasn’t been much in the two versions, or (dare I say it) one? Also, a mention as well. Microsoft reportedly spent online communities about Windows 7 and upgrade paths are confusing at best. It’s hard over 300 million dollars on marketing for REALbasic, although you may hear more by to tell how and if your copy of Windows is Windows 7, and it shows. The seven second the time you read this. Things definitely seem upgradeable to Windows 7 (this may be a demo videos on the site each showcased a to be workable. As a side note, REALbasic personal issue, since my Vista launch promo nice feature that you could use every day. looks pretty good running in a Windows 7 license has no upgrade path whatsoever). More importantly, they were quick, funny, themed environment. If you need a new license, places like Tiger and not afraid to have a little fun. Microsoft Windows 7 isn’t without annoyances. As in Direct or NewEgg are your most likely sources is trying not to take itself too seriously Vista, it notified me that I was missing anti- of new OEM versions of Windows 7 (Home with its approach, and it’s fairly successful spyware and antivirus software. I checked Premium $109.99, Professional $149.99, (although spending 300 million dollars to off Windows Defender for an easy answer, Ultimate 189.99). Upgrades, if you qualify, present this persona seems heavily serious but I installed the open source antivirus are more expensive than the OEM versions: on closer examination). It’s the first time I’ve software ClamWin instead of my usual AVG. $119.99 for Home Premium, $199.99 for seen some warmth for Windows that comes Windows 7 refused to recognize ClamWin Professional, and $219.99 for Ultimate. across as genuine. even after repeated efforts and multiple These websites, along with Microsoft’s site, The applications that come with Windows restarts. Perhaps I missed something simple, have charts detailing the features in each have been given facelifts as well. WordPad is but Windows 7 is all about not fighting the version. the most drastically different, with a Ribbon user. It’s also clear that some interface It’s clear that I think Windows 7 is a winner. interface a la Office 2007. Even Notepad elements are unchanged from older versions I’ve been a Mac user for twenty years, since seems a bit new, and Calculator is new for of Windows, making workflows clunky at System 6. I’ve been a Windows user since the first time since Windows 3.1, seemingly. odd times. Frankly though, Windows 7 is Windows 3.0 and DOS 3.3. This is the first Solitaire is new too. The only application a huge change to smoother, more organic time that I can say that Microsoft has an OS apparently left untouched is the venerable interface. The leftovers can be overlooked in that I could use on a daily basis as an alterna- Command Prompt, probably to appease the hopes that they’ll be steadily upgraded tive to the Mac OS. It’s the biggest upgrade DOS purists. over the next few years. from a usability standpoint since Windows The most important application to run on The one real annoyance with Windows 7 95. It fulfills the promise that Vista made. Windows 7 is arguably REALbasic. I used a are its versions. Having three versions (Home Finally, it makes me very interested in what demo copy of REALbasic 2009 Release 4. It Premium, Professional, and Ultimate) is Microsoft does next, and perhaps that’s the started smoothly, and compiled a few proj- better than Vista’s versions, but can’t it be most important thing of all.

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 11 REALREVIEWS t o o l s & p l u g i n s

Bento 3.0 Dave Mancuso IN BRIEF Product FileMaker used to do this with flat an active user community that shared Bento 3.0 story of Bento, file databases and a special “Lookup” files, templates, and ideas very well. The Manufacturer FileMaker’s personal database appli- field. FileMaker says that Bento is rela- The community was a secret killer FileMaker, Inc. cation, is an odd one. The rumor is tional, and the SQLite the databases feature of HyperCard. FileMaker is Price that it was originally intended to be are saved in is relational, but purists trying to do something similar with $49.00 single user, the database element of the iWork on the web differ. What’s clear is that Bento. It’s created a user community $99.00 five license application suite. At some point Bento gives you no power user mode for Bento with shared templates. family pack (web site the database was spun off into its to dig into the SQLite parts of the FileMaker has seeded the template download) own orbit. The database application database. A primary or key field can exchange with starter files, and slowly Contact Info (codenamed “Gluon”) became Bento, be made implicitly, but there’s no way the collection is being added to by http://www.filemaker.com/products/bento/ and FileMaker took custodianship of to control the database as you can do users. With the release of Bento 3, Pros it. It became an entry level cousin to by making your own in REALbasic. FileMaker hopes that the applica- Prebuilt templates, easy to start using, FileMaker Pro, but it was obviously a In addition, there’s no way to make a tion gains critical mass and that the integration with other very different beast. Bento is a nexus database that runs itself without the template area expands. Mac OS apps, online point for iApps, heavily integrated with host Bento application. It seems silly Designing and using libraries and community iPhoto, Address Book, and iCal. It’s to compare Bento with REALbasic’s templates are, as you might expect, Cons designed to become a home for all your database capabilities, but you might easy to do as long as you don’t need Lack of flexibility, data, trying to prove that the whole is look at Bento as a quick way to create a anything outside of the boundaries ambiguous relational database capability, greater than the sum of its parts. database for yourself. Could Bento be that Bento has set for you. Even lack of SQL support Bento autosaves like FileMaker used for some quick purposes instead within these rules, you can design Pro, but the reason is completely of taking the time to build a database new templates that are related to each Rating (1.0-5.0): 3.9 different. Bento isn’t document-based. in REALbasic? In contrast, there’s no other, getting much further than you It’s library-based. The libraries are comparison. Bento is very good at might think. displayed in the left panel of Bento’s doing what it does, but what it does At first glance, Bento seems like main window. Each library in Bento is very narrowly focused. REALbasic a database application that might could be considered a table in a SQLite is wide open in terms of flexibility if work in a pinch instead of creating database. In fact, the libraries are all you have a bit of time, and it lets you one from scratch in SQL. On further stored in a SQLite database hidden in dig into SQLLite all you want. examination, Bento is a tool for certain the user’s Library folder (Application One thing that Bento does nicely is kinds of things, but by no means for Support, Bento). You’d never know integrate with iPhoto, Address Book, everything. If you need what it does, this from using the application. and iCal. You can see data from these you’ll do very well with it. FileMaker Bento is all about the interface, and applications in Bento Libraries, and offers a free trial download to experi- the interface is all about giving you a manipulate their data from inside ment with Bento for thirty days. It’s turnkey solution. Bento is designed the Bento application. to hide you from the complexities of Be careful to read the anything to do with database design, documentation of you form, or function. do this. In some cases Bento has prebuilt templates in a Bento will modify data variety of styles. If you want a different in these other applica- style, Bento gives you the ability to tions, but not always. change the look of your forms at any Also, things you add to time, with a live transition to the new Bento for these other look that’s obviously based on Core applications will not be Image. It gives you both a Forms view added to their data sets. and a table List view, and will give you Bento tracks your extra both in the same window if you’d like. information and uses it Thus you can have a field list inside a as extended fields, but form. Adding a new field to the form does not modify original (and the Library) displays a dialog data in the other appli- box with numbered steps and expla- cations. You’ll need to nations for each step (Choose a Field study how Bento uses Type, Name the Field, and Options). data from other appli- It’s clear that Bento works extremely cations to get a feel for hard to help the regular user design it (and avoid messing databases. things up). It’s not completely clear if Bento is Apple’s HyperCard is flat file or relational. You can relate receding into the past fairly quickly, certainly worth a look, and perhaps a fields in two different libraries, but but one thing that HyperCard has was purchase if it meets your needs. RBD#8106

12 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Feature

by Geoffrey A. Rabe

RB Summit 2009 Visiting the Boulder, Colorado Conference

At a Glance Inspiring Apps, an independent Colorado firm that special- izes in writing custom software using REALbasic, and the Association of REALbasic RBD#8107 Professionals (ARBP), jointly sponsored a three-day Summit at Inspiring Apps’s offices in Boulder (see Figure 1), September 24-26, the first such REALbasic conference held Target Reader: in Colorado. Beginner The Summit began Thursday afternoon with a “meet-and-greet” during which our About the Author: hosts, Joe Strout and Brad Weber of Inspiring Apps, and ARBP President, Bob Keeney, Geoffrey began programming on outlined the sessions to be held the next two days. Following that, we broke for dinner a Radio Shack Color Computer, at several nearby restaurants on Pearl Street, a pedestrian mall that runs through down- back in the early-to-mid 80s. When town Boulder (see Figure 9). he could finally afford one, he On Saturday morning, Bob Keeney (who also writes the BKeeney Briefs column for bought a PC clone and VB3-6, but this magazine) had the first session, “Reporting Tools, Options, and Techniques” (see eventually wised up and moved to Figure 2). He mentioned that, at the last REALWorld Conference, there was only one such the Mac platform and REALbasic application to use for reporting, On-Target Reports, and that a good reporting tool was 2009r3. He’s much happier now! (All at the top of the list of feature requests received by REAL Software’s Feedback tool. But photos courtesy of Geoffrey Rabe.) one year later, there are several, in various stages of development, usability and support (see his column in this issue for more on that topic). He also discussed how making a print-out was one such way of “reporting” that many REALbasic developers use, and the various tools and controls for making print-outs that come with REALbasic. During the next session, we engaged in a live iChat with Geoff Perlman, CEO of REAL Software (see Figure 3). Many of his comments regarded the then-upcoming Release 4 of RB 2009. The transition of the underlying framework for Mac OS X from Carbon to Cocoa was mentioned, but was not going to be ready for R4, nor was an interesting-sounding new control, the Passcode Field, which would allow for built-in password-checking functionality, though they both would be in a future release. Related to Bob’s session, Geoff also showed a demo using the reporting tool now built-in to REALbasic, and as noted earlier, one of the most requested features. He also mentioned moving away from Type and Creator codes, long used by Macs to identify which programs could open which files, beginning with Tiger, to Uniform Type Identifiers, a much more useful way to do this. (A very informative article on Uniform Type Identifiers can be found at http://forums. appleinsider.com/showthread.php?s=&threadid=103219 if you’re interested.) The next several sessions and demos were all centered around databases, an area I’m no expert in, though the comments and discussion of the other participants left me wanting to know more. First up was Ryan Vail, of Inspiring Apps (see Figure 4). His

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 13 Figure 1: Taken Thursday, during the “meet-and-greet.” Brad Weber noticed the rainbow out of the window of the Inspiring Apps office and pointed it out to us, commenting on the frequently-changing nature of the weather here on the Front Range.

session, “SQLite Power Tools,” provided an introduction to the uses of SQLite, with many examples tied in with the REALSQLdatabase, documentation for which can be found within the Language Reference. Some pros mentioned in asso- ciation with this are that it’s free (i.e., it comes with RB), it’s cross-platform, and while not for use directly in the IDE, there is a Firefox plug-in available for development in the browser environment; a con that was mentioned was its user- interface. In addition, he went over the command-line client of SQLite3, which comes with the development tools, and provided a demo. He also showed demos for encrypting, backing-up, and attaching databases (e.g., shipping a program to a client with some default information set on a USB drive). Both attaching and detaching a database sounded relatively easy. However, importing an SQLite data- base to a MySQL database did not sound nearly as simple. The reference Ryan gave for this can be found at http://stackoverflow.com/ Figure 2: This are from the first session, on Friday (“Reporting Tools, Options, and questions/18671/ if you’d like more details. Techniques”) given by Bob Keeney, Pres. of the ARBP, co-sponsors of the Summit, However, I discovered another reference and frequent contributor to RB Developer. online (http://sqlite.phxsoftware.com/forums/p/941/4725.

14 November/December 2009 | REALbasic Developer | www.rbdeveloper.com I want to make a comment here which relates to the Summit specifically and to the REALbasic community in general. As mentioned several times, I don’t have nearly as much experience using RB as the other participants, and in fact I’m more of a hobbyist, while the others were all profes- sional programmers. However, I found the group to be very helpful and patient with my questions and comments. In fact, for a project I’ve been “working” on (more plan- ning than actual programming) I needed a custom control which I’ve tried designing myself with rather unsatisfactory results. However, as a result of my bringing this up with the group, the following day Bob Keeney had an excellent suggestion on a different approach I could take designing the control, and both Christian Schmitz and Joe Strout gave me a control they had whipped up in minutes. So what I’m getting at is that the RB community, from my experience and what I’ve seen online and in the REALbasic Developer magazine, Figure 3: This is from the second session (“Cocoa and Reporting Features in is very open and helpful to both new and REALbasic”) which was given by Geoff Perlman, head of REAL Software, via iChat, experienced programmers, and that these where he also discussed some of the changes/features of RB2009r4, which is now smaller events are well worth attending available. (That’s Joe Strout in the blue shirt in the foreground.) even if you’re not a full-time developer. (In a similar vein, I found the following large discussion on the topic, which — quote from a review of REALbasic 5 on aspx) which was easier for me to under- as mentioned above — was beyond my MacWorld’s site: Software-Development stand given my lack of experience with experience. But on the other hand, Seth Application Remains Top in Its Field databases. Verrinder, of BKeeney Software, Inc., led “When you commit to REALbasic, you Ryan’s session was followed by a demo, the next session, “OO Database Framework become part of an enormous base of smart, given by Brad Weber, of how even large and Introspection,” which was easier for dedicated, and friendly users who provide databases can be imported, encrypted/ me to follow. a variety of great resources, from books to decrypted, and zipped, which led to a message boards.” Now, back to the Summit....) Speaking of Joe, who is a frequent contributor to the RB community in many areas, he had the next session, “Profiling and Performance Tweaking.” Simply speaking, this topic relates to getting the most out of your code and the best perfor- mance of your application. One of his first points was on program optimization — “don’t do it yet” — wait until after you’ve profiled your code. How to do this? You can do it manually, using the Pause button at certain points in your application’s run, to check properties, variables, etc. You can also measure the time certain routines take by including profiling code before and after the run, using microseconds. In addition, Joe included some perfor- mance pitfalls to watch out for: with databases, minimize the number of queues and cache small look-up tables; avoid unnecessary double-buffering (and be careful — OSX uses double-buffering Figure 4: This is Ryan Vail of Inspiring Apps, delivering his session on “SQLite with all drawing routines); when repeated Power Tools.” operations are involved, DIM local variables, as they are always fast; and avoid creating

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 15 Figure 5: This is Christian Schmitz of Monkeybread Software talking about “Building REALbasic Plugins,” the first session on Saturday. Figure 6: This is Jay Crain of Inspiring Apps talking about and destroying objects and strings when possible. And he also “Usability ¥ Design Techniques,” the second session on mentioned some handy habits: retain objects you’ll need again, Saturday. creating and exporting them; use Split and Join, which are almost always faster than CountFields and NthField; flipping loops around can of it great, but I’ll try to summarize briefly. His introduction to sometimes add speed; and use a Dictionary for random look-ups. usability began with a comparison of desktop versus web design, The last session on Friday was also one of the most lively ones: their shared principles, and he mentioned a renewed focus on “Version Control, and Why it Rocks,” by Aaron Gerber and Mathias usability having grown with the web. A major point he began Gran. You could tell they were really into their subject from with is user-centered design, putting the user at the center of the start as they provided lots of fun comments and examples. your design strategy. Some principles he shared are as follows: Unfortunately, their’s was one of the longer sessions and is beyond designs should be transparent; aesthetics are important, but not the scope of this article. However, they did provide some URLs everything; and the success of a design can be measured by how to resources online: you can get the Mac Subversion Client (http:// infrequently the user has to stop and figure out how the program versionsapp.com/#), the documentation (http://svnbook.red-bean.com/), and the works. He also emphasized consistency: within the user expecta- main site for Subversion (http://subversion.tigris.org/). tions; within an app or web site; and between related apps and After Friday’s last session, we were in for quite a treat. Included web sites. Inconsistencies can also be a strength within an app, with the Summit’s ticket price was dinner at Salt, a fairly new restaurant downstairs from and next door to IA’s offices. Our group took over most of the basement seating area, and we could order basically whatever we wanted to eat and drink. However, this was more than just a nice dinner, but a chance to socialize and network with the other members of the Summit, and as such was very worthwhile. It also showed what great hosts we had! The first session on Saturday was “Building REALbasic Plugins,” by Christian Schmitz, well-known for his MonkeyBread Software collection of plugins for REALbasic (see Figure 5). However, again, the summa- tion of this presentation is beyond the scope of this article (he’s written a full article for this magazine based on his presentation). But Christian is very accessible and helpful, via his website (http://www.monkeybreadsoftware.de/) and mailing list (https://www.monkeybreadsoftware.de/ realbasic/mailinglist.shtml). The last formal session was “Usability and Design Techniques,” by Jay Crain, Figure 7: Bob Keeney, discussing the state of REALbasic programmers, and showing Inspiring Apps Designer (see Figure 6). the difference between ARBP members and non-members. He packed quite a lot into his hour, all

16 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Figure 8: Various participants of the Summit. That’s Brad Weber on the laptop, leading the “Facilitated RB/RS/Summit Feedback Session” at the end of the Summit, on Saturday afternoon.

as cues to the user that some things are right place or doing something the right of course that was key to the people from meant to act or to be operated differently. way. All in all, many useful suggestions. Inspiring Apps and Bob Keeney (for the In addition, he says to always allow Undo, After Jay’s session and a lunch break, ARBP), but we also discussed in general to give the user an ‘out,’ and that feedback we all were involved in a feedback session, our thoughts on the RB community as a is key, to let the user know they are in the led by Brad Weber (see Figure 8). This was whole. Norman Palardy, unofficial REAL not only to be about the Summit, though Software representative and frequent pres-

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 17 Figure 9: After the “meet-and-greet” on Thursday afternoon opening of the Summit, people split into groups for dinner. This is at Old Chicago Pizza. Clockwise around the table, from the left: Monika and Christian Schmitz, Rick Praetzel, Rick Roberts, Fred Roller, and the author, Geoffrey Rabe.

Figure 10: Another shot of the participants of the Summit, also showing Ryan Vail (in front with the laptop) and Seth Verrinder, operating the video camera to tape the conference.

ence on the RB Forums, answered some a very good one, and I look forward to one of the smaller ones that are beginning questions and comments, and the session future conferences, here in Boulder, or to take place around the country, to do was very positive for all involved. abroad, if I can make it. And I encourage so. I think you’ll find it very worthwhile As I mentioned, I found the Summit any RB programmer out there who has (and a lot of fun!). and my interaction with professional a chance to attend such a conference, members of the RB community to be whether it’s REAL World in Austin, or

18 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Interview

by Marc Zeedar

Meet Alex Restrepo REALbasic, custom controls, and iPhone apps

How did you get into computers and programming? At a Glance Well, my father used to teach programming to college students in the late 70’s and early 80’s, so I can’t really remember my house without a computer in it. Somewhere RBD#8108 in storage my dad has an Apple ][ and it’s the first computer I have memory of. We always had Apple computers in the house. So from a very young age my dad taught Target Reader: me the basics of programming, but it wasn’t until my senior year in high school that I Beginner really got into programming and eventually went into Computer Science in college. About the Interview Subject: You’re from Colombia? Alex Restrepo lives in Colombia Yes, born and raised in Colombia. My father taught computers, calculus, and physics and develops educational in a local university. software, iPhone applications, and uses REALbasic to write Are computers, Macs, and iPhones in particular, popular there? custom controls, such as the For the longest time they weren’t. Unfortunately Macs, and everything Apple (except acclaimed CustomEditField (a for maybe the iPhone) was extremely expensive. It wasn’t until the whole iPod success line editor written from scratch in and later the iPhone success that prices became somewhat reasonable (though still pure REALbasic code, no plugins much more expensive than PCs). Ten years ago I knew maybe three people who had required). His software can be Macs. Nowadays you can easily spot people using their MacBooks wherever a Wifi found on his website (http://homepage. hotspot is available. mac.com/alexrestrepo/indexmain.html). Does living in Colombia give you a different perspective on computing? I think not. The world is now small enough that you have access to everything just about everywhere, especially technology and computing in particular. Everything is on the net.

How did you discover RB? In college, all computers were PCs, except maybe for a few workstations here and there, so teachers always expected all assignments to run on PCs, which to me was an insult. So one day — I don’t remember where — I read about RB and how it was going to be able to compile for Windows in a future version. That got me really excited as I could get away from using a PC. I downloaded a demo and was instantly hooked, I loved its Object-Oriented approach Figure 1: Alex Restrepo. and how easy you could get an app running with almost no effort. Back then was also just appearing, and like many other languages, you would find yourself writing tons of code to add UI elements to windows, and wiring their actions with code.

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 19 Figure 2: A visual editor, written in REALbasic, that allows the user to create content for the company’s web-based educational software.

REALbasic freed me of all that so I could concentrate on what was important, the program itself.

So what sort of programs did you write? All sorts of things. Teachers would ask us to implement classic algorithms for lots of things. I’ve always been a very visual person and I remember writing these using all sorts of animations while everyone else used command-line apps. I also got into hardware programming and at one point built a small plotter driven by an RB app, via the serial port of a PC, even though the app was written entirely in a Mac.

What do you do today? Do you make a living writing software? Yes, I currently work for an educational software company, and even though our products are web-based, every tool used in-house from content editors and content manage- ment systems, to sales tools and reporting systems, are built using REALbasic. They all run on both Macs and PCs, with barely any specific code for either of the platforms. Our web apps are all .net based, however, the content they display is managed by RB apps.

Why did you take that approach? Speed. Using RB we were able to write visual content editors, the drag and drop kind, that allow our editors to review and create content quite easily (see Figure 2). Figure 3: A still-in-development custom control Alex is These apps then simply upload the formatted content to creating. our server’s database. Doing the same kind of things with

20 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Figure 4: Alex’s awesome CustomEditField control.

a web-based app would have been much amazed at how fast they actually worked. if the user deletes characters, the gap more difficult and time consuming. It all kind of snowballed from there. I becomes larger, up to a specified limit, started adding the line managers and in which case the data is copied to a new What else do you do with RB? my syntax highlight engine. I showed it array and the gap reduced. This approach I enjoy writing custom controls. A lot of to a couple of RB developers that I knew is simpler to implement and quite fast, those I end up using in projects at work used my previous editfield and they were not to mention that line management and are born from very specific needs, sold. They were the ones that convinced was also much simpler, though it’s a bit but a lot of times I also simply enjoy the me to finish it and make it available to more inefficient if the file turns out to way a control works in some other app or the public. be really big. platform and enjoy the challenge of being able to reproduce that. (Figure 3 shows an What are gap buffers and piece Currently CustomEditField is a unfinished control I’m working on.) tables? line editor. Any plans to add word They are structures to store large wrap and make it more like a text You wrote CustomEditField. How chunks of text. Piece tables are struc- editor? did that come about? tures in which edits are handled using That is the most requested feature. I find it funny that CustomEditField linked lists in which you simply replace Unfortunately it’s also the most difficult (see Figure 4) was actually born from an the changed text with a new node. These one to implement when it comes to user autocomplete editfield... I had written are super fast and make undo almost a interaction.... I do have that feature as my SyntaxHighlightEditField and found no-brainer (as you can simply restore a big to-do in my list. Maybe in version myself frustrated when I tried to add an old nodes to support undo) but line 2.0, who knows. autocomplete engine for it. It was simply management is really complicated. Gap too limited for what I had in mind (a basic buffers are large arrays (memoryBlocks How popular has CustomEditField XML editor) as there was basically no way in CEF’s case) in which you add a “gap” been? Has it been successful for for me to precisely place the autocomplete to the array wherever the insertion point you? options. From there I started looking at is at. If the user types something the new It has been very successful, or at least how text editors worked. That led me to characters are added to the “gap” without more than I expected! I was able to get learn about gap buffers and piece tables having to resize the array (unless there’s a new MBP from it, so that made me a (to store the actual text). In a few days I no more room, in which case a new gap happy man. I know of a lot of people that had the storage classes working and was needs to be created). Same for deletions,

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 21 Figure 6: Prismas, ported to iPhone. Figure 5: Prismas, made with REALbasic, running on a Mac.

use it in their projects, commercial and while to get up to speed. After we finished spot in every developer’s arsenal. Its OO free, that in itself is a reward for me. the calculator, I ported the small physics approach is so elegant that it would be a app I have on my website (Prismas) which great language in which to learn how to Coolness. On a personal note, I was originally written in REALbasic (see program, while also providing the power like it very much! Figures 5 and 6). to do some serious work when you need Thanks! The game “Crazy Drops” was a copy of to. The only problem I have with it is the a really good old game for Mac, “Candy final size of the executables, but that is a I see you’re now making iPhone Crisis.” I always wanted to make a whole different matter. applications. “networked” version and that’s how it Yes, I have a couple of iPhone apps out was born. You can play against another What improvements would you there, three to be exact. player, via Wifi. It was done pre-OS3, so like? GameKit wasn’t available yet. One thing I love about Cocoa is its How’s that going? view hierarchy and how it can easily be One of them is for sale; the other two How was your experience doing extended, allowing you to create just are free. The commercial one did okay the port from RB? about any control you can think of with for a couple of months, nothing great, It was surprisingly easy. Basically very little code. If that made it into RB’s enough to pay for a couple of dinners. it’s the exact same code, except for the upcoming Cocoa extensions, I’d be very Not bad, especially without doing a lot drawing code which in the phone is done happy. of advertising, and I just don’t have the using core graphics. In just a few hours I time for that. had a prototype running. It was almost What’s in the future for you? copying and pasting and reformatting Anything exciting coming up? How do you find developing for a bit. Not knowing what the future holds is iPhone versus REALbasic? exciting. Basically finishing a couple of Well, when the iPhone SDK came out a What’s your take on where RB fits updates to my iPhone apps, and finally friend from college who had been working into the programming world? releasing a couple of custom controls to on a graphic calculator for WinMobile REALbasic is a great language, I still the RB community that I just haven’t had devices contacted me for help getting it to don’t know of any other tool that lets you the time to finish, though some people are run on the iPhone. I really liked the SDK build Mac and PC applications without already using pre-release versions. and the tools. I had worked with / pulling your hair out. Its speed from idea Obj-C in college but nothing beyond to executable is also unbeatable (in my Thanks for the interview! academic “experiments” so it took me a opinion). That being said, I think it has a

22 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Feature

REALbasic Plugins Getting started with the Plugin SDK

Getting started with the REALBasic plugin SDK can be difficult. At a Glance The following article shows you how to get started on Mac OS X, Windows, and Linux. It is based on the presentation from the REALbasic Summit 2009 in Boulder, Colorado. RBD#8109 About plugins Target Reader: If you compare REALbasic with a car, you can see plug-ins as replacement, exten- Intermediate sion, or tuning parts. So while REALbasic comes with a lot of built-in stuff, you Source Code: always find things which are missing. Or you have a function in REALbasic which No doesn’t work for you and you need a replacement function. Or you need a tuning part to perform a task faster. For example, a picture effect which performs better RB Version Required: in optimized C code than in REALbasic code. And in that case you can take a plugin 2005+ off the shelf or make your own. Platform(s) Supported: There are a few reasons you may have to write a plugin. For example you can Mac OS X, Windows, Linux embed an existing static library or existing code in C/C++ or Objective-C into a Platform(s) Unsupported: plug-in. Technically you can even embed code from other platforms into your plugin. Mac Classic For example you can compile and link into your plugin code written in Fortran. Another reason to write a plugin is to call operating system functions which are About the Author: difficult to call from REALbasic. Some calls to COM interfaces or C++ classes are Christian Schmitz is the creator much easier from a plug-in. A third reason may be that you want to use symmetric of the Monkeybread Software multi-threading. This is easier to setup and run in a plug-in than in REALbasic code REALbasic Plugins. with declares or existing plug-ins.

Requirements To compile a plugin you need a C compiler. We’ll later check the different compilers you find on different platforms. Technically you could use any other compiler which creates a shared library with a specific entry point, but a C/C++ compiler is the easiest as the SDK has C/C++ code. Once you download the SDK and get started you need a lot of patience. The plug-in documentation is limited and for a few functions you only find documentation in an email in the plugin mailing list.

Mac OS X For Mac OS X you can use different compilers. GCC and LLVM come for free with Xcode on Mac OS X. For a better optimization you can of course pick other compilers like the compilers. If you like you can use the Xcode IDE from Apple.

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 23 In the long run, and if you have several plug-ins, you will certainly switch to some scripts running in the terminal. Whatever you use doesn’t matter, but you need to compile a dylib shared library in bundle style. You compile a 32 bit universal binary library for the Mac OS X Universal target in REALbasic and if you support older REALbasic versions a second PPC-only library for the Mac OS X target. Until version 2009r4REALbasic was based on the Carbon application frame- work, but future versions will use the Cocoa framework. So you will want to compile all GUI code twice. Once for Carbon and one for Cocoa. Non-GUI code should still be linked twice, one time for Cocoa without the Carbon framework.

Windows On Windows you can go with the free GCC compiler. You may want to use Figure 1: The new project dialog in Xcode with the REALbasic template the Microsoft Visual C compilers. Of course it does not really matter which tions are not allowed to use the picture, C compiler as long as it creates a native REALbasic versions the graphics, or the window class. But Windows DLL. Even Codewarrior 8 can What REALbasic version do you want those console flags will be no problem do this. And it has the great advantage to support at a minimum? Depending on for older versions of REALbasic as they that it runs on Mac. So Mac users can which version you choose as minimum are ignored there. use it to compile code on Mac for both you are limited to what you can use. For REALbasic 2009r3 and newer you Mac and Windows. But whatever DLL REALbasic 2005r4 introduces console need to provide a universal Mac OS X you compile, make sure it is native flags. So you can mark which functions, library. For older REALbasic versions code and not some byte code from the classes, and modules are supported you need to provide a PPC library, .net world. for console applications. If you don’t too. With REALbasic 2006r4 new 64 set the console flag the given item will bit data types are added. If you want Linux not be visible in developing a console to use these new data types any older For Linux you can use the compilers application. And console safe declara- REALbasic versions will report an error coming with your favorite Linux distribu- tion. If you don’t have one preinstalled, it is easy to install the packages for gcc or llvm. Those are two open source compilers you can use for free. For your distribution, make sure you install the 32 bit version so you have it easier and all libraries already installed in 32 bit. Because REALbasic expects a 32 bit ELF shared library compiler for x86 CPUs. One important thing on Linux is to keep your plugin linking to older library versions. Each Linux distribution has different versions of the libraries installed. And your existing user base may use older distributions with even older libraries. So you may want to install packages for older C/C++ runtime libraries, and you may prefer to link to libstdc++.so.5 instead of libstdc++.so.6 or libstdc++.so.7. Each newer version introduces new functions which may not be available in older versions. So if you depend on the older versions, your plugin will work with older and newer Figure 2: The new project in Xcode versions.

24 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Free Movie The MBS Plugin™ Tutorials! The Ultimate REALbasic plugin www.monkeybreadsoftware.de/realbasic/movies/ Adds Over 30,000 functions to REALbasic! The Monkeybread Software REALbasic plug-in collection is a big toolbox to help you solving your problems. Thousands of new functions will help you developing better applications! ■■ Use the CUPS plugin to access the Mac OS X and Linux print system. ■■ Compress data using BZip2 and ZLib engines ■■ Copy files asynchronously or synchronously. ■■ Use the DotMacKit to access .mac/mobileme features. ■■ New for Snow Leopard: Get geo coordinates using CoreLocation / Use OpenCL / New CoreImage filters / Quicklook Preview Panel / New functions for PDFKit and QTKit classes ■■ Use Spotlight classes to search on a Mac ■■ Use OCR classes for optical text recognition ■■ Extract frames from a QuickTime movie ■■ Use GraphicsMagick to read/write/manipulate over 88 major formats. ■■ Create your own serial number system for your applications ■■ Access image metadata (e x i f , i p t c , and others) using CoreGraphics ■■ Powerful SQL plugin for accessing multiple SQL databases (Oracle, Microsoft SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL, and o d b c , SQLite). ■■ The PictureMBS class handles pictures of any size using virtual memory. ■■ Connect to j d b c databases and use java classes using the Java plugin. ■■ Control USB HID devices on Mac and Windows ■■ Burn CD/DVDs in your application ■■ Record audio and video v9.3 ■■ Create transparent windows ■■ Run Javascript in a HTMLviewer control Supports ■■ Create professional charts using ChartDirector Snow ■■ Change/fade the screen gamma ■■ Run PHP scripts in your applications. Leopard! ■■ Perform window and screen transitions ■■ Read and write j p e g , t i f f , p n g , and g i f images. ■■ Use Dongles to protect your software (h a s p , Unikey, and Rockey) ■■ Use the x-rite Eye-One Device for color measurement ■■ Handle ICC Profiles, XMP metadata, CMYK images inj p e g and Ti f f . ■■ Cocoa classes: picture taker, color palette, spellchecking, and picture effects. ■■ Compile, decompile, and execute AppleScripts ■■ Download and Upload data using the c u r l class over f t p , f t p s , h t t p , h t t p s , Gopher, Telnet, d i c t , l d a p , and file protocol. ■■ Perform color management using ColorSync or LCMS. ■■ Use SpeechSynthesizer and SpeechRecognizer, ■■ Integrate your app with iCal, iChat, iPhoto, and Addressbook on Mac OS X

See the website for individual part pricing: PARTS $30 – $75 https://www.monkeybreadsoftware.de/realbasic/buy/ plugins-buy-nonEU-new-paypal-us.shtml COMPLETE * $294 / $147 Commercial License / Academic License Access SQL Databases: Oracle, Microsoft SQL Server, SQL $148.50 DB2, Sybase, Informix, InterBase/Firebird, SQLBase, MySQL, PostgreSQL and ODBC and SQLite $898.50 / $1498.50 Create/import/modify PDF files on Mac/Win/Linux. DynaPDF (Lite/Pro) Includes embedding of fonts and text extraction. ($448.50 / 748.50) (Academic Lite/Pro License) Professional charts for RB. ChartDirector $298.50 / $148.50 Commercial License / Academic License * Includes all plugins except independent plugins like DynaPDF, SQL, and ChartDirector.

FREE Trial Download and Full Documentation: www.monkeybreadsoftware.de Figure 3: We change the architecture setting to Universal binary

on compilation. It simply does not know REALbasic 2008r3 the SDK comes with open virtual volumes in REALbasic what an “SInt32” or an “UInt64” data everything you need to make plugins for using folderitem.CreateVirtualVolume type is. With REALbasic 2008r1 you the new Cocoa target. and folderitem.OpenAsVirtualVolume. have better array access functions in the This virtual volume contains for each plugin SDK. You need this to create and Plugin file format platform a shared library in a special fill an array in the plugin and return it Plugin archives in REALbasic are folder hierarchy. There is a folder for to REALbasic code. And starting with virtual volumes. You can create and build resources containing the shared

26 November/December 2009 | REALbasic Developer | www.rbdeveloper.com libraries and there are folders for IDE resources which contain the help files or the control palette pictures. You don’t need to build this folder hierarchy yourself. You can use the Plugin Converter project that comes with the plugin SDK to create the plugin archive for your libraries. Over the long run you will want to write your own tool so you can automate the build process. If you like you can add pictures for the control palette. For a better look on different operating systems you can even have different pictures there. One for Windows 2000, another picture for Windows XP, and one for Windows Vista. You can also add html pages for the online help. But using a lot of html pages slows REALbasic down as the html files Figure 4: We change the deployment target setting to Mac OS X 10.4 are copied to a temporary folder. “Mac OS X deployment target” which is defined. Actually this is the version Developing a plugin is by default the “Compiler default”. number of the Microsoft C compiler Now we want to show you how to Change it to “Mac OS X 10.4” to compile which exists only if the code is compiled start with the plugin SDK to get a plugin your plugin for all Mac OS X versions using the Microsoft C compiler. Mac and compiled. Together we will create a starting with Mac OS X 10.4. (see figures Linux targets will ignore it. As we want little plugin with one simple function 3 and 4) to use the same code for all platforms, and compile it for all three platforms. Now you can build your project once. we have it already here. Next is the At the end we merge those libraries to Hit Command-B or select Build from include for the REALbasic plugin func- one plugin archive. the Build menu. It takes some time for tions. In the rb_plugin.h file and the To get started go to the REALbasic Xcode to build the project, but once it realplugin.h file it references you find website and download the REALbasic finishes you should see an error message all the classes, constants, and functions package. Inside the extras folder you or a “Succeeded” message on the bottom in the REALBasic plugin API. should find the Plugin SDK files. right of the window. Now replace your Now in the next 4 lines you find the plugin cpp file with this code. By default definition of the C function called sum. Mac OS X it is very short with just an empty It basically adds one integer to another On Mac OS X we use Xcode for this PluginEntry function and one include integer and returns that value. Very example. Inside the examples that come line. Take this code: simple. The key thing is the next line. with the plugin SDK, you find a folder There we define a REALmethodDefinition named “Xcode Mach-O Template”. Inside #ifdef _MSC_VER structure which is the definition for a is the “REALbasic Mach-O Plugin” folder #include "WinHeader++.h" global function. This definition tells the which you want to copy to the other #endif REALbasic compiler which C function Xcode templates. Depending on your it needs to call for the given REALbasic Xcode version this location is different, #include "rb_plugin.h" function. And for REALbasic we provide but for Snow Leopard you can use the here the function pointer to the sum templates folder in “/Developer/Library/ static int sum(int x, int y) function and the REALbasic declaration. Xcode/Project Templates”. { The compiler parses this declaration in Now launch Xcode and create a new return x+y; order to know how to call our function project. Select the “Xcode Mach-O } in C. Although both are named sum here, Template” template and save your new only the name in the REALbasic method project (see figure 1). Once you have the REALmethodDefinition sumMethod = { matters. The C name is just decoration, project open, you see a lot of red entries (REALproc) sum, but we keep it in sync because this name (see figure 2). To fix this, find your plugin REALnoImplementation, "sum(x as can appear in a crash report. project folder in the Finder and copy integer, y as integer) as integer" }; In the PluginEntry function, you can the folders “Glue Code” and “Includes” do all the initialization of your plugin. Be from the plugin SDK. Once you are back void PluginEntry() aware that this function is called in the in Xcode the red entries are gone and { IDE so the compiler can learn the plugin Xcode finds all of the files. REALRegisterMethod(&sumMethod); function. So you should check for your Now you want to edit the project } initialization code to make it very effi- settings and opt to compile a universal cient and not mess up the IDE. Better to binary. For that you select in Architecture Let’s discuss the code above. The first make initialization methods or put your the entry “32-bit Universal”. Also you lines are for Windows only. So we use initialization in a class constructor. But want to check the deployment target conditional compiling to only compile the important part of the initialization is setting. Scroll down and look for the them where the _MSC_VER constant what we do here. We register the global

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 27 Figure 5: In Visual C on Windows with the test plugin project

method to REALbasic by calling the Windows the Release folder inside the project REALRegisterMethod function. Actually For Windows, you start by copying folder, but the one you need is the “Test you can see a deprecation warning here. the plugin SDK to a Windows (virtual) Plugin.dll” file. For your plugin you might want to go and machine. For this example I prefer to With that DLL we have the Windows make a new module or a class and add a use Visual C 2005 on Windows 2000 part compiled. If you like you can drop shared method. But for some things you inside VMWare Fusion. Visual C 2005 this DLL file into the plugins folder want to have a short name and still use is a good choice because the plugin SDK on Windows and launch REALbasic to a global method. comes with an example for that Visual test it. If you want to test it, copy the compiled C version. dylib to your plugins folder. REALbasic So copy your plugin SDK folder to a Linux loads plugin libraries for the current plat- Windows machine. Locate the “Visual For Linux you copy the plugin SDK on form directly from the plugins folder. But Studio .NET 2005 Example” folder in the your Linux machine. Also you copy the for bundling plugin libraries for several examples. Open the Test Plugin project TestPlugin from Mac or Windows to the platform, you need to create the rbx in Visual C by double clicking the “Test Linux machine. Now in the plugin SDK archive. Run REALbasic with the dylib Plugin.vcproj” file. We copied the whole you find the example “Box Control” which in your plugins folder and you can use plugin SDK file so Visual C automatically has a makefile for you. Copy this makefile the sum function in your code: finds the Includes and GlueCode files to your PluginTest folder. A makefile is automatically. a little script file which is run with the MsgBox str(sum(5,4)) Now change TestPlugin.cpp. You make tool. It runs compiler and linker should simply copy the code we have commands if needed so you don’t need This messagebox shows 9 if the plugin above on the Mac to Windows with the to recompile everything every time. You is found and compiled correctly. That is clipboard. Choose Build Solution from need to modify it: your plugin for the Mac. Next we look at the Build menu and after a couple of First replace all instances of “boxcon- the Windows target. seconds, your project will be compiled trol” with “testplugin”. On the top of (see figure 5). You find several files in the makefile below the comment lines

28 November/December 2009 | REALbasic Developer | www.rbdeveloper.com you find a few constants defined. The PLUGINSDKDIR needs to point to your plugin SDK folder. You should change it to “../..” for the case where you have your testplugin inside the examples folder. For other folders you need to have the path different of course. Further down you find the definition of the PREFIXHEADER constant. Change it to “LinuxHeader.h” so it finds the Linux header file correctly. Now you can go to the terminal. Use cd and ls commands to go inside the plugin folder. Now run the makefile with the make command. You type “make all” to call the make utility and let it start on the all: line in the makefile. From there it will see that it needs to compile both testplugin.o and PluginMain.o before it compiles the libtestplugin.so library (see figure 6). This library file is needed for the next step. Of course you can test your plugin by copying it into the plugins folder and running REALbasic for Linux. Figure 6: The typical output of make in Linux Merging parts Back on your favorite platform you now have all three libraries in one folder. Inside the plugin SDK folder you find the “Plugin Converter” folder. There you find the “Plugin Converter.rbp” project which you compile for your platform. Now you have the plugin converter command line application. Open the terminal on Mac OS X/Linux or the command shell on Windows. There you can use cd to go to the folder with your libraries. Now run the PluginConverter tool with the following options:

PluginConverter -n test.rbx -w32 "Test Plugin.dll" -car TestPlugin.dylib -lnx libtestplugin.so

The -n switch tells the converter to create a new plugin. With the other three options you can specify the parts to embed. We specify the Windows part, the Carbon partn and the Linux part. In the future you may want to add another dylib for the Cocoa target.

Some more words In the long run you will want to have all platforms share the same files. A common way is to host them on one platform and use Samba file sharing (SMB) to let all platforms access all files. Or to use subversion (SVN) to synchronize between Figure 7: Looking into the final plugin file platforms. After you setup your file sharing you need to setup both projects and the makefile. The paths must be correct and the build folder paths need to be changed too. Also you may want But please read the documentation coming with the SDK first, to write a script to create the final rbx file automatically. check the other plugins and search on the web for other people On MonkeybreadSoftware we currently have 350 plugin having the same problems first. projects which assemble to 43 rbx plugin files. So you see you can have several plugins in one rbx file. But with this number Web Resources: you need to automate things. So we have several scripts which http://www.realsoftware.com/download/ compile all these plugins. One for Windows, one for Mac OS X, http://www.monkeybreadsoftware.de/realbasic/movies/CreatePluginMac.shtml and one for Linux. And a final one to create the rbx files. Also we http://forums.realsoftware.com/viewforum.php?f=5 use self-written tools to write the scripts above, create the rbx files, and extract the declarations for the documentation. If you have questions about developing plugins, please ask your questions in the plugins section of the REALbasic forums.

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 29 REALWord

by Andy Dent

Karel, the REALbasic Robot How the rbKarel robot simulation teaches logic with RBScript

Karel the Robot has been around for nearly thirty years as a way At a Glance to teach people the basics of logic through solving simple problems. The rbKarel project uses RBScript to provide the language interpreter for Karel along with a RBD#8110 few goodies like spoken output and single-stepping. It also uses a much simpler context object for a second RBScript to define worlds. Why write a parser when Target Reader: RBScript does the hard work for you? This article doesn’t attempt to teach the Intermediate basics of RBScript — see the resources list at the end for past RBDeveloper Source Code: articles on that topic. What I do cover are some of the interesting challenges in Yes adapting RBScript for Karel and particularly how to add single-stepping and other controls over the script execution. As I wrote the article I also found myself RB Version Required: explaining a few points about the software design decisions, which may seem 2006+ heavy-handed to experienced programmers but hopefully will keep reminding Platform(s) Supported: others of some core principles. Mac OS X, Windows, Linux When Jeff Ayling posted his request for help, I was intrigued by the “Just how Platform(s) Unsupported: hard could it be?” prospect of trying to implement a particularly REALbasic Linux, Mac Classic style of Karel. I had already published a complex example of RBScript being used to drive About the Author: 2D graphics. Putting a little user logic on top of this didn’t seem that hard, just Andy is a freelance developer a case of adding a few methods to the context object to manipulate a robot. from Perth, Western Australia Things are never quite as simple as they seem in the first rush of enthusiasm who alternates REALbasic with and one challenge I hadn’t anticipated is that Karel’s world is not one of pixel C++, C#, Ruby, and Objective-C coordinates but of a grid with intervening walls and coordinates. The first public and welcomes the return to the teaching trial also proved that adding single-stepping and some feedback as to kindler, gentler and often more- what was going to happen next was a hugely desirable feature. productive world of REALbasic. Karel From the Users’s Viewpoint Karel moves around on a simple grid of vertical Avenues and horizontal Streets, with walls between. See Figures 1 and 2 for examples. He carries a Beeper Bag into which he can put the Beepers he picks up and from which he takes beepers to put on the grid points. Beepers are conceptually there — they are visible but (thankfully) do not actually beep. Real audible beeping is not an enhancement that has been requested and is probably the Karel equivalent of the tag. If more than one beeper is on a given grid location, we have improved visual feedback that a count is visible in the middle of the beeper.

30 November/December 2009 | REALbasic Developer | www.rbdeveloper.com rbKarel supports multiple robots but at this stage won’t animate them all. There are no restrictions on what order you place items, and beepers and the robot can be placed on top of each other. Worlds exist between the grid coordinates being either North (1) or West (4) of an intersection. As the world files are run as an RBScript, you could also write complex loops rather than keep using literal segments — an entire maze generator or fractal program could be supplied as a script to define a Karel world.

A Trivial World

World 5 5 Beepers 4 3 10 Robot 3 3 1 0 Wall 3 3 4 wall 3 3 1 wall 3 4 4

Karel Programming The original Karel language had a simple conditional if.. then and looping iterate N times constructs. We can’t remove anything from the RBScript language so the full power of RBScript conditionals is available. To make life a little easier for people who are new to the idea of variables, a single index variable is predefined dim i as integer unless it is already included in their code. This takes advantage of the RBScript idiom of composing your own preface with user scripts to have variables defined in RBScript space.

Original Karel Code from KarelJ examples

BEGINNING-OF-PROGRAM if facing-east then turnleft; move; iterate 5 times begin pickbeeper end; end;

rbKarel Version of Original

if facingeast then The only instructions you can issue Karel are to move, turnleft turn, pick up and put down beepers. The other verbs in the move language, as you will see below, are to evaluate the world for i = 1 to 5 so Karel can decide what to do next. Something to consider pickbeeper is, with this kind of interactive environment, users can next write complex Karel scripts to solve a problem in one go, end as a typical programmer might. They can also enter just one verb to tell Karel to move or turn, and see how that affects the state of the world. That is like the experience Original C++ Karel Code Simple Example of exploring algorithms with a dynamic language such as Ruby or Python. #include using namespace std; Defining Worlds The three verbs that define a world position stacks of int main() beepers, walls made out of segments, and a robot. Internally,

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 31 { the top of his sunglasses and deciding how many to pick TurnOn(); up. Looking at the list of functions below, you can see how Move(); all of them have a negated version, rather than having to Move(); parse a logical not statement. Of course, if people put a not PickBeeper(); in front of any conditional, followed by a space, RBScript The Karel verbs I implemented are close to the apparent normal interpretation will work anyway. standard — there has been a little variation between versions. Movement is blocked by there being a wall or edge of the Being written in RBScript means we don’t have to worry world in front of Karel. An interesting aspect of the Karel about terminating semicolons and, although the context world is that it combines both absolute NSEW directions methods listed below are, strictly speaking, invoked through and a relative sense. People can write code thinking in function calls, we can take the normal REALbasic approach either paradigm and it will work better for some worlds than of dropping the parentheses to get very clean syntax. Another others. The Mountain Climbing problem shown in Figure 1 benefit is lack of case sensitivity in RBScript, unlike the is an interesting one which asks the user to imagine Karel Java implementation. Errors from case are an issue you do moving vertically, as seen from the side, rather than the not want to have to debug for beginner classes! normal top-down viewpoint. I also took the liberty of making TurnOn and TurnOff Standard Karel Environment Testing Functions optional. My view is that the graphical text box into which they type their program clearly bounds the program so ■■ anyBeepersInBeeperBag requiring these extra verbs is another added thing people ■■ facingEast shouldn’t have to worry about. ■■ facingNorth The environment testing functions are pretty self- ■■ facingSouth explanatory. The only one I think is slightly confusing is ■■ facingWest the idea of being nextToABeeper which is when a beeper is ■■ frontIsBlocked at the same street corner as Karel, I think of it as the robot ■■ frontIsClear leaning against a signpost, eyeing a stack of beepers over ■■ leftIsBlocked

The MBS ChartDirector Plugin™ The ultimate charting solution for REALbasic

New Version n Professional charts in your cross platform applications! 5.0! n Supports Mac OS X, Windows and Linux. n Visit gallery to see sample charts: http://www.monkeybreadsoftware.de/realbasic/chartdirector/ n Download a free demo copy on www.monkeybreadsoftware.de as part of the MBS REALbasic plugin collection. n Royalty-free licenses available per developer for $298.50 (Commercial) and $148.50 (Academic).

32 November/December 2009 | REALbasic Developer | www.rbdeveloper.com GUI but there are no dependencies on it. As you can see from Figure 3, the window is connected to the KarelWorld by interfaces and you could implement your own variation quite easily. The drawing surface used is a subclass of my GraphicsScripter which exposes the Graphics2D functions as a REALbasic context object, allowing you to write scripts that do all kinds of drawing on a Canvas. Most of what it does is very simply repeat each of the methods on a known Graphics object DrawCircle(x as integer, y as integer, r as integer)

mDest.DrawOval x, y, r, r

When you use a subclass as a context object, all the public methods of the parent are still available to RBScript so this is a nice way of separating the development. From postings I’ve seen in various mailing lists and forums, I think many people think they have to copy all the methods they want in their context into a single class. So, if you want to write a spinoff, consider just inheriting KarelScripter and adding your own methods, and you can continue to take advantage of any fixes in the original. Figure 1: Simple Karel World — Mountain Climbing In classical OOD terms, rbKarel has a separate Model which is the ■■ leftIsClear Non-Standard Methods Exposed KarelWorld class. It maintains the state ■■ nextToABeeper to Script, mainly for mapping coor- of the world and does minor dual duty ■■ noBeepersInBeeperBag dinates. as an RBScript context object when ■■ notFacingEast ■■ Avenue2X parsing the World files. The main ■■ notFacingNorth ■■ AvenueGapX visible objects within the world, the ■■ notFacingSouth ■■ IsRunning Robot, Walls, and Beepers are stored as ■■ notFacingWest ■■ NextAvenue objects which maintain their own state. ■■ notNextToABeeper ■■ NextStreet All these draw using a KarelScripter to ■■ rightIsBlocked ■■ Street2Y supply the drawing commands. ■■ rightIsClear ■■ StreetGapY See Figure 4 for a comprehensive ■■ StreetSpacing class diagram of all the classes involved Standard Karel Imperative Actions ■■ Wait in the user interface and drawing. (all logged) ■■ WorldResized ■■ X Worlds of Streets and Avenues ■■ Move ■■ Y The streets which are drawn as ■■ TurnLeft gridlines are calculated and drawn as ■■ PickBeeper Other Public Functions not Intended shown in Code Listing #1. They are ■■ PutBeeper for Script Use: just background graphics, having no ■■ ErrorShutdown active role and so didn’t need modeling Property Exposed to Script ■■ LeftDirection independently. Note how the KarelWorld ■■ MovePause ■■ PrepareKarelScript gets its width and height from the ■■ RightDirection KarelScripter at the time of drawing. That Other Karel Imperative Actions ■■ SetLogger way, if the original Canvas is resized, the Say grid will redraw proportionately. I can’t ■■ TurnOff emphasize too highly — avoid caching ■■ TurnOn Implementing the Basics such values unless you are really From the start, I wanted the core certain the cached value is needed Karel engine to be reusable. The for performance reasons, hopefully SimpleKarelRunner window is a nice because you’ve proved a need through

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 33 testing. The more values you cache, the more fragile your architecture becomes and you find yourself with weird edge condition bugs where an uncommon user action has side-effects in appar- ently unrelated areas. There is no attempt to see how well the avenue and street lines fit. The user is responsible for specifying how many are in the world and they get to choose the size to which they drag the Canvas in the GUI so it is up to them to achieve an aesthetic result. One of the late changes in rbKarel was adding the disclosure triangles on the window, so the script and controls panels can be hidden. Jeff was lecturing with 800x600 projectors and wanted an easy way to show complex worlds. Hiding the UI was easier than adding a separate zoomed window.

Drawing Objects All the Karel objects draw using a KarelScripter and you can see in Code Listing #2 how a few simple shapes are composed to draw the robot. The impression of direction is given by choosing where to draw the blue oval representing the robot’s eye, rather than rotating a complex object. This is a good example of how we often can fake Figure 2: Karel Maze things in games and animation rather than having to actually model the more sophisticated aspect of a rotating body. translated to X and Y pixels at the last If we had a 3D robot with an animated minute. If someone wants to mix their for each w as KarelWall in mWalls waggle as it moved, something a lot own drawing logic into the script they smarter would be needed. Even using a could scribble anywhere they want on if w.IsBetween( ave1, street1, ave2, fancier graphic would probably require the Canvas but would probably want street2 ) then real rotation. to use coordinates relative to the return true The most obscure part of Code Karel objects. The methods X and Y end if Listing #2 is how this direction is expose relative coordinates calculated next calculated. A simple enum is used to at runtime. Thus the scripted objects return false specify direction and the robot has will appear at the correct location even REALbasic is fast enough that I a Facing property. This shows up in if the window is resized and the grid suspect we could run through hundreds the script commands where you can drawn scaled. If you really wanted fancy if not thousands of walls in such a loop see the final action is to set the robot custom graphics, the scaling factors are without a user noticing the delay. The direction. also exposed to the graphics context more complex code is in the IsBetween as AvenueGapX and StreetGapY. test as shown in Code Listing #3. As a KarelScripter.TurnLeft general design pattern, I like to have Collision Detection collections of fairly smart objects. That The collision detection problem in design also lends itself to testing with Wait MovePause // this implements the speed of playback rbKarel is very simple because the only separate unit tests. if mLogger<>nil then things Karel can collide with are walls The apparent simplicity of this colli- mLogger.LogKarelEvent "Turn Left", self and the boundaries of the world. In a sion detection hides some sophisticated end if much bigger world, with performance thinking. Currently, you can only move mDirection = LeftDirection issues, an optimal solution would be a robot one cell at a time. However, needed but the simple Karel world the collision detection doesn’t make mWorld.TurnRobotTo mDirection allows me to write easy code: assumptions about adjacent cells. You KarelWorld.IsWallBetween(ave1 could specify a jump in a straight line Custom Drawing as integer, street1 as integer, ave2 of four cells and the detection would The world of Karel objects is in as integer, street2 as integer) As still work because it only checks the street and avenue coordinates, only Boolean start and destination. The collision

34 November/December 2009 | REALbasic Developer | www.rbdeveloper.com some things were obvious, in some cases to both of us.

Logging to Speech Speech was one of those cool features I just had to add because REALbasic makes it so easy. It’s also a good example of how a simple feature sparks the user imagination to create a much more complex requirement. I added the Say verb to the core Karel syntax just so users could celebrate with a few words aloud. The initial version was used in a demonstration of speaking when the problem was solved. As soon as we started trying to use Say within loops, it became obvious that Karel could both run and talk at the same time — not a problem if you’re going slowly. The issue really came to a head when I added the logging Say each change feature and Karel would complete running a script whilst the computer gabbled on for a couple of minutes. This has been solved for Mac in SpeechUtilties.SpeakSynchronously but there is an outstanding issue for Windows to work out a way with declares to wait whilst speech is still being output. Figure 3: GUI Connections to Karel Usability Through Delays detection also is only checking the easy extension would be an rbKarel From the start, I’d built in the geometry of the world — it is not related program logging across a socket inter- delay feature to keep Karel running to movement in any way. That means face! A simple Composite pattern is at a visible pace. The delay period, of you could reuse the same collision used — a KarelMultiLogger allows a series course, is specified in a variable. It detection to see if two robots could of loggers to be invoked. was very easy to add a slider on the see each other or fire at each other in Logging can also be a way of intro- main window that adjusted this vari- a straight line. ducing delays, in rbKarel’s case able, although we invert the sense of deliberately. As discussed in more the slider so that faster is to the right. Logging detail below, logging to speech and The quick evolution of this slider is a Logging is an essential element of single-stepping both require the nice example of iterative design and debugging any program. There is a logging class to pause so the user can how sometimes less is more. I started richer logging mechanism built into catch up with Karel. putting text on the slider which was updated to indicate the delay, stewed with Jeff over whether a typical Karel user would care about the amount of The impression of direction is given by choosing where to draw delay and we finally tested it with a class with all the text removed. The the blue oval representing the robot’s eye, rather than rotating idea of a slider that adjusts speed is a complex object. This is a good example of how we often can intuitive and people easily related to the scale of the slider and its sense of fake things in games and animation rather than having to actually direction. I think the actual magnitudes of the delay were fine-tuned in three model the more sophisticated aspect of a rotating body. iterations — it now ranges from one second delay down to zero.

Single-Stepping and Canceling rbKarel than exposed through the user Adding Fun and Features All the significant actions of Karel interface. The KarelWriteLogger provides Once the basics were implemented, that affect the state of the world log a base class you could subclass to write Jeff was able to start playtesting. Even before they perform their action. That to anything supporting the standard before he used rbKarel with a class, allows us to have an about to blah REALbasic Writeable interface, so an approach to logging. Single-stepping is

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 35 Figure 4: Overall Class Diagram

Do implemented very simply — if you turn on single-stepping app.YieldToNextThread then a KarelStepLogger is inserted ahead of all the other loop until mStepButtonPressed or StepCheck.value=false loggers. It waits until the step is acknowledged, by the StepButton.Enabled = false user pressing a Step button on the main window. Because mStepButtonPressed = false it knows what is about to happen, the user gets to see that StepAboutPrompt.Visible = false as a comment on the window. With the stepping logger StepActionMsg.Visible = false causing the delay before the other loggers, if the user also has speech logging turned on, they don’t hear the descrip- There are a number of interesting aspects to the step- tion of the action until they press the Step button. ping method which deserve careful thought — it was not arrived at easily! SimpleKarelRunner.StepNeeded(msg as String) It is invoked through an interface and the caller knows StepButton.Enabled= true nothing about how it is implemented. It could as well be a StepAboutPrompt.Visible = true timer or monitoring a microphone for a sufficiently loud StepActionMsg.text = msg noise. StepActionMsg.Visible = true A minor but appreciated usability feature is that the loop monitors the state as well — unchecking will StepCheck continue the same as pressing the Step button. // spins waiting for that button to be enabled The main point of course is that it requires the RBScript // this will be called from a separate non-GUI thread running Karel to be running in a separate thread. If the script ran in the

36 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Code Listing #1: KarelWorld. DrawWorldBackground(ks as KarelScripter) Why Google Code? One of the ways to spread the news about dim width as integer = ks.Width dim height as integer = ks.Height REALbasic is to provide public examples of const marginPenSize = 4 interesting projects or useful snippets of code. dim insetFrame as integer = Margin — marginPenSize // the thick line is inside the margin There are several major code repositories which dim doubleInset as integer = 2*insetFrame have the kind of prominence I wanted — Google dim frameWidth as integer = width — doubleInset dim frameHeight as integer = height — doubleInset Code has an appealingly straightforward wiki

ks.PenSize = marginPenSize and already hosted several major REALbasic ks.PenColor = ks.white projects. ks.FillRect 0, 0, width, height // clear background ks.PenColor = ks.black You can count on projects on Google Code to ks.DrawRect insetFrame, insetFrame, frameWidth, frameHeight be well-indexed by Google! The simple project

ks.PenSize = 1 management tools it provides make it easy to

track issues and provide a notification feed for ks.PenColor = ks.blue issues logged as well as version control updates. // vertical gridlines and numbers At the time, the other major contender was // gap either side of lines dim aveSep as double = ks.AvenueGapX SourceForge which had a much more compli- dim aveY1 as integer = Margin dim aveY2 as integer = height — Margin cated interface. They have since significantly dim x as double = Margin improved their appearance and features but for i as integer = 1 to mNumAvenues x = x + aveSep I’d still recommend Google Code as easier to dim aveX as integer = Round(x) maintain. ks.DrawLine aveX, aveY1, aveX, aveY2 ks.DrawString str(i), aveX-4, height-2 // tweaked position next main thread, it would be locked up and the user interface

would not react to the actions you see tested above. // horizontal gridlines and numbers The threaded approach that enables single-stepping was dim streetSep as double = ks.StreetGapY first added to give the ability to halt Karel. The Run button is renamed to Stop once we start running and it is also dim streetX1 as integer = Margin possible for an error condition within the script to cause a dim streetX2 as integer = width — Margin halt (e.g., if the user runs Karel into a wall). These all rely dim y as double = Margin on an undocumented but, in hindsight, obvious aspect of for i as integer = 1 to mNumStreets how REALbasic works — if you are running an RBScript in a thread you can kill the thread to halt the script. y = y + streetSep dim streetY as integer = round(y) KarelWorld.ErrorShutdown(msg as string) ks.DrawLine streetX1, streetY, streetX2, streetY for each obs as KarelWorldObserver in mObservers dim flippedStreetNum as integer = mNumStreets — i + 1 obs.ErrorShutdown self, msg ks.DrawString str(flippedStreetNum), 1, streetY+2 next if mOurThread is nil then next // unable to actually stop running else

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 37 mOurThread.Kill //will stop any KarelScripter that is Code Listing #2:KarelRobot.DrawInContext(ks as KarelScripter) using us as well dim x as integer = ks.Avenue2X( mAvenue ) end if dim y as integer = ks.Street2Y( mStreet ) Currently, the only ks.PenColor = ks.red KarelWorldObserver we use is the SimpleKarelRunner GUI itself which const halfWidth = 8 is able to report the error message in ks.FillSquare x-halfWidth, y-halfWidth, 2*halfWidth red text. // now work out side to put blob blue eye on dim sideOffsetX, sideOffsetY as integer Packaging Predefined Worlds and if Facing = KarelScripter.North then Scripts sideOffsetX = 0 A free program like rbKarel is often sideOffsetY = -halfWidth quickly rejected unless it includes elseif Facing = KarelScripter.South then sample documents. This article is sideOffsetX = 0 not about how to make dynamic sideOffsetY = halfWidth menu handlers so I won’t go into elseif Facing = KarelScripter.East then details. In brief, rbKarel includes sideOffsetX = halfWidth the DynamicDelegatingMenuItem and its subclass FolderItemMenuItem to make it sideOffsetY = 0 easy to have menus of FolderItems that else are loaded at startup from a couple of sideOffsetX = -halfWidth special folders. These menu items are sideOffsetY = 0 tagged with the folder item so it can end if just be opened late and a script read. const blobRadius = 4 The SimpleKarelRunner. ks.PenColor = ks.blue SetupDynamicFolderMenus method ks.fillCircle x + sideOffsetX — blobRadius, searches a number of directories y + sideOffsetY — blobRadius, starting with the immediate applica- 2*blobRadius tion parent directory, Documents, and others

The MBS DynaPDF Plugin™ The ultimate PDF solution for REALbasic

Professional PDF support in your cross platform applications! Supporting Mac OS X, Windows and Linux. n Create PDFs with interactive forms, add vector graphics, web and file links, annotations, bookmarks and file attachments. n Use digital certificates to sign your PDF files with digital signatures and NEW Academic encrypt them with 64 or 128 Bit keys. Licensing Now n Import PDF pages and extract content, edit text, forms and graphics. Available! n Split and merge PDF files. n Supports color spaces: RGB, CMYK and Grayscale, multipage TIFF files, custom page templates and much more. Royalty free licenses available for 599 € (Lite), 999 € (Pro), and 1499 € (Enterprise) per developer. Academic licenses are available for 299 € (Lite) and 499 € (Pro). This license can be used also in C/C++ cross platform applications and on Windows with C#, VisualBasic, VB .NET. Download a free demo copy on www.monkeybreadsoftware.de as part of the MBS REALbasic plugin collection. 38 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Andy Dent to the rescue! I was excited to receive a response from Andy who offered to have a look at the project — as long Jeff Ayling’s Story as I didn’t tell his wife :-) Here is his response to my post:

Based in Sydney, Australia, my Game Training G’day Jeff ( HTTP://www.gametraining.net) business has been growing consis- Does it have to exactly match the Karel syntax? tently since early 2009. In the early days my students always I’m pretty sure I can come very close with some- had trouble getting their head around simple coding concepts thing in RBScript which would make it a small while working on our game projects as most had not had any enough project that I could justify the time this previous coding experience. I knew I needed to take each weekend (I am very busy and you are NOT allowed student through a training process which started with simple basic concepts and became gradually more challenging to get to tell my wife!). them ready for some serious video game coding. I discovered Karel the Robot while watching an online I was very excited to be able to finally use RBScript for some- Stanford University lecture on ‘Programming Methodology’ thing productive. I had initially intended to have my students by Professor Mehran Sahami. You can watch all 28 parts of learn to use Karel while working within the REALbasic IDE the lecture via iTunes U with the link below. but Andy’s idea meant we could have a freestanding Karel application which our students could use in class without http://deimos3.apple.com/WebObjects/Core.woa/Browse/ introducing the additional learning curve of working within itunes.stanford.edu.1615329425.01615329428 the REALbasic IDE. I now take every new student (my youngest is 8 and eldest What impressed me about Karel the Robot was the way is 65 years old) through a process of 3 x 1 hour lessons using students were able to learn basic programming techniques and rbKarel. I have created approx 20 Maps which begin with super concepts in a unique and enjoyable way. I think the key lies in simple concepts and become increasingly difficult. I have one allowing students to write code which gradually increases in Map which is so difficult that I have had only one student able complexity without changing the underlying content of each to solve it. He actually came up with the answer at 2am after project. Karel never changes yet Karel’s world does change the challenge had been haunting him for two weeks. and the student is required to solve problems and get Karel I teach each student four main concepts which I have found to perform various tasks. the most useful before moving into game development. After seeing Karel in action I knew this was what I needed to introduce my students to code writing. However, I didn’t want 1) The While Loop to introduce them to the complexities of getting , a Java 2) For/Next Loops Runtime Environment, and the project up and running. I’ve 3) If Statements always been a huge fan of REALbasic and I posted a message 4) Subroutines, methods and functions in the REALbasic User Forum (the NUG) to see if anyone was Once a new student understands these concepts we are able interested in assisting with the project. to start scripting games without the student getting intimidated by the more complex code used in our game projects. This was my post on the NUG: We are even able to write basic AI code using Karel such as the following which allows Karel to navigate through a maze. Hi all, Next week I’m teaching some young kids a bit while notnexttoabeeper about software development. if frontisclear then After watching the Stanford University move Programming Methodology videos at elseif rightisclear then (http://deimos3.apple.com/WebObjects/Core.woa/Browse/ turnright itunes.stanford.edu.1615329425.01615329428) I feel that Karel move the Robot could be a nice project to show my students. elseif leftisclear then Unfortunately Karel is written in Java — I’d love turnleft to get Karel up and running in REALbasic. move http://karel.sourceforge.net/ else turnleft Is anyone up for the challenge of getting Karel end running in RB? I’m spinning too many plates right wend now to attempt it but I’d be willing to pay a small amount to anyone who could help — sorry no real rbKarel has transformed the way I teach and I sincerely budget for this teaching gig. appreciate the wonderful work of Andy Dent who brought my idea to life.

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 39 SetupDynamicFolderMenus() mWorldsFolder = FindSpecialFolder("KarelWorlds") Code Listing #3: KarelWall.IsBetween(ave1 as mScriptsFolder = FindSpecialFolder("KarelScripts") integer, street1 as integer, ave2 as integer, street2 as integer) As Boolean if mWorldsFolder<>nil then FolderItemMenuItem.MakeMenuForFlatFolder App.MenuBar, "Worlds", 5, mWorldsFolder, AddressOf handleWorldsMenu, AddressOf // horizontal lines FileIsOKAsScript if mOnEdge = KarelScripter.North or mOnEdge = KarelScripter.South end if then

if mScriptsFolder<>nil then if street1 = street2 then return false // we don't block anything that FolderItemMenuItem.MakeMenuForFlatFolder App.MenuBar, is horizontal "Scripts", 6, if street1 > street2 then mScriptsFolder, AddressOf handleScriptsMenu, AddressOf FileIsOKAsScript dim tempStreet as integer = street1 end if street1 = street2 Conclusion street2 = tempStreet I got a huge kick out of writing rbKarel and it’s the closest end if // swap street1 and 2 thing I’ve done to being a games programmer. I can’t claim if mOnEdge = KarelScripter.North then any credit for the design because the inspiration was Richard E. Pattis’s but I think I added a few nice usability touches. // North is above the point A lot of the fun of designing software comes from iterating if street1 <= mStreet and street2 > mStreet a design and smoothing off rough edges. If you caught yourself rolling your eyes at too many and ave1 <= mAvenue and ave2 >= mAvenue then return true statements of the obvious, with little lectures on design else practices, you’re obviously experienced enough to go off // South is below the point and add an eye-rolling option to rbKarel! Hopefully this work will inspire a few other people to if street1 < mStreet and street2 >= mStreet consider RBScript as a games platform and they can start and ave1 <= mAvenue and ave2 >= mAvenue then return true with rbKarel and code their own. Jeff and I would really like to see a community of rbKarel users develop and that end if will give me further motivation to enhance rbKarel. I have a dream of even smarter users who start playing with else the graphics properties — why can’t Karel leave a trail of breadcrumbs? // vertical lines if ave1 = ave2 then return false // we don't block verticals References and Additional Reading Material Karel Overview: http://code.google.com/p/rbstuff/wiki/rbKarelOverview if ave1 > ave2 then dim tempAve as integer = ave1 Karel the Robot home page for C++ implementation: http://www.cs.mtsu.edu/~untch/karel/ ave1 = ave2 Karel Java home: http://sourceforge.net/projects/karel/ ave2 = tempAve end if // swap ave1 and 2 Karel Java version documentation: http://karel.sourceforge.net/doc/html_mono/karel.html if mOnEdge = KarelScripter.East then Related REALbasic Developer articles: // East is right of the point RBD 2.6 “Using RBScript” by Thomas Reed RBD 3.1 “Command-Line RBScript” by Joe Strout if street1 <= mStreet and street2 >= mStreet and RBD 5.5 “Dynamic RB, Part 1” by Marc Zeedar ave1 <= mAvenue and ave2 > mAvenue then return true RBD 5.6 “Dynamic RB, Part 2” by Marc Zeedar else RBD 7.1 “Scripting for Fun and Profit” by Marc Zeedar RBD 7.5 “A Plugin System” by Thomas Tempelmann // West is left of the point if street1 <= mStreet and street2 >= mStreet and Karel The Robot: A Gentle Introduction to the Art of Programming by Richard E. Pattis: http://www.amazon.com/Karel-Robot-Gentle-Introduction-Programming/dp/0471597252 ave1 < mAvenue and ave2 >= mAvenue then return true end if Karel++: A Gentle Introduction to the Art of Object-Oriented Programming

by Joseph Bergin, Mark Stehlik, Jim Roberts, Richard E. Pattis: http://www.amazon.com/Karel-Gentle-Introduction-Object-Oriented-Programming/dp/0471138096 end if return false

40 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Beginner’sColumn T Corneritle

Basic RB Controls, Part 1 by Marc Zeedar [email protected] Exploring the RectControl class

give you a way to create a RectControl At a Glance Lately I’ve been covering object. Instead you’ll always work with some fairly advanced beginner topics, so a subclass such as a PushButton. Because RBD#8111 I’ve decided to take a moment to cover the of that, you may not be that familiar with obvious. Often the most simple things are the RectControl object so this could be an Target Reader: not well documented or publicly explained important primer. Beginner and present awkward obstacles for those A RectControl has a number of standard Source Code: just starting out. methods, properties, and events, that, Yes As one simple example, I remember when because of inheritance, all basic controls RB Version Required: I first used REALbasic being puzzled about also share. This means that if you know 2006+ how to group radio buttons together. If I how to programmatically set the location just had one group on a window it worked of a CheckBox, you also know how to set the Platform(s) Supported: fine, but two or more groups didn’t as they location of a RadioButton, since both work Mac OS X still acted like one group. It was a while the same way. Platform(s) Untested: before I realized I had to group the radio So we’ll begin by exploring some of Windows XP, Linux, Mac Classic buttons inside a GroupBox for them to work these shared features and later I’ll cover in sync. the unique aspects of each control. Note About the Author: So today we’re going to begin an explora- that this article is designed to be a general Marc taught himself programming tion of some of the most basic of REALbasic overview, not a comprehensive exploration, in high school when he bought controls. Much of this may be obvious to so I won’t spend a huge amount of time his first computer but had no you, but hopefully you’ll find at least one on each feature. The specifics of how each money for software. He’s had or two nuggets of new information. feature works are covered in the Language fun learning ever since. Reference and of course I’ve explained many Shared Basics of these in other columns dedicated to topics We’ll begin by covering the most basic that depended on those features. aspects of basic controls. In the past we’ve Let’s start with RectControl Events. talked about the object-oriented principle of inheritance — that’s how you’re able to create RectControl Events custom subclasses of existing controls, for These are basic events that any controls instance. If you look through most controls based on RectControl can receive. Most of you’ll see they’re all based on a generic these should be familiar to you. Note that object called RectControl. though many subclasses of RectControl can receive these events, that doesn’t necessarily RectControl make them useful. For instance, the Line Note that you don’t interact with a control can receive a KeyDown event, but RectControl directly: REALbasic does not how, when, and why would you use that?

Figure 1: The HelpTag feature in action.

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 41 A Line doesn’t really need key presses. It KeyUp - The user has released a key on This adjusts the slider position based on gains that ability via inheritance, but it’s the keyboard. the user’s use of the horizontal scroll wheel. not of much practical value. Just ignore the MouseEnter - This gets triggered when the (Cool feature: on a Mac OS X laptop this feature on objects that don’t need it. mouse arrow enters the control’s area. It even works with two fingers on the touch ConstructContextualMenu - Used to build is extremely useful for providing simple pad to do horizontal scrolling!) a ContextualMenu. See RBD 6.5 for my “hot help.” See the Hot Help example in Note: It’s important to remember that column on working with Contextual today’s demo project. Note that this type this event is dependent upon the mouse Menus. of help isn’t as useful as in the past now pointer being inside this control. If the ContextualMenuAction - Gives you a way to that there’s the HelpTag property (see the pointer is elsewhere, this event does not execute a Contextual Menu action. Again, next section). get triggered. (If you wanted such behavior, see my article in issue 6.5 for more. MouseExit - This happens when the user you’d have to put the code inside the DragEnter - This event happens when moves the mouse pointer outside of the window’s MouseWheel event, but then your something is being dragged to this control. It control. scroll wheel feature would only benefit a is useful if you want to do something special MouseMove - This event gets called when single control, which might be okay.) with the drop, such as highlight the control in a custom manner. RectControl Properties I wrote about drag-and-drop in I remember when I first used Properties store information RBD 7.6. Though the primary inside an object. Some are read- drag event I talked about was REALbasic being puzzled about only, meaning you cannot change DropObject, these others should them. They are for information be easily understood if you under- purposes only. Others you can stand basic drag-and-drop. how to group radio buttons change and it may change the DragExit - This gets called when behavior of the control. the drag is leaving your object. together. If I just had one group Active - This returns true or false For instance, perhaps the user based on whether the control is started to drop something onto on a window it worked fine, active or not. In most circum- this control, then changed their stances, it is automatically mind and moved away, in which but two or more groups didn’t activated or deactivated (such case you’d want to undo any as when its window is not front- special highlighting you did in as they still acted like one most). This is read-only so you DragEnter. cannot set this, only examine it. DragOver - This gets called group. It was a while before AutoDeactivate - You can turn the while an object is being dragged automatic deactivation feature off over this control. It’s primary if you’d like. benefit is that it passes the live I realized I had to group the Enabled - This is where you can x/y coordinates of the dragged enable or disable a control. This object. This could be useful for radio buttons inside a GroupBox is extremely useful if a control live updating as the object is being should not be useable in certain dragged around, or if you had a for them to work in sync. situations. For example, you might large custom control, such as a only enable a “save” PushButton if canvas, with multiple drop targets there is data that requires saving. inside it. This event gets triggered If there is no data or it’s already every time the dragged object moves, so you the mouse moves around inside the control. saved, you would disable the button. could check to see if the object is within an The coordinates of the pointer are passed, Height - This sets or gets the height of internal target and highlight or unhighlight so if you want you can do various things the control. You can use this to dynami- that target. based on where the cursor is pointing. cally adjust the control’s size, or use Top DropObject - This is when the user lets go MouseWheel - This gets triggered when the and Left to set the control’s position on of the mouse button and actually drops user scrolls a mouse wheel. Not all users the window. the object onto this control. Thoroughly have mice with wheels, but this allows you HelpTag - This sets the help text that is covered in RBD 7.6. to customize the control’s response for those displayed in a small popup box when the KeyDown - The user has pressed a key on that do. Because wheels can be scrolled pointer hovers over the control (see Figure the keyboard. The pressed key is passed horizontally or vertically, this gives you 1). The disadvantage of this type of help to the event as a string so you can look at additional input from the user. Depending over an always-visible help display is that it to see what it is and do something with on the type of control, you could scroll the the help isn’t obvious and the user may not that information if you want. As mentioned control’s contents in a different manner (i.e., realize it is there. earlier, not necessarily useful with many faster or in larger increments), or perhaps Left - This sets or gets the left-most loca- controls. Also keep in mind that this event change a setting. The Slider control on the tion of the control. This is relative to the only gets called when this control has Hot Help window in today’s demo shows window, not the screen. Note that you’re the focus. Many basic controls, such as this with the following simple code: free to set this to a value off the window — Lines, never get the focus, or don’t keep that can be a useful way to hide a control it (PushButtons only have to focus while me.value = me.value + deltaX without deleting it. (Though if you do that, being pushed). you should disable it, since an off-screen control can still intercept user input and

42 November/December 2009 | REALbasic Developer | www.rbdeveloper.com

Figure 2: Before and After window resizing with various locked BevelButtons. Notice how the position and the shape of the buttons change depending on how their sides are “pinned” to the parent window.

could create confusion. For instance, an LockLeft - This locks the left side. parent would point to that enclosing object, off-screen text field could trap the user’s LockRight - This locks the right side. not the window. (That object’s parent typing but they wouldn’t see the results LockTop - This locks the top side. property would presumably point to the on-screen and would wonder what was MouseCursor - This allows you to set the window unless it was also nested, such happening to their text.) pointer cursor that is displayed while the as a RadioButton inside a GroupBox inside a LockBottom - This “locks” the bottom of pointer is within the control (if it’s not TabPanel. Be careful about nesting too deep, the control. Think of it as a stick-pin into overridden by setting it within the Application however, as that can cause complications the bottom side of the control, pinning it class or Window). REALbasic includes a and it’s not a good idea interface-wise.) to the window (or own parent object if this number of standard cursors within system. TabIndex - This is an integer value that is inside something else, like a GroupBox). cursors, such as a pointing finger, grabber controls the order of the controls on the That way if the user resizes the window (or hand, magnifying glass, etc. window so that when the user presses the parent object), the bottom of the control Tab key to switch between controls, the will move with the adjusted window size. switch happens in numerical order. Because there are four sides to a control, TabStop - If you set this to false, the user you can lock any or all of them for different cannot tab to this control. The default is effects. For instance, if you just want the Parent - This refers to the object that true. control to move with the window, just lock contains this control. That usually is the Top - This gets or sets the position of the one side. If you want the control to change parent window, but not always. Some top of the control on the window. Adjusting shape, lock several sides (see Figure 2 for controls, such as PagePanels or GroupBoxes, it will move the control. some examples). can enclose other controls. In those cases,

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 43 TrueWindow - This returns the actual window parent of the control, even if it’s deeply nested inside other controls. Visible - This sets whether the control is visible or not. (Handy Tip: controls that contain a lot of data, such as ListBoxes or text fields, can be slow to fill with data while visible. Set them to invisible, fill them with data, and then make them visible again for a speed up!) Width - This gets or sets the width of the control. Window - A reference to the parent window of the object.

RectControl Methods Standard methods implemented by RectControl objects are: AcceptFileDrop - This is where you set the file type of acceptable files that can be dropped on this control. You can call this Figure 3: Today’s awesome demo project. method multiple times, once for each file type. If you don’t do this, the file drop will be rejected. See my drag-and-drop article MouseX - The horizontal location of the in RBD 7.6. Shared Control Features mouse pointer, in pixels from the left edge AcceptPictureDrop - You call this if you want Now that we’ve covered the basic shared of the window (not the screen). the control to accept dropped pictures. features of controls by going over the events, MouseY - The vertical location of the AcceptRawDataDrop - Here you can specify properties, and methods of the RectControl mouse pointer, in pixels from the top of a specific type of data that can be dropped base class, there’s one more base object we the window. on the control. should examine. Name - The control’s name. You can change AcceptTextDrop - You call this if you want RectControl itself is based on a class called this programmatically if you want. the control to accept dropped text. Note that Control, and it has a few events, properties, PanelIndex - This gets or sets the panel there is a difference between dropped text and methods that are also inherited by all number this control is placed upon. It is and a dropped text file. If you want your other controls. Most of these will be familiar set to -1 if it’s not on any panel. control to accept both, you need set your to you, but just to be thorough, I’ll go over Scope - This lets you know if the control’s control to accept both. them briefly. scope is private or public. Private controls DrawInto - This is a rarely used command cannot be accessed from outside of their and has proven to be buggy and unreliable Control Events parent window. in my experience, but it’s a fun method to Controls have two basic events, Open TabPanelIndex - This gets or sets the tab experiment with. It basically allows you and Close, which are triggered when the panel number this control is placed upon. to draw the control into a graphics object. control is about to be opened and when it It is set to -1 if it’s not on any panel. You could use this to print a control, for is about to close. Window - The control’s parent window. instance (drawing it into a graphics object Within Open you can do any initializa- you are printing). tions needed, or set various attributes Control Methods Invalidate - Forces the control to imme- of the control (such a size, label, display There’s only one method, Close, which is diately redraw itself. It’s similar to Refresh characteristics, data, etc.). used to close the control. You should use but happens right away. It’s useful if you’ve Within the Close event you’d do any this with caution as attempting to access changed aspects of the control and need it to cleanup required (save data, dispose of a closed control will crash your program be updated. You can also call this specifying objects, save a setting, etc.). with a Nil Object error. Normally you the region (rect) to redraw. don’t need to use this as the control will NewDragItem - This creates a new drag automatically be disposed when its parent item when the user’s dragging away from Control Properties window is closed. Usually this is used for the control. You can specify the size of the Most Control properties are read-only: deleting dynamic controls that are part of dragged item. See my drag-and-drop article you cannot modify them (Name, PanelIndex, a control array. in RBD 7.6 for more. and TabPanelIndex are the exceptions). Many Refresh - Redraws the control when the of these properties are esoteric and rarely Conclusion system has time. needed. That’s all we have time for today, but it’s RefreshRect - Redraws just the specified Handle - The control’s handle. Used by a good start: we’ve actually covered 90% of portion of the control when the system advanced programmers only. (If you don’t the functionality of most basic controls! In has time. know what a handle is, you don’t need to part 2 I’ll cover some basic controls where SetFocus - This gives this control the focus. use this feature.) we’ll study the unique characteristics of When a control has the focus, key presses Index - The control’s number, if part of each control and how to use it. and other inputs are sent to that control. a control array.

44 November/December 2009 | REALbasic Developer | www.rbdeveloper.com From Scratch

ClipSaver by Brad Rhine Build a clipboard manager

you’ve cut and copied and allows you At a Glance Hello, my name is Brad to retrieve them when necessary. and I am addicted to having multiple RBD#8112 clipboards. The Adventure Begins I can’t help myself. I don’t remember And so we begin our bold and fateful Target Reader: exactly when it started, but I vaguely journey to build a clipboard manager Beginner remember how it happened. There was in REALbasic. Right off the bat, I Source Code: some sort of promotion or sale, and I know that we will have to make some No ended up with a free copy of one of the compromises. First, just to keep things RB Version Required: more popular clipboard managers out simple, we’re only going to worry about 2006+ there. I didn’t use it at first, but once I text that has been on the clipboard. got the hang of it, I was hooked. I loved Handling images, video, audio, and Platform(s) Supported: that my computer remembered the other arbitrary data is beyond the Mac OS X, Windows, Linux last hundred things I copied. It was so scope of this column and will be left About the Author: liberating. I could copy, copy, copy to as an exercise for the reader. Also, Brad Rhine is a database my heart’s delight with nary a thought some of the user interface goodness I administrator and webmaster to losing my precious memories. Er... had come to love about my previous who uses a variety of languages, memory. Random access memory, to clipboard manager (no, I’m not going including PHP, Ruby, and, be exact. And to top it all, the history to identify it by name, so don’t even of course, REALbasic. stayed there between restarts. So I ask) simply won’t be easily achiev- could copy something, restart my able in a cross-platform application, computer, and still paste the same so we’ll need to come up with a good thing. Those were good days. interface that can work on multiple operating systems. Trying Times But, on the other hand, we have an But alas, progress comes at a price. opportunity to improve on some things. Times change, and operating systems For example, our clipboard manager change, and things stop being compat- will feature time and date stamps, so ible, and sometimes they want to that we can know at a glance when charge for a minor point upgrade just we added something to the clipboard because you got a freebie a couple history. years back. And suddenly, for the In addition, wouldn’t it be great if same functionality you had before, our clipboard manager could keep you have to pay. multiple computers in sync with the Well, those of you who have been same clipboard history? As someone reading my column for long enough who uses a laptop in conjunction with will know my typical reaction to such several desktop machines at various a situation: Forget buying it; I can locations (home, office, etc.), I would build it! find that tremendously helpful.

A Brief Explanation Designing The System For those of you who have never Let’s focus now on how we want our used a clipboard manager and may clipboard manager to work. Obviously, not have made it through my rambling there will be a timer that runs at regular introduction, a clipboard manager intervals to capture the clipboard’s simply stores a history of items that contents, but let’s step back and figure out how we want it to behave for our

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 45 end user. Then we’ll lay out the inter- Finally, I dragged a Timer onto the to ClipBox. But at some point, we’re face and write the code to match the window and named it ClipTimer. I set going to want to do something with behavior that we want. its mode to 2 (so it fires repeatedly) all those clipboard history items. So Our clipboard manager should have and its period to 1000. let’s enable dragging and dropping an unobtrusive interface that sits in the from ClipBox. background, refraining from drawing Adding Some Code We’ve already set its EnableDrag attention to itself. It should only be Give MainWindow a new property: property to True, so all we have to noticed by the user when the user wants LastClip As String. do now is implement the DragRow to access the clipboard history. Now let’s open up the code editor event. The DragRow event gives us Duplicate items should be filtered for ClipTimer. In its Action event, two parameters: Drag As DragItem out of the clipboard history if they ClipTimer is going to do a lot of the and Row As Integer. Row, obviously, occur right next to each other. In heavy lifting for us. First, it’s going indicates which row of the ListBox is other words, if the user copies the text to check to see if the clipboard has being dragged. Drag is an instance of a “Hello, world!” two or three times in any text in it. If it does, it’s going to DragItem, something containing arbi- a row, it should only show up in our check the text against the last item in trary data (in our case, plain text) that application one time. However, if the our clipboard history. If it matches, it can be dragged from one program to user copies “Hello, world!”, then copies bails out. If it doesn’t match, it adds another. What we’ll to do is set Drag’s “foo”, then copies “Hello, world!” again, it to ClipBox, along with a time and Text property. “Hello, world should show up twice, date stamp. But before any of that, we have to separated by “foo.” So the first thing we need to do is make sure we have a valid, existing Our clipboard history should be easily instantiate a new Clipboard object and ListBox row: and quickly searchable, giving our end a new Date object: user three ways to find information: If Row = -1 Then Return False by scanning the clipboard history, by Dim C As New Clipboard looking for a specific time and date, Dim D As New Date Returning False tells REALbasic that or by using our search feature. we haven’t done anything to handle Finally, we’ll need to discuss how our Then we check to see if the clipboard the Drag event, and that the system clipboard manager will keep multiple contains any text, and we exit the should do whatever it would normally computers in sync. More on that later. method if not: do, which is, in this case, nothing. Now For now, let’s turn to the interface. to set Drag’s Text property: If Not C.TextAvailable Then Return Building The Interface Drag.Text = Me.Cell(Row,0) Create a new project in REALbasic. Next, we check to make sure the text I’m using REALbasic 2008 Release 5.1. on the clipboard doesn't match the last Finally, we need to return True, to Yes, I’m a bit behind the times, but I item we saved: tell REALbasic that we have indeed like to stay a few versions behind in handled the Drag, and that it no longer this column to accommodate those If C.Text = LastClip Then Return needs to worry about doing the right who don’t necessarily live on the thing: bleeding edge. Finally, we've made it through all I called my project ClipSaver, but I those hoops and conditions, and we add Return True encourage you to come up with a name the text to ClipBox, along with our time that’s far less lame than mine. and date stamp (while assigning the Go ahead and run the project to see To get things started, I renamed current clipboard text to LastClip): what we’ve got so far. You should now, Window1 to MainWindow and opened after copying a few things to load up it up. Its default size of 600 pixels by LastClip = C.Text your clipboard history, be able to drag 400 pixels will be perfect for design ClipBox.InsertRow(0,C.Text. items out of the ListBox and into other time, but I did make it resizable. ConvertEncoding(Encodings.UTF8)) applications. I also added a ListBox to the window ClipBox.Cell(0,1) = D.SQLDateTime and gave it two columns. I set the ClipBox.Refresh Data Storage column headers to “Clipboard” for Quit the application and run it column zero and “Date” for column One thing you may notice is that again. Did you notice the problem? one. I also set the ListBox’s LockLeft, we’re going to convert any text we Our clipboard history is lost between LockRight, LockTop, and LockBottom find to the UTF-8 encoding. I’m not application runs. That is, in very tech- properties to True, so that it resizes with sure of technical reasons behind this, nical terms, a bad thing. We want our the window. I gave it the name ClipBox. but I found that I got the cleanest clipboard to be saved not only between I also made sure its EnableDrag prop- text that way. If any loyal reader can application runs, but between restarts, erty was set to True. offer an explanation or alternative, and ideally on multiple computers. In addition, I placed an EditField in I’m all ears. So it goes without saying that we’ll the upper right corner of the window need to store the clipboard history and named it SearchField. I set its Getting Data Out somewhere on disk. The questions are LockTop and LockRight properties to So far, so good. We have an applica- where and how? What format should we True. I also placed a StaticText to its tion that’s monitoring the clipboard use and where should we store it? This left to act as a label. and appending any new text it finds brings up a related question: how do

46 November/December 2009 | REALbasic Developer | www.rbdeveloper.com we store the data in such a way as to enable simultaneous details to sweat out with this implementation, but it has access from multiple computers. the potential to be very successful. We have a few possibilities for data storage. One would A third possibility, and the last that we’ll entertain, is be a simple delimited text file. On the plus side, this would to use a database server. On the positive side, this should be very easy to implement in REALbasic, and it should be make synchronizing our clipboard history a piece of cake: relatively fast, as long as we limit our clipboard history to a few SQL queries here and there, and it’s done. It would a reasonable number of entries, such as one hundred. On also make implementing our search feature very easy. But the negative side, access from multiple computers could with great upsides often come great downsides. It would be problematic. Location of the file could be as simple as require setting up a database server, such as REAL Server, using a service like DropBox, but multiple copies of our PostgreSQL, or MySQL, which is beyond the skill level of clipboard manager could potentially be reading and/or many developers. And the server would always have to be writing to the file at the same time. Unless managed very available, so a machine that’s accessible across the internet carefully, that could end up not working at all, or worse, would be best. Not everyone has access to such a computer destroying user data. or server setup. Another possibility is to designate one computer as the master and develop a protocol to manage clipboard A Cliffhanger? Seriously? synchronization over a network. On the up side, this stands So what do we do? How will we choose? Tune in next an excellent chance of keeping the history synchronized time to find out. Until then, happy coding! in real time. There are multiple downsides. For starters, By the way, I’ll make the source code available in the next managing network transfers like that isn’t really for the issue (when there’s more to show). faint of heart. It’s not terribly hard if you know what you’re doing, but for newcomers to either REALbasic or networking in general, it can be a rather daunting task. Secondly, what happens when the master computer is offline? Do we cache our multiple histories locally and them merge them when the master computer is available? There would be a lot of

Get RBD Year 7 in print form!

• Quality perfect-bound book • 330+ pages • Color cover, black insides • Complete issues 7.1–7.6 • 25% off retail price for current RBD subscribers

Order today at www.rbdeveloper.com

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 47 BKeeney Briefs

Reporting Tools by Bob Keeney [email protected] Database reporting

REALbasic arena for many years. Their At a Glance It’s been a pretty amazing external designer is very nice but a little year and a half since Real World 2008. buggy. It also only works with Valentina RBD#8113 During the conference, between sessions, databases, which is either a strength or and even in the after-hours events, I’ve weakness depending upon your needs. Target Reader: had conversations with many REALbasic The Valentina Reports tool does a good Beginner developers about the lack of reporting job with Sub-Reporting. Like On Target Source Code: options for REALbasic. I’ve even lobbied Reports, Valentina Reports can be used No every REAL Software employee that outside of your RB application. Platform(s) Supported: I could bend the ear of for a built-in RSReport (http://www.rothsoft.ch/realbasic/ Mac OS X, Windows XP, Linux, reporting tool. rsreport/) is a non-banded reporting tool. Mac Classic The community obviously thought it Non-banded reporting tools have you was a pretty important thing as well. place every object (even repeating data About the Author: In the 2008 Association of REALbasic fields) on the page and you have to keep Bob is the owner of BKeeney Professionals “Wish List” Survey, it was track of page placement for pagination Software located in Kansas City. the top rated wish among ARBP and purposes. Even though it’s not a ‘banded’ He is a founder and the current non-ARBP survey takers alike. REAL reporting tool it’s fairly easy to create President of the Association of Software was listening as well. repeating lines of data. RSReport is REALbasic Professionals. When I spoke at the REALbasic Summit also introducing a report designer using in Boulder, Colorado in late September external formats that should be available of this year, I was pleased to do an hour by the time you read this. The report long session on nothing but reporting viewer and designer are both drop-in tools. Instead of just one, there are now RB container controls. several options! Here is a summary of Einhugur Reports (http://www.einhugur.com/ what is available. EinhugurReports/) is currently in development On-Target Reports and it’s hard to tell if this product will (http://www.ontargetreports.com) was the only ever see the light of day considering the commercially available option a year and a competition. It makes extensive use of half ago. This ‘banded’ the Einhugur plugins which makes this report designer allows ‘free in development’ tool not so free. When I spoke at the REALbasic you to save your report The tool has a drop in viewer/designer templates to disk and (They are one component!) which is Summit in Boulder, Colorado in late use them in your interesting and it makes use of an external REALbasic application. file format as well. September of this year, I was pleased Many developers have Turbo-Report (http://www.turboreport.com/) been frustrated with is an open source non-banded report to do an hour long session on nothing On-Target in recent tool. Like RSReport you have to place all years, but a recent elements on the page so it takes a little but reporting tools. Instead of just one, update and a push for bit more time to set up and use. It has better support makes an interesting ‘table’ feature that makes there are now several options! On Target a reasonable repeating rows simple to use. choice. RBRW (http://code.google.com/p/rbrw-core/) Valentina Reports is another open source reporting tool (http://valentina-db.com/index. and it’s been ported to REALbasic from php/en/products/valentina-reports) is a banded C++ by its creator Andy Dent. It’s a big, reporting tool and a relative newcomer to the reporting field but they’ve been in the

48 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Figure 1: On-Target Reports.

Figure 2: REALbasic’s Report Designer.

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 49 Figure 3: Valentina Reports.

complex project that has some interesting features and is definitely worth looking at. The new kid on the block is REAL Software’s reporting tool that I’m dubbing REAL Reports (for lack of a better name) Write for RBD! which was introduced in RB 2009 Release 4. The banded report designer is integrated into the REALbasic IDE and is fairly easy to use and it works with any database supported by Have an idea for RB as well as other types of data sources. It’s a little too early an article? Want to to tell how well this tool will work for beginning and advanced RB users, but since it ships with RB it’s now the de-facto stan- contribute a Review or dard for reporting tools and all others will be compared to it from now on. Postmortem? I wouldn’t hesitate to look at any of these reporting tools. I was surprised at how well they all worked despite some being relatively new or being sparsely documented. Depending upon We’re always looking your needs, each one has some interesting strengths and weak- for new material! nesses. All are inexpensive when compared to their counterparts available in the Windows world. What they all lack, however, is runtime interaction. Runtime Send a query letter to interaction means allowing the user to click on a report object and receiving an event at runtime that allows the developer to [email protected] describing present a more detailed report (or do some other interesting your idea. If we’re interested, we’ll things). Some call this ‘drill down’ capabilities. An example of this would be a Chart of Accounts report typical in many accounting contact you and establish a schedule. applications. If the Vehicle account seems really high, the user could double click on it and be presented with an account detail report rather than running the report manually. Read our Writer’s Guidelines: Exporting options are relatively limited as well. A few have PDF export but nearly all have some sort of graphical export. http://www.rbdeveloper.com/ This is a far cry from the Microsoft Office and email format options available for Windows developers using Crystal Reports writerguidelines.shtml and Active Reports. Hopefully it won’t take another 18 months to get some more advanced features. Happy coding!

50 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Databases for REAL

Reporting with REALbasic by Paul Lefebvre [email protected] REALbasic 2009 Release 4

At a Glance On September 29th, REAL Software shipped REALbasic 2009 Release 4. Its big new feature? You guessed it: reporting! That’s right, the REALbasic IDE now has a built-in report designer! So without further ado, let’s take a RBD#8114 look at it. Target Reader: Intermediate A Quick Overview RB Version Required: To create a report in REALbasic 2009r, you first need to add a report object 2009r4 to your project. To do this select Project->Add->Report. You can also edit your Source Code: toolbar to add an “Add Report” button. Figure 1 shows what the report designer No looks like. As you can see, it has three main areas. A list of controls on the left, the main About the Author: editor window in the center and the properties editor on the right. REALbasic Paul Lefebvre has been using supports these report controls: REALbasic for 8 years and is the owner of LogicalVue Software, ■■ Field RBDevZone, and a founding ■■ Label member of the Association of ■■ Picture REALbasic Professionals. ■■ Line ■■ Oval ■■ Rectangle ■■ RoundRectangle

Just drag one of these controls to the report editing area to add it to the report. Each control that you add, has its own set of properties that you can modify. In addition, each control has two events associated with it (AfterPrinting and BeforePrinting) where you can put your own code. The report designer also supports grouping and a wide variety of data sources. For more information, be sure to check out Chapter 8 in the REALbasic User’s Guide and to look up the various reporting classes in the Language Reference.

Creating a Report To start using REALbasic reports, launch REALbasic 2009 Release 4 and create a new project, which we’ll call RBDReport. Add a new report object to this project and call it MyFirstReport. Double-click the report to start editing it. We’ll start simple, so just drag a Label onto the PageHeader section of the report designer. Change its name to HeaderLabel and play around with the properties. I made mine bigger, increased the font size and centered it. Now let’s add a couple fields to the report. Drag two Fields to the Body section of the report designer. Change their DataField properties to FirstName and LastName, respectively and position them next to each other (see Figure 2). Next, we want to actually view the report. Unfortunately, you’ll have to do a bit more work here. The designer does not have built-in preview capability (no, File->Print does not actually print a preview of the report).

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 51 Figure 1: REALbasic Report Editor

row = "Bob,Roberts" Creating A DataSet mData.Append(row) First we’ll need some data for the report. We’ll create our own simple class that will always return the same data. You row = "Bilbo,Baggins" can also use a database as a data source or have a class that mData.Append(row) pulls data from text files (or wherever else you might have your data). We’ll use the class method as it’s a bit trickier mCurrentRow = 0 to get started with. Using a database RecordSet is quite easy so you can just refer to the REALbasic documenta- NextRecord tion for that. This method increases our internal row counter: Create a new class called SimpleDataSet and specify Reports.DataSet as its Interface. You’ll be prompted by mCurrentRow = mCurrentRow + 1 REALbasic to have it add the methods for the interface for you. You should answer Yes. When you open SimpleDataSet, EOF As Boolean you’ll now see that it has several methods which need to This method simply returns True when we’ve reached be implemented. Before we do that, though, we’ll need to the end of the data. create a couple properties to help track our state: If mCurrentRow > mData.Ubound Then Private mCurrentRow As Integer Return True Private mData() As String Else Return False Run End If This method contains code to initialize the data. In our case we’ll just populate a simple array with a couple names Field(idx As Integer) As Variant and set it to start at the first row. Code: This method returns a specific field value for the current row. The field index is a 0-based integer: // DataSet consists of two columns, FirstName and LastName (separated by commas) // Get the specified field data for the current row Dim row As String Dim row As String

52 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Figure 2: Our Sample Report Layout

row = mData(mCurrentRow) Select Case fieldName Case "FirstName", "LastName" Dim columns() As String Return 5 // Text columns = SplitB(row, ",") End Select

Return columns(idx) Displaying and Printing the Report Now that we have some sample data, we can go ahead Field(name As String) As Variant with displaying and printing the report. Open the default This method looks up the field data based on the fields window in the project and add the following: name. We just call the above Field implementation to get this: ■■ a Canvas control and name it ReportViewer ■■ a PushButton and name it RunReportButton Select Case name ■■ a PushButton and name it PrintReportButton Case "FirstName" ■■ a method called RunReport(print As Boolean) Return Field(0) ■■ a property: Private Property mCurrentPage As Picture Case "LastName" Return Field(1) Now we can add the necessary code. We’ll start with the Else RunReport method since it is where all the work is done. Return Nil We create our DataSet and pass it to the report engine. Note End Select the different code paths when printing the report versus just displaying it: Type(fieldName As String) As Integer This method returns the data type of the specified field Dim ps As New PrinterSetup name. Since our simple data set only has two fields and Dim output As Graphics they’re both Strings, the code is simple: If print Then

November/December 2009 | REALbasic Developer | www.rbdeveloper.com 53 Figure 3: The Completed Report

If ps.PageSetupDialog Then End If output = OpenPrinterDialog(ps, Self) To run the report when the Run Report button is clicked, End If the Action event is this: End If RunReport(False) Dim ds As New SimpleDataSet And lastly, the Print Button code is this: Dim rpt As New Report rpt = New MyFirstReport RunReport(True)

If rpt.Run(ds, ps) Then That’s it. You can now run the project, click the Run Report Dim rptPage As Reports.Document button and see your report displayed (see Figure 3). Click rptPage = rpt.Document the Print Report button to be prompted to print it. If rptPage <> Nil Then If print Then Summary rptPage.Print(output) It’s great to see reports as a built-in feature of REALbasic. Else The designer is easy to work with and it is nice to be able mCurrentPage = rptPage.Page(1) to use anything as a data source. Features I’d like to see ReportViewer.Refresh added: End If ■■ an included report viewer rather than having to create End If our own End If ■■ an ability to preview the report while designing it Our Canvas needs to paint the picture, so it’s Paint event ■■ a way to allow end users to create reports looks like this: ■■ a way to load reports externally at run-time

If mCurrentPage <> Nil Then g.DrawPicture(mCurrentPage, 0, 0, Me.Width, Me.Height)

54 November/December 2009 | REALbasic Developer | www.rbdeveloper.com Diets leaving you hungry?

Learn the secrets to huge meals that let you lose weight in Marc Zeedar’s new book, Eating BIG While Eating Lean. Available in print and PDF from www.eatingbig.com

Get RBD in book form!

■■ Quality perfect- bound books ■■ 300+ pages each ■■ Color cover, black insides ■■ Complete issues of each year ■■ Discount for current RBD subscribers

Order today at www.rbdeveloper.com New to REALbasic Developer? You need all the issues! Order back issues in Print or on CD!

Volume 1 Volume 2

All Six CDs Now Available!

Volume 3

Volume 4

Printed back issues available while supplies last! CDs Include Issues in high-res PDF format, searchable database, project files, REALbasic University archive, and more! Volume 5 Order today—this offer is for a limited time! www.rbdeveloper.com/cd/ REALbasic is a registered trademark of REAL Software, Inc. REALbasic Developer is not affiliated with REAL Software.