Basic

1053

Transcript of Basic

  • Welcome to REALbasic University! .................................................................................. 5 Exploring the REALbasic IDE ........................................................................................... 9 Working with Interface Elements ..................................................................................... 15 The Code Inside ................................................................................................................ 21 Helpful REALbasic........................................................................................................... 30 The Problem...................................................................................................................... 41 Starting A Project.............................................................................................................. 48 Adding Dialog Boxes........................................................................................................ 60 Adding a Module .............................................................................................................. 72 Finishing the Open File Routine ....................................................................................... 84 The buildMenu Method .................................................................................................... 95 The Rename Dialog ........................................................................................................ 106 Compiling a Standalone GenderChanger........................................................................ 121 Review: REALbasic for Dummies ................................................................................. 131 Programming for the Rest of Us ..................................................................................... 135 Two Sample In-House Programs .................................................................................... 146 REALbasic Animation: Introduction to Sprites, Part I ................................................... 162 REALbasic Animation: Sprites Part II ........................................................................... 174 REALbasic Animation: Sprites Part III .......................................................................... 188 REALbasic Animation: Sprites Part IV.......................................................................... 197 REALbasic Basics .......................................................................................................... 205 REALbasic Basics II....................................................................................................... 216 REALbasic Basics III ..................................................................................................... 225 REALbasic Basics IV ..................................................................................................... 234 A New Look.................................................................................................................... 246 CSS Update..................................................................................................................... 259 Creating Custom Classes II............................................................................................. 271 RBU Pyramid I ............................................................................................................... 277 RBU Pyramid II .............................................................................................................. 284 RBU Pyramid III............................................................................................................. 292 RBU Pyramid IV............................................................................................................. 303 RBU Pyramid V.............................................................................................................. 315 RBU Pyramid VI............................................................................................................. 324 RBU Pyramid VII ........................................................................................................... 334 RBU Pyramid VIII.......................................................................................................... 345 RBU Pyramid IX............................................................................................................. 359 RBU Pyramid X.............................................................................................................. 370 RBU Pyramid XI............................................................................................................. 382 RBU Pyramid XII ........................................................................................................... 392 RBU Pyramid XIII.......................................................................................................... 405 RBU Pyramid XIV.......................................................................................................... 421 RBU Pyramid XV: Undo Part 1...................................................................................... 438 RBU Pyramid XVI: Undo Part 2 .................................................................................... 450 RBU Pyramid XVII: Polishing Part I ............................................................................. 462 RBU Pyramid XVIII: Polishing Part II........................................................................... 474 RBU Pyramid XIX: Polishing Part III ............................................................................ 485

  • RBU Pyramid XX: Bug Fixing....................................................................................... 496 RBU Pyramid XXI: Wrapping Up.................................................................................. 512 An Exciting Announcement............................................................................................ 521 SpamBlocker: Part I........................................................................................................ 528 SpamBlocker: Part II....................................................................................................... 536 Zoomer: Part I ................................................................................................................. 545 REALbasic Developer Magazine Update....................................................................... 555 Zoomer: Part II................................................................................................................ 559 SimplePaint: Part I .......................................................................................................... 570 SimplePaint: Part II......................................................................................................... 581 SimplePaint: Part III ....................................................................................................... 591 SimplePaint: Part IV ....................................................................................................... 601 SimplePaint: Part V......................................................................................................... 609 About the Delay .............................................................................................................. 617 SimplePaint: Part VI ....................................................................................................... 617 Monotab: Part I ............................................................................................................... 624 Monotab: Part II.............................................................................................................. 632 FontPrinter: Part One ...................................................................................................... 645 FontPrinter: Part Two ..................................................................................................... 655 FontPrinter: Part Three ................................................................................................... 668 FontPrinter: Part Four ..................................................................................................... 676 FontPrinter: Part Five...................................................................................................... 687 Review: REALbasic 4.5 (Part 1) .................................................................................... 697 Review: REALbasic 4.5 (Part 2) .................................................................................... 710 Review: REALbasic 4.5 (Part 3) .................................................................................... 719 Review: REALbasic 4.5 (Part 4) .................................................................................... 726 DoRbScript: Part I........................................................................................................... 737 DoRbScript: Part II ......................................................................................................... 744 DoRbScript: Part III........................................................................................................ 755 DoRbScript: Part IV........................................................................................................ 761 Book Review: Learning REALbasic Through Applications .......................................... 769 OOP University: Introduction......................................................................................... 775 OOP University: Part One .............................................................................................. 781 OOP University: Part Two.............................................................................................. 788 OOP University: Part Three............................................................................................ 794 OOP University: Part Four.............................................................................................. 799 OOP University: Part Five .............................................................................................. 806 OOP University: Part Six................................................................................................ 811 OOP University: Part Seven ........................................................................................... 818 OOP University: Part Eight ............................................................................................ 827 OOP University: Part Nine ............................................................................................. 834 OOP University: Part Ten............................................................................................... 845 OOP University: Part Eleven .......................................................................................... 853 OOP University: Part Twelve ......................................................................................... 864 OOP University: Part Thirteen........................................................................................ 873 OOP University: Part Fourteen....................................................................................... 882

  • OOP University: Part Fifteen.......................................................................................... 892 OOP University: Part Sixteen ......................................................................................... 906 OOP University: Part Seventeen..................................................................................... 919 OOP University: Part Seventeen..................................................................................... 932 OOP University: Part Nineteen....................................................................................... 941 OOP University: Part Twenty......................................................................................... 948 OOP University: Part Twenty-One................................................................................. 954 OOP University: Part Twenty-Two ................................................................................ 962 OOP University: Part Twenty-Three .............................................................................. 969 OOP Intermission: iConversation Part One.................................................................... 975 OOP Intermission: iConversation Part Two ................................................................... 985 Book Review: REALbasic Visual Quickstart Guide ...................................................... 992 OOP University: Part Twenty-Five ................................................................................ 995 OOP University: Part Twenty-Six ................................................................................ 1005 OOP University: Part Twenty-Seven............................................................................ 1012 Debugging Part One...................................................................................................... 1018 Debugging Part Two..................................................................................................... 1023 Debugging: Part Three.................................................................................................. 1034 Debugging: Part Four.................................................................................................... 1041 Debugging: Part Five .................................................................................................... 1046

  • REALbasic University: Column 001

    Welcome to REALbasic University! RBU is a new weekly tutorial column on Macintosh programming, using REALbasic, the development environment I like to call the "heir to HyperCard."

    Like HyperCard, REALbasic features an elegant IDE (Integrated Development Environment), a simple script-like language, and powerful automatic features that make writing your own software programs almost as easy as drawing a picture of what you want it to look like.

    Unlike HyperCard, however, REALbasic applications are real Macintosh applications. They may not have all the speed of C++, and not everything in REALbasic is as simple as it should be, but you might be surprised how many REALbasic-created applications you already have on your computer. Many popular programs, such Aladdin System's Intellinews or Toby Rush's NetCD were created with REALbasic.

    Those of you who read my summer series on Mac programming as part of my regular Less Tangible column on MacOpinion should be familiar with me. I'm the author of Z-Write, a new kind of word processor which I wrote entirely in REALbasic. I'm not a classically trained programmer, though I did take an introductory course in programming in college. That should be a help in writing this column, as that means if there's a naive mistake to be made, I've no doubt done it. Part of my teaching philosophy is that to learn, you've got to make mistakes -- so we'll be exploring common mistakes and solutions within these columns. I'm not necessarily trying to teach you proper programming techniques, but help you learn enough to develop quick solutions for real-life problems you face.

    I have one goal with this column: I want to teach people how to program. Far too many people think programming is a horrible, scary, complicated thing full of mathematics and obtuse jargon, which it is, but it doesn't have to be that way. Writing your own program can be one of the most rewarding experiences you'll ever have. Learning programming will reduce the fear and mystery of computers and increase your amazement at the sophistication and occasional pure stupidity of modern software.

    REALbasic University is going to start at the beginning, assuming you, the reader, has never even written an AppleScript. Most of these columns are going to be a series of tutorials, with lots of step-by-step hand holding, so no matter what your Mac experience, you'll be able to follow along and learn REALbasic. (These columns will build on one another, so the archives will be invaluable for going back later, to relearn a particular technique or start of a tutorial series.)

    Thus the first few columns will be extremely basic and may not appeal to REALbasic veterans. Take heart! While I'm gearing this toward the novice, eventually we'll be

  • writing some real projects -- games and handy utilities -- and along the way we'll be tackling specific problems that REALbasic newbies often face, like adding a cool "About Box" to your program, or saving files with your program's custom icon.

    Send in Your Questions

    At the end of each column, I'll be answering select reader questions -- send your REALbasic University questions to [email protected]. I can't promise to answer every question, and keep in mind I'm not going to be writing a novel for each answer, so priority will go to simpler questions that have universal appeal. Keep your questions specific. (A general query like "How do I write my own web browser?" will be rejected.) I'm also open to suggestions for projects and issues you'd like me to cover in future columns.

    Things You'll Need

    Obviously, you'll need a copy of REALbasic. You can download a free demonstration copy of REALbasic from REAL Software. The demo is fully functional for 30 days and applications you create will stop working after five minutes, but it's sufficient for you to get started learning programming. When you're ready to buy REALbasic, REAL Software will simply send you a registration number which will fully activate your copy.

    REALbasic is sold in Standard and Professional versions. I recommend the less expensive Standard version unless you have particular needs for compiling Windows applications or database programming (the two main features the Professional version adds). The Windows compiling feature isn't bug-free (to say the least), and it's quite complicated making a program that will run on both Windows and Mac OS. Besides, the Standard version lets you try out the Professional features, and you can always upgrade later if you decide you need to.

    If you don't already have a copy, get ResEdit 2.1.3 from Apple as we'll eventually need that. A graphics program like Adobe Photoshop or the shareware GraphicConverter will also be useful.

    (Note: as of February 12, 2001, the current version of RB is 3.0. This newly released version features an improved interface and compiling for Mac OS X. For the moment, Im still using RB 2.1, so some of my screen shots might look a little different. Ill be switching to 3.0 soon. When you download RB 3.0, you can download either the "Classic" version, which runs under Mac OS, or a version that only runs under OS X.)

    Installing REALbasic

    Once you've downloaded REALbasic, simply decompress it with Stuffit Expander and drag the resulting "REALbasic 3.0" folder to a convenient place on your hard drive.

  • The first thing I usually do after installing REALbasic is to increase the amount of memory allocated to REALbasic. REALbasic programs tend to use a lot of RAM, and since you have very little control over how that RAM is used, your program will probably just crash if it runs out of memory. The simplest solution (other than bugging REAL Software to give us better memory management) is to allocate plenty of memory to your programs. Within the REALbasic IDE (Integrated Development Environment, a fancy way of saying "the editor where you write programs") you'll need even a little bit more memory, since the editor itself uses a few megabytes. I usually double the default allocation; if I'm using a machine with plenty of RAM, I'll add twenty megs. (Keep in mind that while writing your program, before you make it more efficient, you might inadvertently use more memory than you think.)

    So while you're thinking about it, select the REALbasic application icon, do the "Get Info" command, and increase the memory partition.

    Starting Your First Project

    When you launch REALbasic, it opens a blank, untitled project. A project is your program's source. It contains everything you create for your program: code, windows, menus, resources like sounds and graphics, etc. It is very important that you manage your project and everything associated with it carefully.

    For instance, a typical project will include graphics: icons, pictures, etc. You can place these in your project and REALbasic will show them, but they aren't actually saved in your project file. Instead, RB (I'll abbreviate REALbasic as RB occasionally) simply includes a reference to the original file. This makes it easy to update your graphics (just edit the original file), but don't you dare throw away the original graphic or your project won't work! (REALbasic will complain and ask you to find the graphic when you try to compile your program.)

    What you should do is create a folder in the Finder for your project. I name mine the name of my project. Inside that folder I sometimes have other folders for graphics and other resources (help text, notes, sounds, etc.). This keeps everything organized. (On larger projects, I have an "old stuff" folder where I put old copies of my project, graphics I had planned to use but I'm not any longer, layered Photoshop files, etc. That way I'm not permanently throwing away something I might later want, but it's not in my active area.)

  • Advanced Tip: I do most of my programming on my laptop, but I also have a desktop machine and sometimes I switch between the two, depending on what I'm doing. I've found creating a small disk image file (I use Apple's DiskCopy program and create a 10MB or 20MB disk image) for my project is a great way to keep everything with a particular project together. Since it's a disk image, I can create folders and files within it, yet it's just a single file, ideal for transporting between machines. (It's also convenient for making backup copies of your entire project by just duplicating a single file.)

    Next Week

    We'll explore the REALbasic IDE and learn our way around.

    .

  • REALbasic University: Column 002

    Exploring the REALbasic IDE We'll begin our RB journey by exploring the IDE (Integrated Development Environment) -- the editor where we create our program. REALbasic's editor is incredibly nice, though it does have some limitations (which we'll eventually cover in later columns).

    There are basically three key areas of the IDE: the Tools Palette, your project window, and the Properties window. These should be visible at all times as you'll constantly be using or referring to them.

    In case you're not using REALbasic right this second, here's a graphical look at the IDE. (Click to see the larger version.) [Note: these screenshots are from version 2 of REALbasic. The RB 3.0 IDE is similar, but includes new toolbox icons.]

    First, note that (nearly) every program you create needs a window. A window is where you'll put interface elements, such as popup menus, checkboxes, and text fields. You can't put an interface element (also called a control) like a checkbox into your project -- you must place it on a window that's inside your project.

    The default project that RB creates when you first launch it includes everything you need for a very simple project: there are some basic menus (at minimum your program needs a Quit menu item) and a blank window (called Window1). In fact, you can even run this project -- you've created a very simple (and useless) application!

    When you run a project (choose "Run" from the Debug menu or press Command-R) you are telling REALbasic to compile your program (assemble all your project's elements and translate your code's English-like syntax to computer-talk) and immediately activate the resulting new program. When you run a program within the IDE, RB does not create a new program on your hard drive. Instead, the program is loaded entirely into memory and run as though you double-clicked its icon on the hard drive.

  • Why run a program in memory instead of creating a "stand-alone" application? Two reasons: speed and debugging. Compiling to memory is faster, and while you are programming you'll find you compile your project frequently, to test your code. Debugging is the process of finding and fixing errors in your program. REALbasic has an integrated debugger which is made available when you run a program within the IDE, and it can help you find the source of your problem.

    Another advantage of running your program within the editor is that if you accidentally put your program into an "infinite loop" (basically the program waits for a condition that will never happen, such as 5 equalling 10) you can cancel the running program by pressing Command-Shift-period.

    Here's what the empty project looks like when running, and in "debug" mode. (Click to see the larger picture.)

    We'll get into using the debugger in future columns, but for now I don't want you to be confused when you run your program and yet can still see your project windows behind your application. The IDE and your program look an awful lot alike. The most significant difference is the menubar at the top. Learn to keep an eye on that so you can tell if your program is running or you're in the IDE.

    To switch to the IDE, simply click on any of the background windows (such as the project window). Your application is suspended until your reactivate it. To switch back to the running program, choose "Run" again from the Debug menu or press Command-R (clicking on the deactivate program window does nothing).

    For now, play with this a bit. Run the empty project, use the menus, switch between the IDE and your program, etc. Try it a couple times until you've got the hang of it. You're going to be spending a lot of time in the REALbasic IDE, so get used to it.

    (Note: you can even edit your program in the IDE while it is running! We'll get into this more later, of course, and there are limitations to this feature, but being able to make changes to a "live" program is a significant time saver as RB only has to recompile the code you changed, not the entire program.)

  • When you're ready to continue with this tutorial, quit from your program if it's running (choose "Quit" from the file menu) to return to the IDE (don't quit REALbasic -- quit your program).

    The second most important part of the IDE is the Properties window. This is a floating palette you can position anywhere you'd like (the default location is fine, though you might want to change the size). The Properties window lets you change settings on various objects within REALbasic. For instance, if you select "menu" in your empty project window, the Properties window will go completely blank. That's because the menu object has no settings (properties). Try selecting Window1 -- suddenly the Properties window is full of various settings, such as the name of the object (Window1), the size and kind of the window, etc. Most of these settings are unique the type of object selected, though some, like the "name" field, are common to all objects (every object in REALbasic has to have a name so you can refer to it).

    The third most important part of the IDE is the Tools palette. Why this is called the tools palette, I don't know. Tools, by definition, let you modify your content (i.e. a paint brush adds a brush stroke to your canvas). In REALbasic the Tools palette is more like a library of interface elements: you can drag items from the library palette to put them into your program.

    Here's a brief explanation of the palette (click for full-size view):

    Your First Program

    Now you're going create your first REALbasic program! This is going to be a useless and very simple application, but it will show you how powerful REALbasic can be.

    Starting with the default, empty project automatically created when you launched REALbasic, we're going to drag a few interface elements to your program's main window. Interface elements are often called controls, or user controls, because they are things the user can interact with, such as a scrollbar or checkbox.

    First, let's drag the item that looks like a "OK button" onto your project's window. Don't worry about where you put it -- stick it anywhere you'd like (you can always move it later). Notice that the button will be named "Untitled" not "OK" (but you can also change

  • that). While the button is selected (notice the black handles at each corner) the Properties window will display the fields that allow you to change the size and content of the button. For now, leave these alone. You can come back later and play with these settings.

    Now drag the checkbox icon to your window. It also is untitled, which is fine for now.

    The third item we want is an Editfield -- that's a text editing area. It looks like this: . Drag it onto your window and we're done.

    That was a lot of work (ha ha), so let's save our project before we continue. We'll called it -- the pi character is created by holding down the Option key and

    pressing "p". (This convention is a Mac programming tradition. You don't have to follow it, but it's a good idea.)

    Now that our project is saved, let's try running it. Joyful, isn't it? You haven't typed a single line of code, yet you have a working button, checkbox, and text editing area! Even more amazing, the menus also work: try copying and paste text in the editfield.

    That's it for a mild introduction to REALbasic. Next week we'll add features to this demonstration project and actually type some code!

    Letters

    I received a number of positive e-mails about last week's debut column, with one detraction. It came from Scott Raney, President of MetaCard Corporation, who objected to my terming REALbasic as "the heir to HyperCard." He writes:

    There is currently only one true "heir to HyperCard" and that is our product MetaCard which actually can import HyperCard stacks and run HyperTalk scripts (something that anyone who knows both products will tell you is not now, nor will ever be, possible with REALbasic). Not only that, but MetaCard applications also run unmodified on Windows and all popular UNIX systems, even the first of which REALbasic still has major trouble doing. Of course, productivity-wise there is no comparison between the two products: by the time you've got all your variables typed and your program compiled, a MetaCard developer will have his much smaller and easier-to-maintain application already debugged, which is the true benefit of using a scripting language instead of a third-generation language.

    That's great. I tried MetaCard years ago, when it was quite primitive (it showed great promise), but I wasn't aware it was still in development. I'll have to examine it sometime.

    I agree that REALbasic is not HyperCard. If you're interested in a HyperCard-like product, look at MetaCard or SuperCard.

  • But I still stand by my statement. My point comparing REALbasic to HyperCard is that HyperCard allowed non-programmers to create sophisticated software. If you look back at the early years of the Macintosh, many innovative freeware and shareware products were produced in HyperCard by non-programmers. These days, software has become much more sophisticated, and I doubt you could market (or even give away) such simple programs, but at the time, HyperCard projects were powerful and amazing.

    What delights me about REALbasic is that it is almost as easy to use as HyperCard was, but with professional quality results. (Please note that I'm not saying that SuperCard and MetaCard are not professional programs; I'm talking about HyperCard, which hasn't been updated in years.) For some users, a scripting environment is more appropriate and faster, but others need something between scripting and C++.

    Joe Strout (from REAL Software) writes:

    I like what you're doing with RBU. One small correction: you write "When you download RB 3.0, you can download either the 'Classic' version, which runs under Mac OS, or a version that only runs under OS X." Not quite true, since the Carbon version runs on any version of MacOS from 8.6 to OS X (as long as CarbonLib 1.1 or later is installed).

    Good point, Joe! Thanks for the clarification. I don't happen to have CarbonLib 1.1 on my machine and I think that's why I got it into my head that it was one or the other. So those of you planning to upgrade to Mac OS X when it ships next month, feel free to download the Carbon version.

    Finally, a question. Jamey Osborne writes:

    Here's a question/topic suggestion for your new column:

    How best to make the transition from spaghetti code to object-based programming?

    I'm an "old-time" amateur hacker that learned the old MS-DOS and I've studied Mac programming essentials, programming simple games in Pascal, but I've never managed to get comfortable in the "object-oriented" world that is programming today.

    For example, I've an idea for a project I'd like to undertake in RB (brand new to it). I can see how I envision an "old-time" flowchart to go, but I have no idea how to break it into the object mode. Kind of daunting to an old hacker....

    Good luck with the column and count me as an eager reader!

    Thanks, Jamey! Excellent question. Object-oriented programming (OOP) requires a different mindset from traditional programming and making the transition can be difficult. I still struggle with that myself, coming from a background similar to yours.

  • One of the things I like about RB, however, is that since it is object-objected, your own programs tend to fall in line. For instance, if you create a document window for your program, you can write a routine for the window that knows how to save itself. Then if the user opens several windows, they each have their own save routine. That's OOP!

    Obviously your question is too complex to be answered in a few paragraphs, but I will be exploring OOP issues in various columns in the future.

    Various comments from readers:

    Saw the first column on RBU. Great! I've been waiting for something like this to come along. I'll be there every week. --Scott Clausen

    Very cool. Exactly what I have been looking for. THANK YOU! I look forward to being a regular reader. -- J. Michael Wash

    Thank you, Thank you! I've been waiting for 2 years for someone to do something like this. Several started and never followed through. REALbasic is just a hobby with me and I can't spend as much time learning as I would like, but if someone is going to show me how. I can't wait. --Bill Tucker

    I'm very excited about your REALbasic University and Realbasic Developer magazine. As a REALbasic developer myself I congratulate you on your efforts to spread the gospel. -- Terry Findlay

    Thank you so very much for providing RealBasic instruction to a novice such as myself. I hope to find that RealBasic suits my right brain! --Carol Goodell

    That's it! Keep the letters coming and come back next week.

    .

  • REALbasic University: Column 003

    Working with Interface Elements Last week we created an application with a window and a few interface elements, such as a checkbox and text editing area. Without writing a single line of code, we had a working program. Let's continue where we left off and expand on that theme. Open up last week's project (or create it from scratch again).

    First, let's look at what happens when you select an interface object: the object is outlined in your system's highlight color and handles (tiny black squares) appear at each corner. These handles let you resize the object. If you drag an object from the inside, you can move the object. If you drag one of the object's handles, you'll expand or shrink the size of the object from that side. (When you are rearranging things, be careful you don't accidentally drag and handle resize an object!)

    (Note on Selecting: RB works like standard Mac applications in that you select an object by clicking on it, and if you hold down the Shift key while clicking, you can select several objects at once. You can also use the tip of the arrow to draw a selection rectangle around objects and it will select all objects within the rectangle. When you do that, realize that the object must be completely inside the rectangle -- sometimes, such as with a static text object with a small amount of text, the visible portion of the object is smaller than the full size of the object. Tip: If you press the Tab key while your window is frontmost, RB will select the next object in your window. Each time you press the Tab key RB will select the next object, in the order in which you added them.)

    Let's select the EditField control we placed on Window1 last week and make it bigger. Make it almost as wide as your window and the height of several lines of text. Notice that when you change the size of the object, the width and height properties on the Properties window reflect the change. If you want, you can simply type in numbers to specify the exact height and width you'd like for the object.

  • Notice that when you move an object within the window, intersecting grid lines appear and help your object snap to an invisible grid or to another object. This is great for helping you align interface elements within the window and to each other. Here's what that looks like:

    REALbasic also gives you some powerful automatic alignment options. With more than one object selected, go to the Format menu and the Align submenu. There you will see

  • several options such as "Align Left Edges," "Align Right Edges," and "Space Horizontally" (there are also vertical versions of these same commands). If you select one of these commands, the selected objects would be aligned on their left or right sides, or if you selected the "Space Horizontally" or "Space Vertically" commands it will adjust the objects to there is equal space between each object.

    When you place interface elements on a window, REALbasic keeps track of how your objects are positioned: you could, for example, place one element on top of another. Sometimes this is inconvenient: you would like to move an object below or above another. If you select one of the objects, you can use RB's rearrange commands (found on the Format menu) to move that object forward or backward, or all the way to the front or back of your window.

    (Note: sometimes you'll need to move elements forward or backward simply because RB makes it difficult to select one object behind another. If you're trying to select the background object RB will keep selecting the front object when you click. You can temporarily rearrange the objects to allow you to select the other object, then rearrange the objects back to their original order when you're finished.)

    EditField Properies

    Let's select the EditField you created (probably called EditField1). With it selected, the Properties window should show you something similar to this:

  • There are lots of settings here, but for now we are only interested one. Under "Appearance" you'll find an item labeled "Multiline" which is probably not checked. Check it. This will let your editfield accept more than one line of text -- essentially turning your little edit box into a mini-word processor.

    Try it! Run your program and play with the editfield. If you want, quit your program and turn the "multiline" option off and rerun the program to see the difference. (You'll need to quit your program to access the editfield's properties: you can't access an object's properties while your program is running.)

    Next Week

    We'll add some code to our project so it will actually do something!

  • Letters

    Our first letter comes from Benjamin Burton, who quotes last week's letter regarding object-oriented programming and adds:

    This is a letter you posted, and I'd just like to same I'm in the exact same boat. I've gone from BASIC and Assembly on my Apple IIc to Pascal on a 286. I have some old projects (and new ideas) I'd like to move into OS X, but I feel like REALBasic must be so simple I'm missing something. I've purchased REALbasic: The Definitive Guide by Matt Neuburg, and it just seems likes he knows too much, but not enough about communicating.

    Anyway, I wish your column would appear once a day instead of once a week. If it were shareware, I'd pay the fee, so keep 'em coming.

    -Ben

    Thanks for the note, Ben! Matt's book is great and essential for anyone really interested in getting the most out of REALbasic, but even he'll admit it isn't a tutorial. It's designed as a comprehensive resource, and if you're ever stumped about how something works -- or doesn't work -- in REALbasic, you turn to Matt's book.

    For tutorials, turn to REALbasic University! Keep following RBU and in a few weeks we'll have you producing your first real program.

    Next, we hear from J. A. Russell:

    I recently purchased RB 3.0 because of the advertising hype and a desire to extend my very limited computer knowledge. As a person who has no programming experience, the information provided by RealSoft is extensive, but of no help to someone, like me, with no programming experience. I hope your tutorial will always keep this in mind.

    I have seen other tutorial sites which started to help the complete new user, but soon passed them by to deal with problems/questions sent in by more experienced users. I have seen several of the, "I'm going to help you from step #1 to the end." Sites fail because they quickly forgot that the site was started to deal with beginners, not the esoteric problems that they recieve from more advanced users.

    I understand completely, John! Keeping the right balance between "advanced enough to be interesting and not so advanced it's intimidating" is a tough task, but that's my goal. I want to challenge you, and help you learn, but I also have a real passion for bringing programming to non-programmers. Your feedback on my success/failure on this is important to me, so if I'm ever glossing over a complex subject or skipping a step you don't understand, please let me know. I'd much rather receive complaints from advanced users telling me I'm dealing with "the basics" than lose the "newbies."

  • Our final question comes from John Rahn, who includes a picture of his problem:

    I know I'm missing something simple and basic...

    I've written an application and it works fine - except for the fact that when I bring up my "Settings" window, it is (sometimes) grayed out. The window is in front, and it is accessable and all the controls are useable, but it is grayed out (screen capture attached):

    What am I missing?

    Thanks

    JP Rahn

    Wow, John, I hate to admit on my first technical question that I'm stumped, but I'm stumped! Even though the dialog is frontmost and active, RB has it grayed out as though disabled. Very strange.

    I tried to recreate your situation myself, but it always worked correctly for me. To answer your question I'll need more information: what window type is your "Settings" dialog set to, and how are you calling it (dialog.show or dialog.showModal)? It might be helpful for me to see some of the related source code, if you wouldn't mind.

    Meanwhile, any of our bright readers have any ideas?

    .

  • REALbasic University: Column 004

    The Code Inside Let's expand our program a bit. We're going to add a little bit of programming code -- just a few lines -- to add a really cool feature to your program. The feature is called "Hot Help." While the exact nature of "Hot Help" varies, it basically consists of textual information displaying when you point at an object.

    First, let's add a static text object: drag the "A" icon from the toolbox to your project window. Position it near the bottom of the window. Since it isn't wide enough, either click and drag one of the righthand handles to make the object wider, or select the static text object and in the "Width" field on the Properties window, change it to 275.

    Now, select the static text object, go to the "Name" property and change its name from "StaticText1" to "infoDisplay" (I like to begin my objects with lowercase letters, but you don't have to do that if you don't want to). When you have the statictext item selected, the name field should look like this:

    (Note: When you change the property of an object, it happens immediately. For instance, there's no need to press Return to "save" the name change to your object.)

    To add our feature, we're going to have put in some lines of code. Where do you type code in REALbasic? The answer is cool (and similar to HyperCard): inside the object!

    Begin by selecting one of your objects... let's try EditField1. Select the object and press Option-Tab (hold down the Option key while pressing the Tab key). You should see something similar to the following:

  • This is the Code Editor for Window1. On the left side you'll see a list of object types: Controls, Events, Menu Handlers, Methods, and Properties. We'll be explaining these in more detail in future columns, but for now, we're going to focus on the Controls section. All of the interface elements you placed on Window1 are controls, so each of them should appear within the Controls section.

    (Each section has a disclosure triangle text to it, just like a List View of your files within the Finder. You can reveal or hide the items inside the section simply by clicking on the triangle. Objects within the sections may also have items inside them -- if so, they will have their own disclosure triangles.)

    In this particular case, we are looking at the events for EditField1: KeyDown, GotFocus, LostFocus, SelChange, TextChange, MouseMove, MouseEnter, MouseExit, Open, Close, DropObject.

    Events are basically things that happen to a control. One of the ingenious things about REALbasic is that code is not only encapsulated inside objects, but that the object itself (a window or a control) is filled with events each with their own code. This separates different types of code without you having to specifically differentiate between them yourself.

  • For example, in traditional Mac programming, your main program is a loop that constantly checks for events. Did the user click in the menubar? Did the user click in your window? Is the mouse over a particular control? Did the user type on the keyboard? Etc. With each choice, you'd send the computer off to a particular routine that handles that choice.

    Within REALbasic, events are sent to specific objects. An object can't have events that don't make any sense to it. For instance, a popup menu does not have a keydown event because a popup menu doesn't accept keystrokes.

    All this makes your programming much easier: simply put in code within the event that you need to handle. (This is why these events are often called "handlers," because they handle that event.)

    In the case of EditField1, when you pressed Option-Tab to open its Code Editor, REALbasic automatically put you inside the handler for the KeyDown event. The KeyDown event is triggered every time a user types anything inside EditField1. If you happened to have a second editfield called EditField2, EditField1 would not receive typing for it, and EditField2 would not receive typing for EditField1.

    We don't want to add any code to the KeyDown handler; we're interested in the MouseEnter handler. So underneath the EditField1 section on the left, click on the MouseEnter event. The pane on the right should change to put your cursor within the code for the MouseEnter subroutine.

    Now we're finally going to type some code!

  • With your cursor within the MouseEnter subroutine, type "inf" -- your display should change to look like the following:

    Notice the gray "oDisplay"? That's REALbasic's "autocomplete" feature at work. You typed the first few letters of an object and RB is about to finish typing the object's name for you. The extra text is gray, because it's not really there -- it's just a REALbasic suggestion. You can type something else if you want. Or, if the suggestion is correct and you want to have RB finish typing it for you, press the Tab key. Now the full name "infoDisplay" is displayed in solid (black).

    Accessing Object Properties

    We've already seen Properties at work. EditField1, for example, has Height and Width properties. Properties can be settings for an object, but really they are just storage containers. The "width" property of EditField1 is just a storage container for a number. Eventually you'll learn how to add properties (storage containers) for objects you create yourself.

    What's important right now is that you understand how REALbasic let's you access the properties of an object. REALbasic uses very simple syntax: object-name.property. Translated into English, that means you have the object's name, a period, and then the property name. For example, if you wrote EditField1.width in your code RB would return the value contained in the "width" property of the control called EditField1.

  • In this case, we want to change the value of the "text" property of the static text control called infoDisplay. By putting the property we want to change on the left side of an assignment command (an equals sign), we are telling the computer to "put what's on the right into the container on the left."

    Make your code look like this:

    infoDisplay.text = "This is where you type."

    There! You have just written, in computer talk, "Put the phrase 'This is where you type.' into the 'text' property of the infoDisplay object. Note that the text property only accepts a string: a string is a programming term for text, as in a string of characters. A string can contain numbers, but a number cannot contain letters. You tell REALbasic that something is a string by enclosing the phrase in double-quotes.

    If you had written:

    infoDisplay.text = This is where you type.

    or

    infoDisplay.text = 4586

    REALbasic would complain with a syntax error when you attempted to run the program. (A syntax error means the computer can't figure out what you are trying to say; it's similar to an error in grammar, except computers are so picky that the computer can't understand anything if you don't feed it stuff in exactly the format it expects.)

    We're going to reuse this code elsewhere, so let's select it and copy it to the clipboard (Command-A to select all and Command-C to copy).

    Now click on the disclosure triangle of CheckBox1 on the left side of the Code Editor. We want to be able to see the events inside CheckBox1. Find the MouseEnter event, and paste your code inside it. Since this code has the help phrase for the editfield, edit it so it reads correctly for the checkbox control as follows:

    infoDisplay.text = "This is a checkbox."

    Perfect! Now find the MouseEnter event of PushButton1 and do the same thing. Change it to read:

    infoDisplay.text = "This is a push button."

    Guess what? We're finished! First save the program (Command-S or Save from the File menu). Then run the program (Command-R or "Run" from the Debug menu) and see what your program does. Try pointing the arrow cursor at the push button, the editfield,

  • and at the checkbox. See how the text at the bottom of the screen changes? Cool, eh? You've just added "Hot Help" to your program! With no loss of blood, too.

    The final program, showing hot help in action:

    Now the program is a bit limited. You'll notice, for instance, that when you first launch the program the label at the bottom of the window says "Label:" which is rather ugly, and when you move your cursor outside of an object the help label still displays the old text. Ideally the help text should go away when you point away from an object. Can you figure out how to do that? I hope so, because that's your homework assignment.

    Next Week:

    We learn more about REALbasic syntax.

    Letters

    I found a couple letters I'd neglected in the initial onslaught, so let me deal with them first. Mike Ziegler writes:

    I am considering switching from Hypercard to RealBasic. Is it possible to convert existing hypercard stacks to realbasic?

    There's no way that I know about. REALbasic is not HyperCard, though it is easy to use. HyperCard is very different in terms of how it is structured, with everything on "cards" (instead of standard Mac windows). Theoretically someone could write a tool in

  • REALbasic that would "run" HyperCard stacks or convert them RB, but I don't know that anyone has done that.

    If you're interested in a HyperCard-like product, look at MetaCard or SuperCard.

    Next, we hear from Alvin Chan:

    Good morning, I've used RealBasic, but how powerful is it compared to VB6 which I use now? Is it capable of handling databases of different formats like Active X and does it have APIs function calls too?

    I do like RealBasic's interface better than VB6 except for the menu facility where VB is easier to use.

    I'd like to migrate from VB6 to C++ then Java. What vendor is the best for C++ or Java and the ones that big companies like Apple use?

    God bless, Alvin Chan

    Thanks for the note, Alvin. I haven't used Visual Basic, so I can't really compare the two, but I'd assume RB is as powerful, at least on the Mac platform, though I have heard that VB has some features not matched with RB. For instance, there is no Active X on the Mac, so that wouldn't apply. RB does have some database capabilities (either using it's own built-in format or external databases in SQL, ODBC, or Oracle) and there are plug-ins such as Paradigma Software's Valentina. You'll have to explore these yourself and see if they'll meet your needs.

    REALbasic does support Mac OS function calls and people have done some advanced things with RB by making use of those.

    As to your C++ and Java question, you're getting out of my league (I have little ambition to explore that territory, which is exactly why I use REALbasic ;-), but as far as I know the best (only?) tool is Codewarrior.

    Finally, we get back to John Rahn's question from last week, where his project included a puzzling active window that was "grayed out." I attempted to duplicate his situation and couldn't, so John sent me the source code for his project. I did some digging and finally figured out the error.

    Meanwhile Paul Harvey (I doubt it's the radio commentator ;-) wrote in with the same problem:

    I have also had the situation where a frontmost window in realbasic is greyed out! I've not identified the source, but I have windows that are 'hidden' that are scratch areas for processing editfield data. I don't know if one of those is perhaps taking the frontmost

  • position, even though we can't see it! However, even clicking on the greyed out window does not change the greyed out status. Sometimes clicking on another document window then back to the greyed out one solves it.

    Paul is right on track, because that's exactly the problem. John's project had numerous hidden windows, and some of those were of the "floating palette" variety. Sometimes those hidden windows would be frontmost and sometimes they wouldn't, explaining why his "Settings" window was sometimes grayed out even while it was active.

    The way I finally tested this was to write a little routine. I added a Popupmenu control to the main window of his project. Then, within the MouseEnter handler, I entered the following code:

    dim i as integer me.deleteAllRows for i = 0 to windowCount - 1 me.addRow window(i).title next

    What this did was fill the Popupmenu with the names of the active windows in order, from front to back. Remember, an active window is a window that is "alive" (i.e. loaded and running) and is not necessarily visible on the screen.

    Since I placed this code within the MouseEnter handler, every time I moved the pointer into the Popupmenu's area the window list was refreshed. As I played with his program I periodically went and checked the current window listing. I quickly noticed that whenever the "Settings" was grayed out it was not the frontmost window and whenever it was correct it was the frontmost window. That made me realize the other hidden windows were interfering with REALbasic's understanding of which was the frontmost window and causing it to draw incorrectly.

    The solution is simple: close, don't hide windows when you are finished with them. Closing gets rid of the window while hiding it just makes it invisible. For instance, John displays a "splash screen" when his program is launched, but because he never closed the window it was still around, and sometimes it was frontmost, even though it was invisible!

    To close John's splash screen, I simply added a self.close command within his window's MouseDown handler (replacing his hide command).

    Closing an unused window also saves memory, because an active window is still using memory. Since the window is part of your REALbasic project, you can always bring it back -- it will just get loaded from disk instead of RAM.

    Another important thing to understand about windows: any reference to a window activates it (brings it into memory). The window may or may not be visible, but just

  • referring to it makes it active. In John's case when his program was launched he would read in items from a preference file and set variables in a hidden window with those settings, effectively activating the window though it was invisible. A cleaner approach is to store the setting in a global variable which your window can read when it is opened. (For instance, to set the state of a checkbox, in your window's Open handler put checkBox1.value = globalCheckBoxValue where globalCheckBoxValue is a global variable containing the setting.)

    That's all for this week. Keep the questions coming! If I didn't get to your question this week, I'll deal with it sooner or later.

    .

  • REALbasic University: Column 005

    Helpful REALbasic REALbasic is a fairly simple language, and as it is a form of BASIC, one of the oldest, simplest computer languages, it isn't hard to learn the, uh, basic (sorry) syntax. RB uses traditional BASIC terms such as DIM, FOR, IF, ASC, MID, etc., though occasionally the syntax might be slightly different. If you're familiar with BASIC you'll learn REALbasic quickly, but even if you've never programmed a microwave oven to cook popcorn, you'll find learning RB isn't difficult.

    The actual language of REALbasic is limited to a few dozen commands and functions; but those commands are just the beginning of what you can do with REALbasic. Remember, REALbasic is an object-oriented programming environment. Objects are powerful because an object inherently knows how to do certain things -- it has abilities that distinguish it from another object.

    For example, a push button control knows how be pushed. (It's a pretty simple control.) But push buttons have other abilities (many shared with other objects) that are less obvious, such as the ability to change its size, label, position, and enabled state. These settings of a control are its properties. Much of what you do in programming is work with these settings to reflect the current state of the program. For instance, you might set a push button's state to disabled (not usable) when it's inappropriate for that button to be active.

    REALbasic includes dozens of pre-defined objects, each with unique and shared properties. Learning the capabilities of all of REALbasic's many objects is a challenge, but vital if you want to make your program do what you have in mind.

    Remember from last week's lesson that you access an object's properties by typing the object's name, a period, and the property name. Many properties are simple enough: width sets or gets an object's width, while height does the same with the object's height. But others can be confusing.

    For instance, a popup menu's text property returns the text of the current setting (the text of the chosen menu). But a bevel button control, which can have a menu, uses caption for the button's text and menuvalue to return the number of the selected menu.

    So while every REALbasic object is similar, they are not exactly the same. Another problem: some properties are read-only (you cannot set or change them), while others only want numbers, or perhaps a true or false (boolean) setting.

  • Fortunately, you don't have to memorize all those property names. REALbasic features a built-in help command which can show you the object and a list of its properties and their settings. With many commands, there is even sample code showing how the command can be used.

    Exercise: Go to the Window menu in REALbasic's IDE and choose "Reference" (or press Command-1) to bring up REALbasic's online language reference guide.

    Learning to use REALbasic's online help is essential to becoming a capable programmer. Even after years of using REALbasic, I find myself constantly turning to online help just to make sure I've got my syntax correct. It saves me lots of time and aggravation -- ten seconds of preventative medicine is easier than discovering some code won't compile, or spending hours trying to figure out why a routine isn't working only to eventually realize you accidentally reversed the parameters of the inStr command.

    REALbasic's help is simple to use. A list of topics are in a column on the left, and when you select one, its text appears in an area on the right. There are two navigation modes: the list at left can display every topic alphabetically, or it can display help items grouped by topic. You choose between the two by clicking "Alphabetical" or "Themes" at the top of the list.

  • Syntax Illustrated

    Being able to find the command or function you need help with is one step, but you still need to understand what the help text means. Programming syntax can be complicated; it's vital you understand what REALbasic is telling you.

    Let's take a look at that inStr command. It's a function (a function returns a result) that returns the position of one string inside another. That's a fancy way of saying it finds one sequence of characters in another. Here's REALbasic's Help on the subject:

    What does all that mean? It may look intimidating, but it's not bad once you get the hang of it. The first bit tells you the syntax of the command. In this case,

    result = InStr([start,] source, find)

    shows you how the command is supposed to be used. The items in between the parenthesis are parameters for the inStr command.

  • The bit after the syntax explains each of the parameters. Result is an integer (a whole number). In other words, the command is going to tell you at what position the search string was found. If you searched for "fox" within "The quick brown fox" the inStr command would return a 17.

    Notice how the word "start" above is enclosed in square brackets? That tells you that the parameter is optional. If there are no brackets around the parameter, you must include it or REALbasic will generate a syntax error. In this case, start is a number, and represents the starting point of the search. You might have noticed that inStr always finds the first occurrence of an item. What if you needed to find the second or third occurrence? The answer is you'd start the seach after the first find (you'd have to save the value of the first search and search again, using that saved value as the basis of the second search).

    The final two parameters for inStr are "source" and "find" -- both are strings (text). Source is what you are searching within and find is what you are searching for.

    Therefore, the following is a valid search:

    inStr("The quick brown fox", "fox")

    Of course if you just type the above into REALbasic, you'll get an error because you aren't doing anything with the result of your command. Since the command returns a number, you must do something with that number: store in a variable, or display it. Try putting this in a pushbutton and running your program and clicking the pushbutton:

    msgBox str(inStr("The quick brown fox", "fox"))

    (The above calls the msgBox routine which displays a message, and it uses the str function to convert the number returned by inStr to text, since msgBox only displays text.)

    You may notice that many of the REALbasic help screens have a "Notes" section after the syntax explanation. This is important stuff! For instance, what happens when inStr can't find the string you are searching for? You could test it to see, like this:

    msgBox str(inStr("The quick brown fox", "dog"))

    But if you read the notes you'll see REALbasic says, "If the find string is not found within the source string, 0 (zero) is returned."

    Ah! Good info to know! Now your program can check the result, and if it's zero, know that the string was not found.

    But keep reading. The notes continue, "InStr is case-insensitive." What does that mean? That means inStr("The quick brown fox", "fox") and inStr("The quick brown fox", "FOX") will both return 17 -- inStr doesn't care if the search string is upper or lower case, or if the case of the search and find strings don't match. Most of the time this

  • is good, as you don't have to explicitly check for both situations, but if you want case-sensitivity, inStr isn't the command for you.

    Below the Notes section is an Examples section. Here you'll find some sample code which can be helpful as you see the command "in action."

    Notice how the block of code has a gray outline around it? That means you can drag that chunk of code into your program! It's a great way to experiment with REALbasic commands without having to do a lot of typing. Once the source is in your program, you can edit it as you like.

    After the Examples area, there's a "See Also" section which lists similar commands to the one you're looking at. With inStr, for example, the "See Also's" include Mid, Left, and other string functions (functions that manipulate strings). Notice how those are in blue and underlined? They are hot-links -- click on one to jump you to that command. (You might also find them elsewhere on the page -- like the inStrB reference in the Notes section.)

    Object Syntax Illustrated

    The inStr function we just looked at is a simple command. A control object like a listbox is much more complex.

    Go to the listbox help within the online guide. (The simplest way is to type "list" while the guide is open: REALbasic will select the first item in the list starting with the characters you type.)

  • You should notice a few differences between this instruction page and the inStr one (besides the fact that this one is much longer). First, notice that because the listbox control is an object, it has a "Super Class" section. That's basically its mother -- as a control, it is based on "RectControl," a generic control class. What that means is that it has inherited all of the characteristics (properties) of a RectControl -- stuff like "width" and "height" properties. It's important to know that, because those properties aren't listed in this help window, but of course they are valid for using with a listbox.

    Next, you'll see a list of properties. These are settings you can change. Some, like "initialValue" are listed in bold, meaning they cannot be changed while the program is running. Some you can never set, but others you can set before running the program via the Properties Window when the object is selected.

    After the Properties listing, you find an Events listing. Events are things that happen to an object. For instance, it might be opened, closed, or clicked on. Remember our little "hot help" program? We used the "mouseEnter" event to display an appropriate help message

  • when the cursor was pointed at an object (a control). You won't see a mouseEnter event listed here, because mouseEnter is an event inherited from Mom (rectControl).

    Note: you don't access an object's events programmatically, by coding; listbox.gotFocus generates an error. (This is only true of the events REALbasic provides -- with your own objects you can call your own events.) Instead, an object's events show up within the object's code window. There you can put appropriate code for each event. The listing within the help window is not to show you the code you can type, but what parameters different events generate.

    Finally, if you scroll down past Events, you'll see Methods. Methods are like procedures and functions in other languages. Since REALbasic is completely object-oriented (everything is an object), your subroutines are always methods (the method of an object).

    Methods do things. Some methods need a parameter or two, some don't. You call a method the same way you access a property. listbox1.deleteAllRows is a valid command (assuming an object named "listbox1" exists). If a method requires parameters, you can put those after the method (either enclosed by parenthesis or not). Both of these are valid REALbasic statements:

    listbox1.addRow "This text will be added as a new row" listbox1.addRow("This text will be added as a new row")

    (If there were more than one parameter required, you'd separate them with commas.)

    The Notes and Examples sections of powerful controls like the listbox are essential reading. Some of the examples use skills or features you haven't used yet, so they can be confusing, but playing with the examples is a great way to learn. We'll be exploring the listbox and other controls as we continue with this series.

    Further Help

    REALbasic's online help isn't comprehensive or perfect: there are mistakes, typos, and even a few commands missing. There's also a lot it doesn't cover or fully explain. But don't fret: there are other resources available to you.

    REAL Software also provides REALbasic documentation in PDF format. There are three documents: Language Reference, Developer's Guide, and the Tutorial. (If you want to try the tutorial, you'll also want the tutorial files.)

    The Language Reference document is essentially identical to online help: it details every REALbasic command.

    The Developer's Guide offers more of an explanation of techniques and methodology for programming in REALbasic, which is great, but it would be much more useful with abundant sample code and more examples.

  • The Tutorial takes you through a step-by-step process of building your own SimpleText-like word processor. Unfortunately, in the interest of speeding you through the project, it leaves out a lot of explanation of what you are doing and doesn't explain alternative methods. It basically says, "Do this, put that there, type this in, and you're done." For experienced programmers, it's a great demo, but if you've never programmed before, it can leave you puzzled about why what you did worked (or perhaps didn't, if you messed up).

    (The approach I'm taking with REALbasic University includes more hand-holding and explanations of why we are doing what we're doing. It's slower, but you'll learn more. And for those advanced students who wish for a faster pace, just skip the explanations.)

    If REAL Software's documentation isn't enough (and it probably isn't), there's Matt Neuburg's excellent REALbasic: The Definitive Guide, published by O'Reilly. It's a volume packed with just about everything there is to know about REALbasic. I use it whenever I find I'm entering unfamiliar territory. (For example, I've never had a need to do anything with sockets; if I do, I'll read the section in Matt's book before trying anything.)

    Important Note: Matt's book is not a tutorial -- it's a reference volume. Like its title, it is "The Definitive Guide." But it won't teach you programming.

    If all that isn't enough help, don't forget REAL Software's REALbasic Network User Group mailing list. It's an invaluable resource for posting questions and receiving quick answers. Sometimes you'll even get technical answers from one of the programmers at REAL Software! There's also a search engine of the list archives -- it's a good idea to check there before you post and see if anyone has already answered your question.

    (If you're not familiar with an internet mailing list, it's basically an e-mail exchange where messages are sent to all members. Mailing lists work best if you set up a filter in your e-mail software to direct a list's messages into a particular folder. The REALbasic list tends to be very high volume, with over a hundred messages per day, so you don't want them cluttering up your regular e-mail. Just remember, you don't have to read every message! I usually only have time to browse the messages with topics I find of interest. You can also subscribe to the digest version, which clumps multiple messages together into a single large e-mail.)

    And that's not all! If you really want to get the goods on REALbasic, begin exploring the hundreds of websites devoted to it. There are sample programs, free code, classes and routines you can use in your own software, REALbasic plug-ins (which extend REALbasic's capabilities), and tutorials. Your best bet is to start and the REALbasic Webring and go from there (at press time 107 sites were listed, including my own). Many sites link to others which aren't on the webring.

    Next Week:

  • We start on our first "real" programming project! We're going to write a simple but useful utility. It should take us several lessons, but we'll learn about REALbasic while doing, instead of me just lecturing.

    Letters

    Our first letter comes from Ryan Goudelocke, who writes:

    Marc,

    I'm glad to see all the positive feedback you've gotten for RBU - here's some more! RB's docs are fine if you just want to check out particular controls etc., but overall program design is pretty much left up to the user. Unless you're willing to buy and read Matt Neuberg's book, it would be difficult even to get started. Your column is without doubt a big step in the right direction.

    Question: It's sometimes unclear when objects which are linked to particular windows go out of scope, and how they can best be accessed by functions living in other windows. RB's behavior, as far as I can tell, is different from both all-in-memory languages (like orig. BASIC) and from C++, wherein all classes and their (public) functions are globally available. Later on in your series this might be a helpful topic to explore - it seems like there are a zillion ways of storing/transferring information between classes and their windows (I guess this applies to modules as well), but which is best?

    Anyway, as I said, keep up the good work!

    Thanks for the encouragement, Ryan! I've very pleased with the progress and response of REALbasic University so far, and I hope it grows and becomes an essential part of many people's week.

    Regarding your question, I will certainly explore that issue in depth in future columns.

    For those who are just learning REALbasic, let me briefly explain Ryan's question. He's talking about problems with the scope of a variable. Let's say you've got a subroutine with a variable called Myvar. Myvar is local to that subroutine only -- other routine's that attempt to access Myvar will generate an error, because they don't know that variable exists. A window can have it's own variables, local to anything inside that window, including subroutines inside that window, but a separate window won't know about those. Other variables can be made global -- they are accessible everywhere in the program, by any window, by any routine.

    The problems Ryan is talking about is when you have a dialog box that asks the user a question, what is the best way to get their answer back to the routine that opened the dialog box? If you store the answer inside the dialog box (in a local variable), it goes away when the dialog box is closed. If you store it in the calling window (or routine), the dialog box doesn't know about it, and can't access it to set it.

  • The simplest method is to use a global variable. For instance, you could have a string variable called gTheResult and the dialog box could put the answer inside that. If the user canceled the dialog, you'd set gTheResult to nothing (gTheResult = "").

    However, using global variables can waste memory. For a simple dialog like the above, it's probably fine (especially if you reuse gTheResult for multiple dialogs), but what if your program is some accounting software and the dialog box is supposed to edit a customer record: do you pass a copy of the entire customer record to the dialog? What if the dialog needs to access multiple records, or the entire database? Passing a duplicate copy of the whole database is certainly not efficient, yet there could be complications if the dialog box is allowed to modify the original.

    I remember as a REALbasic newbie I didn't worry about it much but came up with my own hastily glued together solutions and later regretted it. As a matter of fact, my Z-Write uses five or six different methods for passing info between windows -- not good. While it doesn't necessarily affect the user, it makes updating more difficult, because sometimes I find I've effectively painted myself into a corner: whatever system I used to pass info has to change if I want to add a new option to a dialog box. (But I've learned from my mistakes: with each Z-Write update, I clean up some of this poor code.)

    We'll explore this in a future column: there's certainly many ways to do this, and none of them are completely wrong or always right.

    Our final letter for this week comes from Jules Steinhausen, who writes:

    Having struggled with Think Pascal, then Codewarrior, where the simplest prog error would crash or freeze my Mac making development a slow process, I welcome REALBasic. HyperCard etc are fine, really flexible and easy to program but oh so slow. Enough of the prattle.

    My Questions: 1. The tutorial makes you use an App class as the basis for its text editor. I have built a working word game that just has a window as its basis - as the window is visible throughout the game is this OK or should I re-structure my game.

    2. How can I get it to read MS Word files? I've tried adding the type MS8W (I think) to the File types in the appropriate box but the Generic Find file dialog box does not display them for selection.

    PS. At 55 its hard to learn new tricks, but as an old friend of mine (Ed Reppert) used to assure me, Understanding Object Orientated structure is a 'Road to Damascus' job it comes 'one day' in a blinding flash. I live in hope.

    Hey, Jules, great to see you tackling new challenges! You're never too old to learn new tricks. New tricks keep you young!

    To your questions:

  • 1) The tutorial uses the App class simply because that allows you to have multiple documents. When you only have REALbasic's default window as the window for your program, that window is your program. Closing it closes your program (it doesn't actually end anything, but there's really nothing else the user can do -- there isn't even any menu active except for Quit). With an App class that class is your program -- when it ends your program has quit. Since the App class is running even with the main window closed, it can respond to user commands (and enable appropriate menus). We'll talk about this in depth in a future column.

    2) Word files are a proprietary format owned my Microsoft. They don't release the specs, though some companies (like DataViz) have reverse engineered the format enough to create their own translation software. Reverse engineering a complex format like Word is no easy task: that's why most people use Rich Text Format (RTF) as an exchange format. RTF is a text-only format that describes complex documents and is used to move formatted text between word processors. I myself recently released RTF-to-Styled Text, a freeware program that converts RTF to text so that my Z-Write users can import Word documents (Word can export in RTF format). RTF-to-Styled Text is Open Source (I used Belle Nuit Montage's RTFParser library), so you can download the REALbasic source code on my site.

    Hope that helps everyone. That's it for this week -- keep the letters coming. It's great to see what you all are doing with REALbasic!

    .

  • REALbasic University: Column 006

    The Problem My day job is working at a printshop where I receive files from clients every day. Many of these files are created in programs I don't use, or perhaps the job comes from a PC or via the Internet. Either way, I've got files with generic icons that won't open when I double-click on them. Somehow I need to tell my Mac that "ad.jpg" is a JPEG file and it should be opened with Adobe Photoshop.

    The trick is that Mac's have secret Type and Creator codes attached to all files. These codes are simply a series of four characters. Most are simple, like text files are of Type "TEXT" (capitalization is important with Type and Creator codes). If you double-click on a file with "R*ch" as the Creator code, your Mac will try to open the document in Bare Bones Software's BBEdit text editor (if you have installed on your computer). If wanted the file to open in SimpleText, instead, you could change the Creator code to "ttxt" and you'd be set.

    These hidden codes are visible in many technical programs or utilities, such as ResEdit. But most of these are a pain to use, and overkill for my needs. There are also shareware programs out there that let you see and modify a file's Type and Creator codes, but the programmer in me is inherently cheap and I love to reinvent the wheel. So I'm going to write my own utility for changing Type and Creator codes.

    REALbasic to the Rescue

    This kind of problem is ideal for REALbasic. It's a simple problem, but challenging enough to be interesting. As we explore solutions we'll learn about several aspects of REALbasic, such as creating a user interface, classes and data structures, working with files, dialog boxes, and more.

    Program Design

    The first step in writing any program is to do a bit of planning. I know, I know. If you're like me, you prefer to just dive right in a start programming, but a little thinking ahead can save us a lot of headaches later. So let's stop and think about how we want this program to work. What are our needs? What should the program look like? What would we feel comfortable working with?

    Let's start by listing a few essential requirements of our program.

    1. Simple. Type and Creator codes can be confusing. We don't want to be confused. We want something simple and quick, almost transparent. We shouldn't have to

  • worry about saving a file or messing with dialog boxes. In fact, we may want the actual Type and Creator codes to be hidden -- the program could display the kind of file we're converting to and that's all we need to see.

    2. Powerful. I frequently find I need to change the same types of files over and over again. It would be ideal if the program could memorize various Type and Creator codes so I could just choose "Quark XPress" and make some files Quark documents. It also should support multiple files -- what if I have a whole folder of JPEG images I want to be owned by Photoshop?

    3. Elegant. The program should have a clean interface and be easy to use. It should be easy to add, remove, and change saved items.

    That's a pretty good start, but it's rather general: almost all programs should be simple, powerful, and elegant. What we need now are some specifics. Exactly how is our program going to accomplish its task? What is it going to look like? How will it remember Type and Creator code combinations?

    Let's try envisioning the program at work. Remember, we're brainstorming here: anything goes, and nothing's finalized yet. We haven't written any code, so we're free to change anything. It's important to come up with several scenarios, as with programming, there are many ways to do every task, and some are better than others. It might even be a good idea to get out a pen and paper and sketch these out so you can visualize them better.

    Concept #1 Okay, there's a menu at the top with a list of file types (Quark XPress, Photoshop JPEG, etc.). Only one of these can be checked at a time. Then a menu command to "Select File/Folder." When chosen, you are prompted to select a file or a folder. When you do that, those files are changed to the kind you indicated. There'd be other menu commands for adding, removing, and editing saved items.

    Advantages: simple and clean; not even a window.

  • Disadvantages: can only see file type chosen when menu is pulled down; can only convert an entire folder (not ten items in folder); uses the Select File dialog which is a pain to use, especially for multiple files.

    Concept #2 Instead of menubar menus, let's use a window with a popup menu with a list of file types. The user just selects one. There's a convert button which converts all files/folders that are dragged to it. To add an item to the File List, just drag a file of that kind to the popup menu. There'd be menu commands for editing/deleting file types.

    Advantages: simple; handles multiple files well, and doesn't use the Select File dialog.

    Disadvantages: since both the popup and convert buttons accept dragged files, it might be confusing which is which.

    Concept #3 There's a listbox control on a window. Files/folders dragged to the list are displayed. Next to each filename is a file type icon and file type name as a popup menu. The user can easily change the file type for each file by choosing a new one from the menu next to it. There'd a convert button under the list so when all the files were in place, one click would change them all. This way a person could change multiple files to multiple kinds at the same time!

  • Advantages: powerful; visually good (displays file type icon and lists files to be converted).

    Disadvantages: complex -- the ability to change multiple files to different file types at once might be too powerful; difficult to program (REALbasic doesn't have a built-in way to get a file's icon); RB's listbox won't let us include popup menus inside it.

    Concept #4

    A variation of Concepts 2 and 3. We'll have a popup menu of File Types at the top. There's a list of files to be converted and a "convert" button. If a user doesn't want a particular file converted, they can selected it and remove it by pressing the delete key. All files would convert to the same File Type. There'll be a menu item for editing the File List, but you could drag a file to the popup to quickly add it to the list.

  • Advantages: simple and clean; visual difference between large list box and small popup list of file types minimizes confusion; actual Type and Creator codes hidden until editing; ability to remove individual added files is powerful.

    Disadvantages: semi-complicated to program as multiple dialog boxes are needed.

    So, there we go. That gives us a few options to choose from. Concept 3 is obviously the most powerful, but it's rather complicated; overkill for the simple utility we want. Concepts 1 and 2 would be easy to program, but they wouldn't be as elegant as Concept 4. Concept 4 won't be much more work than the others, but offers the perfect compromise between usability and ease of creation. So it's decided: we'll develop Concept 4.

    All that's left is to think up a cute name for our program. We could go with the obvious, something like FileTyper, but let's be more creative. How about something memorable and a little silly... since changing a file's Type and Creator is a bit like a certain surgical operation, how about GenderChanger?

    Next Week:

    We design GenderChanger's user interface.

    Letters

    Our first letter this week is a compliment from Jean-Yves Bosc, who writes: