Date: Tue, 17 Mar 1992 0:24:21 PST From: Bill Lipa Subject: Comp.sys.mac.programmer FAQ Newsgroups: comp.sys.mac.programmer Subject: *** FAQ 02/26/92 *** Frequently Asked Questions (Read Me First!) Summary: Frequently Asked Questions list for comp.sys.mac.programmer Followup-To: Distribution: world Organization: University of Oregon Computer and Information Sciences Dept. Keywords: frequently asked questions faq ***************************************************************************** Frequently Asked Question (FAQ) Posting This version written For newsgroup: comp.sys.mac.programmer February 26, 1992 This file is automatically posted on the first of each month to comp.sys. mac.programmer. It is also available via anonymous ftp from ftp.cs.uoregon. edu (user name 'anonymous', your internet address as password) in the directory /pub/mac. This file is maintained by Michael A. Kelly. He can be reached at the following addresses: Internet: mkelly@cs.uoregon.edu SnailMail: Computer Science Dept. University of Oregon Eugene, Oregon 97403 The purpose of this posting is to answer some of the most common questions asked on this group, and to refer people left with unanswered questions to available sources of additional help. Submissions, comments, etcetera, should be sent to Michael Kelly, as above. All such material sent will be considered to have entered the public domain (and will be subject to editing) unless specific text to the contrary accompanies the message (which may render the submission unusable). ***************************************************************************** Contents: Changes Development Software Compilers Debuggers Other Tools Apple Developer Programs The Associates and Partners Programs Apple Developer University APDA Developer CDs Other useful sources / wells of information: Books and Periodicals Usenet Mac Programmer's Guide (UMPG) Kent Sandvik's Frequently Asked MPW C++ and MacApp Questions FTP sites ftp.apple.com [130.43.2.3] sumex-aim.stanford.edu [36.44.0.6] rascal.ics.utexas.edu [128.83.138.20] mac.archive.umich.edu [141.211.164.153] comp.binaries.mac [newsgroup] One-liners: Aphorisms for our times Specific Questions Answered: (1) How do you tell if a specific key is being pressed? (2) How do you get a full pathname? (3) How could anyone love the File Manager? (4) When do you put an ellipsis on the end of a menu item? (5) How do you set the SFGet/PutFile directory? (6) Why does malloc/calloc keep crashing or returning NULL in Think C? (7) How can I get millisecond timing from the keyboard (or mouse)? (8) How do you put a border around the default button in a dialog? (9) How do I go about writing serial port communications? (10) How do I get the menubar to disappear and re-appear? (11) How do I write an INIT? (12) How do you access the application's data fork? (13) What is the fastest way to paint one pixel on the screen? (14) How do you draw directly into a pixmap without using QuickDraw? (15) How do you draw directly onto the screen without using QuickDraw? (16) How do you register signatures and file types with Apple? (17) What RGB value does the system use for dimmed buttons, menus and window titles? (18) What's the difference between the resource ID of a 'MENU' resource and the menuID field of that resource? (19) When should I call MoveHHi? Eternal Debates: Why doesn't the Mac do preemptive multitasking? Credits / Acknowledgements ***************************************************************************** Changes Added numbers to the Specific Questions Answered. If you see a question posted to c.s.m.p. that is answered in this file, please refer the inquirer to Question #x in the FAQ. Added Specific Questions Answered #19. Replaced the review of Development Software:Debuggers:TMON. Added the review Development Software:Other Tools:Resourcerer. Plus one- or two-line updates/typo fixes to the following: Development Software:Compilers:Think FTP sites:rascal.ics.utexas.edu One-liners:Resources One-liners:Drawing One-liners:Menus Development Software:Debuggers:MacsBug Specific Questions Answered #2, #3, #4, #6, #8, #12, and #17. ***************************************************************************** Development Software This is by no means a complete analysis of the tools, development systems, etc. that are available. This is a short list of things which *most* Mac programmers use (or are at least aware of, and have considered using). Compilers Macintosh Programmer's Workshop (Apple) MPW is a package which contains separately-purchaseable compilers for Assembly, C, C++, and Object Pascal. All of these run in an environment called the MPW Shell. The Shell is a command-line oriented environment, designed for extreme configurability with scripts, user-writeable "tools", i/o redirection, and lots of other bells and whistles. On the pro side, it can do many things that THINK cannot do; it scales much better to large projects; it can be customized much more; and it's Apple's supported development environment. On the con side, it is comparatively expensive, slow, and difficult to learn. A debugger (SADE) is available for it, and is philosophically similar to MPW. An object library is available (MacApp) which allows applications to be built on an object-oriented framework, again similar to MPW in it's approach of being very powerful, but not necessarily easy to learn, easy to use, small, or fast. MPW is also available on the quarterly Essentials-Tools-Objects CD-ROM from Apple. This disc contains the latest version of the entire MPW development environment, as well as debugging utilities and a huge collection of sample source code. This brings the price of the MPW environment down a bit, but it's still much more expensive than THINK. Think (Symantec) Think is two separate products, Think C and Think Object Pascal. They are similar products. Both are integrated editor/compiler/ linker/debugger environments. Both come with a large library of predefined classes (the C classes are written in a sort of pseudo C++ language that is Symantec's own Object C, not C++). Think Pascal is MacApp-compatable, as well. Both support inline assembly, but there is no separate assembler. Their main selling point, however, is that they are very fast and very simple. They are ideal for small projects that you want to finish in a few days, for beginners, and for people who need a full-fledged development environment but cannot afford MPW. This is not to say that the Think environments are not useful for commercial development; many successful commercial programs were written with Think. The difference in power between MPW and Think is only noticeable with very large and/or multiple-developer projects. Debuggers (beyond SADE and the Think debuggers) MacsBug (Apple) MacsBug is an assembly-level debugger. It is a command-line driven, entirely text-based environment which uses little of the Mac toolbox, and is thus fairly stable in crashes (although it doesn't use protected memory, its main failing in the area of stability). It supports complex operations with breakpoints, A-line traps, macros, expressions, and more, and can be configured even more with user-writeable 'dcmd' external code resources. MacsBug is free via anonymous ftp from ftp.apple.com. It is also included with the book "Debugging Macintosh Software with MacsBug." TMON Professional (ICOM) TMON Professional is an object-level debugger which is MUCH more powerful than MacsBug. It has an elaborate interface which looks nothing like a Mac application, and takes a while to get used to. It is a very intelligent program, however, which can often display memory in its most useful format without help (e.g. it will disassemble code, and display a string as a string, automatically). It has strong support for types, allowing you to easily view complex structures, arrays, floating point numbers, and more. You can examine the stack, the heaps, and just about anything else you could be interested in. It also provides versatile scripting, and is amazingly configurable. There are more goodies in this package than I can possible describe here. Drawbacks are high price, and a very steep learning curve. The Debugger (Jasik Designs) The Debugger (also known as Jasik's Debugger, because it was written by Steve Jasik) is the only source level debugger with all the low-level features of Macsbug (speed, straight-forward display of important info) and many of the advantages of source level debuggers (source code, quick display of local variables). Some of its best features are complete support for Object Pascal, speed, and the ability to look at resource map and file information. You gotta love any debugger that will display all of the low-level globals with their values in a single keystroke! It also has a On the down side, the interface is an aquired taste, the documentation needs work and distribution disks lack a certain polish. But, phone support is very good (you often get Steve himself). SourceBug (Apple) This is similar to SADE, but I hear it is much nicer. It is not scriptable, however. Perhaps someone would like to give me a review of SourceBug to put here??? Other tools ResEdit (Apple) ResEdit is the accepted tool for editing and creating resources. It has very little competition, partially because it is a very good and comprehensive program, and partially because it is free (available via anonymous ftp from ftp.apple.com). It allows you to edit any resource in hexadecimal, and most of the standard types have special editors that provide a direct-manipulation paradigm for editing them. Users may write their own pickers and editors for custom resource types, although this is rarely done in practice. Resourcerer (Mathemaesthetics) Resourcerer is a commercially available replacement for ResEdit. Many developers use it exclusively, and swear by it quite vehemently. This is from one of them: RESORCERER is a no-holds-barred resource dynamo. -- embarrasses the ResEdit dialog editor -- supports many more template data types -- swap in different resource templates based on a key value -- creates recursive resources -- generates starter code for a dialog -- does complex searches against resource contents or titles -- renumbers resources in batches -- changes resource types -- excellent support from the author himself Virtual User (Apple) Virtual User allows you to script user interactions with a program so that they cal be relayed over and over, and it can execute scripts remotely, over AppleTalk. So, for instance, you could write a script that puts your program through its paces, and then automatically execute that script simultaneously on lots of differently configured Macintosh systems. It is available from APDA (#M0987LL/B). (This paragraph taken from develop Issue 8, page 60.) Online Companion (Addison-Wesley) Online Companion is a reference tool. Hit a magic key combination, and a pseudo-window opens at the bottom of the screen which allows you to type in a full or partial name and find it in Online's database. It contains Inside Mac and some supplements, Tech Notes, etc. It's fast and simple. Think Reference (Symantec) Think Reference is a reference tool. It is a hypertext version of Inside Mac I-V and the Tech Notes. Click on the function or data type name to go to the page on which it is defined. It includes some very useful notes and examples written by Symantec, and the function prototypes can be copied and pasted into your editor. Very fast and simple to use. But beware of typos and, in some cases, bad advice. ***************************************************************************** Apple Developer Programs The Associates and Partners Programs From the back cover of 'develop' Issue 7: The Associate's Program, Apple's mainstream program for commercial developers, is a convenient and cost-effective way to get essential technical and marketing information. This program offers self-help technical support, keeps you up to date with the latest products and technical documentation, and gives you access to the Apple developer community through AppleLink. Associates also receive discounts on equipment. The Associates program is designed for commercial developers and others involved in development projects, such as contract programmers, training providers, authors, and system integrators. The Partners Program is open to Apple-selected commercial developers. In addition to receiving the same development information and tools as Associates, Partners receive technical support via electronic mail. Membership in the Partners program is limited to developers who directly contribute to Apple's long-term product strategies and business objectives. Information about becoming an Apple Associate or an Apple Partner is available from Apple. Call Developer Programs at (408) 974-4897, AppleLink DEVHOTLINE (devhotline@applelink.apple.com), or write 20525 Mariani Avenue M/S 75-2C Cupertino, CA 95014, for information or an application for the Associates or Partners program. Developers outside the U.S. and Canada should instead contact the Apple office in their country for information about developer programs. Apple Developer University From the back cover of 'develop' Issue 7: Apple Developer University provides training for all levels of Macintosh programmers. The hands-on classes give you experience using the most up- to-date development tools. Classes are offered in locations across the United States, and on-site instruction can also be arranged. Multimedia self-paced courses are available from Developer University through APDA. These courses include Macintosh Programming Fundamentals, User-Centered Design, and Introduction to Object-Oriented Programming. The registrar at (408) 974-6215 can reserve your place or send a current catalog. You can also AppleLink DEVUNIV (devuniv@applelink.apple.com) or write 20525 Mariani Avenue M/S 75-6U Cupertino, CA 95014 APDA From the back cover of 'develop' Issue 7: The Apple Programmers and Developers Association (APDA) offers convenient worldwide access to development tools, resources, training products, and information for anyone interested in developing applications on Apple platforms. A quarterly APDA catalog features over 300 technical products from Apple and third-party developers. There are no membership fees. APDA offers convenient payment and shipping options, including site licensing. Apple Associates or Partners automatically receive the APDA catalog. To order products or to receive a complimentary catalog, (800) 282-2732 U.S. (800) 637-0029 Canada (408) 562-3910 International (408) 562-3971 Fax 171-576 Telex APDA AppleLink (apda@applelink.apple.com) 20525 Mariani Avenue M/S 33-G Cupertino, CA 95014 Developer CDs The developer CDs are available quarterly from APDA, or monthly to Apple Associates and Partners. The quarterly version is also included in the quarterly issue of d e v e l o p. They contain just about everything that Apple makes freely available, including SpInside Mac, the Tech Notes, and a plethora of code snippets. ***************************************************************************** Other useful sources / wells of information Books and Periodicals Technical Books Inside Macintosh Volume I Addison-Wesley. ISBN 0-201-17731-5. $24.95 Inside Macintosh Volume II Addison-Wesley. ISBN 0-201-17732-3. $24.95 Inside Macintosh Volume III Addison-Wesley. ISBN 0-201-17733-1. $19.95 Inside Macintosh Volume IV Addison-Wesley. ISBN 0-201-05409-4. $24.95 Inside Macintosh Volume V Addison-Wesley. ISBN 0-201-17719-6. $26.95 Inside Macintosh Volume VI Addison-Wesley. ISBN 0-201-57755-0. $39.95 Inside Mac is the definitive reference regarding the Macintosh toolbox. Volumes I and II are basically essential to any Mac programmer who uses the toolbox at all. Volume III is essentially a summary, cross reference, index-y sort of thing, and isn't very useful. Volume IV is stuff specific to the Mac Plus and later machines, which would make it almost as important as I and II (not many 512K Macs left out there), except that the routines it describes are not nearly as generally useful. It does have all of the stuff on the HFS File Manager, however, so if you're working with File Manager routines you should definitely consult IV before I-III. Otherwise, you can survive without it for a while. Volume V is the Mac II volume. It has everything on Color QuickDraw, as well as lots of other goodies. I'd say it's more useful than IV, but only if you're doing color. Volume VI is the System 7 volume. It contains all kinds of bizarre new things which are probably not of general use or interest; but it contains a lot of new non-System-7 stuff as well (such as 32-bit Quickdraw), and it has corrections to the other five volumes. Inside Macintosh X-Ref, Revised Edition Addison Wesley. ISBN 0-201-57769-0. $12.95. Inside Mac X-Ref is a cross-referenced index to the six volumes and some other Macintosh technical books. M68000 User's Manual Prentice Hall. ISBN 0-13-609249-7. $22.95. MC68020 User's Manual Prentice Hall. ISBN 0-13-567017-9. $22.95. MC68030 User's Manual Prentice Hall. ISBN 0-13-566423-3. $22.95. MC68881/MC68882 Floating-Point Coprocessor User's Manual Prentice Hall. ISBN 0-13-566936-7. $22.95. The Motorola references are required reading for anyone doing assembly programming on the Mac. The 68000 is by far the most important. The 68881 manual only has relevance to those who want to do floating point and don't want to use SANE (the Standard Apple Numeric Environment, slow but robust, precise and general). Technical Introduction to the Macintosh Family Addison-Wesley. ISBN 0-201-17765-X. $19.95. This book provides an overview of the general hardware design, system archiecture, and ROM design of the Macintosh. It is not required for programming, but does provide some useful background information for programmers new to the Mac. Programmer's Introduction to the Macintosh Family. Addison-Wesley. ISBN 0-201-19254-3. $22.95. This book provides an overview of basic Macintosh programming concepts. It is recommended for programmers new to the Mac. Guide to the Macintosh Family Hardware Addison-Wesley. ISBN 0-201-52405-8. $26.95. This is the definitive guide to the hardware design of the Macintosh family. Designing Cards and Drivers for the Macintosh Family Addison-Wesley. ISBN 0-201-52404-X. $26.95. This is the official guide for developers of expansion cards and peripheral devices for the Mac. This book is required reading for anyone who wants to talk directly to expansion cards (video cards, for example). Human Interface Guidelines: The Apple Desktop Interface Addison-Wesley. ISBN 0-201-17753-6. $14.95. This is the definitive guide to program interface design on the Macintosh. When you find yourself wondering where to put the OK button in a dialog, consult this book. Apple Numerics Manual Addison-Wesley. ISBN 0-201-17738-2. $29.95. This book describes the Standard Apple Numerics Environment (SANE), and provides information about the IEEE-standard arithmetic and about the SANE engines on the Apple IIgs and Macintosh computers. Inside the Macintosh Communications Toolbox Addison-Wesley. ISBN 0-201-57775-5. $24.95. This is the definitive reference volume for the Communications Toolbox. Teaching Books Macintosh Programming Primer Addison-Wesley. ISBN 0-201-15662-8. $24.95. Macintosh C Programming Primer Volume II Addison-Wesley. ISBN 0-201-57016-5. $24.95. These are excellent books for the beginning Mac programmer. Both books use Think C in their examples, but developers using other platforms will find a plethora of useful tidbits. I believe both books are available in Pascal as well. Macintosh Revealed, Volume One: Unlocking the Toolbox Hayden Books. ISBN 0-8104-6551-5. $26.95. Macintosh Revealed, Volume Two: Programming with the Toolbox Hayden Books. ISBN 0-8104-6561-2. $26.95. Macintosh Revealed, Volume Three: Mastering the Toolbox Hayden Books. ISBN 0-672-48402-1. $26.95. Macintosh Revealed, Volume Three: Expanding the Toolbox Hayden Books. ISBN 0-672-48413-7. $26.95. This encyclopedic collection covers the entire Mac Toolbox for the beginning Pascal or Assembly programmer. It sometimes re-iterates Inside Mac, but always offers a fresh perspective. Volume I covers basics including memory management and QuickDraw. Volume II covers the other essential Toolbox managers and exemplifies each by constructing part of a complete text editor. Volume III expands this application, covering printing, drivers, desk accessories, sound and definition functions. Volume IV contains details of programming with MultiFinder, Color QuickDraw and styled text. How to Write Macintosh Software Hayden Books. ISBN 0-672-48429-3. $28.95. This book gives comprehensive coverage of memory management and debugging techniques. It also gives an excellent overview of assembly language programming on the Mac. A must-have. I hear that it's out of print, though. On Macintosh Programming: Advanced Techniques Addison-Wesley. ISBN 0-201-51737-X. $24.95. This book contains a lot of information on all aspects of programming the Mac, including hardware and software architecture, the toolbox, and the use of assembly, C, and Pascal for programming the toolbox. It includes quite a lot of source code. Using the Macintosh Toolbox With C Sybex. ISBN 0-89588-572-7. $29.95. This is a fairly good book for beginning Mac programmers. Experienced programmers will find nothing new here. Programmer's Guide to MPW, Volume I Addison-Wesley. ISBN 0-201-57011-4. $26.95. This is a basic introduction to using MPW. I don't recommend it for anyone who already uses MPW. Programming with MacApp Addison-Wesley. ISBN 0-201-09784-2. $24.95. C++ Programming with MacApp Addison-Wesley. ISBN 0-201-57020-3. $24.95. These give a basic introduction to programming with MacApp; the first with Object Pascal, and the second with C++. Elements of C++ Macintosh Programming Addison-Wesley. ISBN 0-201-55025-3. $22.95. Just what the title says. I haven't had a chance to look at it yet. Programming for System 7. Addison-Wesley. ISBN 0-201-56770-9. $26.95 This is a guide to creating applications for System 7. It describes the new features and functions of the operating system in detail. The sample code is in C and includes a complete System 7 application in Chapter 1 which is expanded in succeeding chapters. ResEdit Complete Addison-Wesley. ISBN 0-201-55075-X. $29.95. Most of this book is not written for programmers, but includes quite a bit of useful information nonetheless. It contains detailed discussions of using, customizing and programming ResEdit, including the creation of custom templates, pickers and editors. It comes with ResEdit 2.1 on disk, with sample source code in MPW C and Pascal. Debugging Macintosh Software with MacsBug Addison-Wesley. ISBN 0-201-57049-1. $34.95. This looks like a really good and useful book, but I haven't had a chance to look at it yet. MacsBug is included on disk, along with several examples and dcmds. Programming the M68000 Benjamin/Cummings. ISBN 0-8053-5550-2. 680x0 Programming by Example Howard W. Sams & Co. ISBN 0-672-22544-1. $17.95. M68000 Assembly Language: Techniques for Building Programs Addison-Wesley. ISBN 0-201-11659-6. The Complete Book of Macintosh Assembly Language Programming [sic] Scott, Foresman & Co. Vol I ISBN 0-673-18379-3 Vol II ISBN 0-673-18583-4 These are all assembly books that have been recommended by people on the net. The first two are general; the others are specific to the Macintosh. Periodicals d e v e l o p Quarterly. $10 per issue. $30 per year. develop Apple Computer, Inc. P.O. Box 531 Mt. Morris, IL 61054 AppleLink DEV.SUBS develop is Apple's technical journal for the Macintosh and Apple II (the focus is on the Mac). The articles are well-written and useful, and it includes the Developer CD. MacTutor Monthly. $5 per issue. $40 per year Third Class; $55 First Class. 1250 N. Lakeview Suite O Anaheim, CA 92807 (714) 777-1255 The only Macintosh programming journal that I'm aware of. A good source of sample code. Usenet Mac Programmer's Guide The Usenet Mac Programmer's Guide (UMPG) is a collection of useful tips culled from comp.sys.mac.programmer. Compiled by Matthew X. Mora (mxmora@unix.sri.com), it is organized by topic and includes a table of contents and index. It is available via anonymous ftp from sumex-aim. stanford.edu (36.44.0.6) in the directory /info-mac/tech/. It is also available in a pre-printed version, or on disk. To get a copy of the printed version send $17.00 to: USENET Macintosh Programmer's Guide Printed Version 39075 Carmel Ct. Fremont, CA 94538 To get a copy of the disk version send $5.00 to: USENET Macintosh Programmer's Guide Disk Version 39075 Carmel Ct. Fremont, CA 94538 Kent Sandvik's Frequently Asked MPW C++ and MacApp Questions This file is available upon request from ksand@apple.com or via anonymous ftp to skinner.cs.uoregon.edu in the directory /pub/mac. ***************************************************************************** FTP sites ftp.apple.com [130.43.2.3] Contents This archive contains just about everything available for free from Apple. Look here first for sample source code, the latest tech notes, and tools such as ResEdit and MacsBug. Very little of what can be found here is available from other archives. Access Anonymous ftp. You should read the file /dts/README.FIRST before downloading from this archive. Everything for the Mac is in /dts/mac. The moderators ask that you download during the off-peak hours if at all possible, since this is just a IIci running A/UX. Submissions You cannot post to this archive. sumex-aim.stanford.edu Contents This archive contains a large collection of public-domain and shareware for the Mac. It is well-maintained and updated regularly. New submissions to the archive are listed every other day or so in the newsgroup comp.sys.mac.digest. Access Anonymous ftp. Read the files in /info-mac/help for more detailed information about the files in the archive. Everything is in /info-mac. Submissions Sumex accepts all submissions that "are of general benefit to the Macintosh community." Basically, if you have something that you think is useful, and that other people may like to have, you should feel free to send it to sumex. All submissions should be compressed and BinHexed, and should include a short but informative blurb at the beginning of the file. Mail your submissions to info-mac@sumex-aim.stanford.edu. Expect a delay of anywhere from a week to a month before your file is made available. For more detailed information, consult the file /info-mac/help/posting- guidelines.txt. rascal.ics.utexas.edu [128.83.138.20] Contents This archive contains most of what can be found at sumex. Its emphasis is on utilities and programming-related items, but it contains quite a bit of other stuff as well. It is the home of the comp.sys.mac.announce archives. Many items tend to appear here before they show up at sumex or comp.binaries.mac. Access Anonymous ftp. Submissions Send submissions to macgifts@rascal.ics.utexas.edu (see Note below). See Submissions for sumex for format description. mac.archive.umich.edu [141.211.164.153] Contents I haven't explored this archive yet, but I hear it has quite a bit of general Macintosh freeware and shareware. Perhaps someone more familiar with this archive could send me a review.... Access Anonymous ftp. Submissions More information to come.... comp.binaries.mac Contents This is a moderated newsgroup for distribution of Macintosh freeware and shareware. Just about everything that gets sent to sumex and the other major archives gets sent here as well. Access Subscribe to the newsgroup.... Submissions All files should be compressed and binhexed for mailing. Posting to the newsgroup should automatically get your file mailed to the moderator. If this does not happen on your system, you can mail your posting to the moderator yourself at macintosh@felix.uucp. Expect a delay of as much as a month before your posting shows up on the newsgroup. Note: To submit a file to sumex, rascal, umich, and comp.binaries.mac, it is probably easiest to send it just to macgifts@rascal.ics.utexas. edu. Your file will then automatically get submitted to all four archives. ---------------------------------------------------------------------- One-liners The Main Loop and Events Call MaxApplZone and MoreMasters when the application starts up. If you call SetApplLimit, do it before calling MaxApplZone. Use HD in MacsBug while running to estimate how many times to call MoreMasters. Don't use SetEventMask to disable mouseUp events. Better not to use it at all. Call WaitNextEvent if you're running under System 6 or later. DTS sample code passes 0x7fffffff to WaitNextEvent when nothing is happening. DTS sample code passes GetCaretTime() to WaitNextEvent when flashing a cursor. Call both GetNextEvent and SystemTask only if WaitNextEvent is unavailable. Call IsDialogEvents and DialogSelect even if GetNextEvent returns false. SetPort to a known good grafPort once every time through the event loop. Set the cursor on suspend and resume events. Call GetDblTime to get the maximum time for a double click. Measure double click time from mouse up to mouse down. Menus Use SetItem to include meta characters literally in menus. Prepend an ASCII 0 to a menu item to use a leading '-'. Never make MENU resources purgeable. Resources GetResource never produces resNotFound. Check for a NIL handle instead. To create a resource file, call HCreate, then HCreateResFile. To open a resource file read-only for shared access, use HOpenResFile. Don't leave ResLoad set to false. GetResource on a dctb may return a non-resource copy of the dctb. Windows, Alerts, and Dialogs Move and size windows to the bounding box of GetGrayRgn. Hide scroll bars when deactivating a window. Call DrawGrowIcon when activating or deactivating a window with a grow region. DrawGrowIcon does not check to see if the window has a grow region. Call PenNormal before calling DrawGrowIcon. itemHit will not be set when a dialog filter is called. Use a disabled UserItem to draw the roundrect outline around the OK button. ModalDialog assumes the dialog is already visible and in the front. Use screenBits.bounds to center dialogs, alerts, etc. below the menu bar. If you save window locations in files, they may not be valid for all monitors. DragWindow expects startPt in boundsRect; if not it may not call SelectWindow. SelectWindow does not automatically call SetPort. You must do that yourself. DialogSelect responds to activate events but ignores suspend/resume events. Drawing Always set the VisRgn and ClipRgn of offscreen ports. Set the ClipRgn first when making a picture. Don't make rowBytes in bitMaps greater than 8191. To dim text, draw a rectangle with penPat=gray and penMode=patbic over it. To draw rotated text, draw to an offscreen bitmap, rotate it, and CopyBits it. Don't use picSize to determine the size of a picture. Check the handle size. Never draw outside a window except in XOR mode for temporary effects like drag. To avoid animation flicker, synchronize drawing to the vertical retrace. Lock handles to pictures before calling DrawPicture. CopyBits on more than 3Kb data will work, but it might have to allocate memory. The small Mac screen is 512 pixels wide by 342 pixels high including menu bar. Files Don't write in the application file. This will fail with read-only devices. Use PBGetVInfo to convert a VRefNum to a volume name. Delete uses the Poor Man's Search Path, so don't delete blindly. File Manager routines with dirID=0 use the Poor Man's Search Path. Truncate and reallocate files before overwriting to reduce fragmentation. Check/change the creator and type of Save As... files before overwriting. If you rewrite files by deleting and creating, copy all Finder information. Directory ID's are longs, not shorts. Shorts work ALMOST all the time. Always set the version number that appears in some file manager calls to 0. To convert a pathRefNum to a name or file number, use PBGetFCBInfo. Prevent the creation of files with names that begin with a period. Interrupts and VBL Tasks Don't call any Memory Manager routines during an interrupt. Unlocked handles may not be valid during an interrupt. To synchronize to the vertical retrace on Macs with slots use SlotVInstall. Handles and Pointers Lock handles before passing their dereferenced pointers to any routine. Lock handles before setting referenced data to expressions containing functions Put an odd long at location zero on a 68000 to help find NIL handle references. Use HGetState/HLock/HSetState to lock a handle then put it back as it was. General Always use unsigned characters within text and Pascal-format strings. Save application preferences in a folder named Preferences in the System Folder Use SysEnvirons to find the System (Blessed) Folder. Use GetAppParms to get the name of the application. The high bit of SysParam . volClik enables the alarm clock. Check the application name at $910 before exiting with ES within MacsBug. To exit to shell in the mini-debugger, enter SM 0 A9 F4 and then G 0. In Pascal, don't nest procedures to be passed by procedure pointer. In Pascal, "with theHandle^^" is unsafe if memory compaction can occur. Controversy Corner (Don't shoot me; I'm just the messenger.) Avoid writing tail patches for traps. There is no official way to tell if MultiFinder is running or not. ***************************************************************************** Specific Questions Answered (1) How do you tell if a specific key is being pressed? Use GetKeys. GetKeys fills a 16-byte KeyMap structure with the state of every key. Each bit represents a single key on the keyboard; 1 means the key is down, 0 means it is up. Note that there can be a maximum of seven keys being pressed at a time - any of the modifier keys plus at most two other keys. Here's an example in C: Boolean IsKeyDown( unsigned short theKey ) // a keyboard-specific scan code for a key { unsigned char keyMap[16]; GetKeys( (void *) keyMap ); return ((keyMap[theKey>>3] >> (theKey & 7)) & 1); } ----------------------------------------------------------------------------- (2) How do you get a full pathname? Take a look at Tech Note #238, available from APDA (and other places). It tells you everything you need to know to get a full pathname, and why you should, in general, use a volume name, dirID, filename (and perhaps volume creation date) triple instead. Also check out the code snippets available from ftp.apple.com et al. There are a couple of snippets that give code to get a full pathname, as well as many other cool file manager tricks. ----------------------------------------------------------------------------- (3) How could anyone love the File Manager? Its always those pesky wdrn's that are the problem. Here is a summary of some of the things to know: vrn = volume reference number (small negative number; e.g. -2) wdrn = working directory reference number (large negative number; e.g. -32123) dirID = directory ID (small (but long integer!) positive number; e.g. 4123) - vrn's and wdrn's can be used interchangably for the most part. - A vrn represents either a volume, or the root directory of a volume. - A wdrn represents a directory on a volume. - A dirID represents nothing without a vrn or a wdrn. - A dirID overrides the directory otherwise specified by the vrn or wdrn unless it's zero, in which case it's ignored. If it is 2 it specifies the root directory of the volume. - You should always use vrn,dirID pairs. To convert a wdrn into a vrn,dirID pair use GetWDInfo, which returns the vRefNum, the dirID and the procID of the wdRefNum. The procID is almost always 'ERIK'. - You can also use GetVol/SetVol to convert volume names to/from vrns. - To store a vrn,dirID pair (between invocations of a program) convert the vrn to a volume name & creation date (for verification) and store them and the dirID (and a filename perhaps). ----------------------------------------------------------------------------- (4) When do you put an ellipsis on the end of a menu item? Put an ellipsis (...) at the end of any menu item which requires more information in order to complete or simply displays information. Usually this involves a dialog of some kind, be it modal or non modal. ----------------------------------------------------------------------------- (5) How do you set the SFGet/PutFile directory? To set the directory that is displayed by SFGet/PutFile, stuff the volume reference number into SFSaveDisk, and the dirID into CurDirStore. CurDirStore = $398; Current dirID from Standard File (long) SFSaveDisk = $214; Negative of current vRefNum ----------------------------------------------------------------------------- (6) Why does malloc/calloc keep crashing or returning NULL in Think C? #include Explanation: In THINK C, parameters and return values are 2-byte ints by default, which causes the value passed to malloc to be $10000 times as large as you think it is, and causes the upper bytes of the return value to be zeroed. Including stdlib includes a prototype which overrides the defaults. Another common cause of problems with malloc is overwriting the end of a string, such as only mallocing the size of the string and then writing the string plus a null into the malloc'd space. Think's malloc algorithm stores block size information in space adjacent to the storage it allocates, so overwriting the storage tends to cause havoc. The problem may not show immediately since it will probably be the next malloc that encounters problems. ----------------------------------------------------------------------------- (7) I'm writing a psychology experiment. How can I get millisecond timing from the keyboard (or mouse)? The simple answer is that you can't. Although the new time manager can call routines every couple of microseconds, input goes through the event manager, which only posts events about every 16 milliseconds. Thus, even if you poll the keyboard every 30 microseconds, you will not get better than 16 ms. resolution. If you really need millisecond accuracy, you need to use external hardware. The good news is that you probably don't need better than 16 ms. resolution anyway. Measuring with 16 ms. accuracy only increases the standard deviation of your RT means by about 4.8 msec. Read: Ulrich, R and Giray, M. (1989). Time resolution of clocks: Effects on reaction time measurement -- Good news for bad clocks. British Journal of Mathematical and Statistical Psychology, 42, 1-12. By the way, there is a mailing list dedicated to running psychology experiments on the Mac. It frequently gets tied up in arguments about millisecond timing. The address to write to is: macpsych-request@stolaf.edu. ----------------------------------------------------------------------------- (8) How do you put a border around the default button in a dialog? The most common way to do this is to create a dummy user item in the dialog, and use SetDItem to install a procedure that outlines the default button. Here is an example in C: /* This function draws a border around dialog item #1 */ pascal void OutlineDefault( DialogPtr theDialog; short theItem; { Rect itemRect; Handle itemHandle; short itemType; short diameter; GetDItem( theDialog, 1, &itemType, &itemHandle, &itemRect ); diameter = (itemRect.bottom - itemRect.top) / 2; if ( diameter < 16 ) diameter = 16; PenSize( 3, 3 ); InsetRect( &itemRect, -4, -4 ); FrameRoundRect( &itemRect, diameter, diameter ); } /* Assume myDialog has been initialized, and item #4 is the dummy user item for outlining the default button. The following lines install the outlining procedure OutlineDefault into the user item, so that OutlineDefault will be called by the Dialog Manager each time the dialog needs to be redrawn. */ GetDItem( myDialog, 4, &itemType, &itemHandle, &itemRect ); SetDItem( myDialog, 4, itemType, OutlineDefault, &itemRect ); ----------------------------------------------------------------------------- (9) How do I go about writing serial port communications? These days, it is best to use the new Comunications Toolbox (CTB). By utiizing the CTB, you will be able to write your code to a single specification, and the code will work with all current CTB "tools" and all future CTB tools. The CTB tools allow programmers to extend the CTB's functionality. There is a tool for each facet of the communications puzzle: Connection Tools, Terminal Tools, and File Transfer Tools. For example, once I have written a piece of code that uses the Serial tool to connect me to a terminal server, combined with the VT102 Tool to emulate a vt102 terminal, and the XMODEM Macbinary Tool to transfer files, the same code will work with Apple Modem Tool, TCP/IP, AppleTalk ADSP, ISDN, X.25, and all future Connection Tools. Further, the terminal can emulate a VT320, ASCII, or other terminals. Files may be transfered with XMODEM, TEXT, and soon ZMODEM and Kermit protocols. The disadvantage of the CTB is that you must limit yourself to the specification of the Connection, Terminal, and File Transfer interfaces. These limitations are *rarely* a problem, but clearly something like a FAX interface program or real time data analyzer, would have to seriously consider the interfaces before committing. For most standard communications applications, such as terminal emulators, Bulletin Board Systems, etc., the CTB is the correct choice. You can only get the CTB development kit from APDA. It is affordable, somewhere just under $100. This includes working sample code. ----------------------------------------------------------------------------- (10) How do I get the menubar to disappear and re-appear? A set of routines to do this in Pascal can be found in the Usenet Macintosh Programmer's Guide. You can also ftp some sample code in C from skinner.cs.uoregon.edu in /pub/mac/menu-bar.c. ----------------------------------------------------------------------------- (11) How do I write an INIT? There is a simple INIT (SetWindow INIT) with source code and explanations in the Usenet Macintosh Programmer's Guide. ----------------------------------------------------------------------------- (12) How do you access the application's data fork? Call CurResFile when the application starts up. Call PBGetFCBInfo to convert that refNum into a vRefNum, dirID and name. Call HOpen with the vRefNum, dirID, and name to open up your data fork. ----------------------------------------------------------------------------- (13) What is the fastest way to paint one pixel on the screen? Using QuickDraw, the fastest way to draw one pixel is MoveTo( x, y ); Line( 0, 0 ); making sure that the pen size is 1 by 1. This is about twice as fast as setting the pen size to 0 by 1 or 1 by 0 and calling Line( 1, 0 ) or Line( 0, 1 ), respectively. I'm not sure why.... See below for how to draw a pixel without using QuickDraw. ----------------------------------------------------------------------------- (14) How do you draw directly into a pixmap without using QuickDraw? As an example, here is a routine that paints a single pixel in a pixmap. To use this procedure, you just have to know what 'value' to pass in. This depends on the current bit-depth of 'thePixMap.' The rightmost n bits of 'value' are used for the pixel value for depth = n. For depths of eight or less, the value of each pixel is an index into a color table. For depth = 16, each 16-bit pixel is interpreted as an RGB value, as follows: Bit: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 Value: R R R R R G G G G G B B B B B U where R = Red, G = Green, B = Blue, and U = Unused. For depth = 32, each 32-bit pixel is interpreted as an RGB value as follows: Bit: 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 Value: A A A A A A A A R R R R R R R R Bit: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 Value: G G G G G G G G B B B B B B B B where R = Red, G = Green, B = Blue, and A = Alpha. void SetPixel( short x, short y, long value, PixMapHandle thePixMap ) { unsigned long rowBytes; unsigned char mask; unsigned char shiftBits; unsigned char *thePixel; unsigned char pixelDepth; char mode = true32b; Boolean swapMode; swapMode = PixMap32Bit( thePixMap ); LockPixels( thePixMap ); rowBytes = (unsigned long) ((*thePixMap)->rowBytes & 0x3fff); thePixel = (unsigned char *) (*thePixMap)->baseAddr; pixelDepth = (*thePixMap)->pixelSize; switch ( pixelDepth ) { case 1: case 2: case 4: case 8: thePixel += (rowBytes * y) + (((unsigned long) pixelDepth * x) / 8L); shiftBits = ((8 - pixelDepth) - ((x * pixelDepth) % 8)); mask = (unsigned char) ((1 << pixelDepth) - 1) << shiftBits; if ( swapMode ) { SwapMMUMode( &mode ); } *thePixel &= ~mask; *thePixel |= (unsigned char) value << shiftBits; break; case 16: thePixel += (rowBytes * y) + (2L * x); if ( swapMode ) { SwapMMUMode( &mode ); } *((unsigned short *)thePixel) = (unsigned short) value; break; case 24: /* untested */ thePixel += (rowBytes * y) + (3L * x); if ( swapMode ) { SwapMMUMode( &mode ); } *thePixel = (unsigned char) (value >> 16); *((unsigned short *)(thePixel+1)) = (unsigned short) value; break; case 32: thePixel += (rowBytes * y) + (4L * x); if ( swapMode ) { SwapMMUMode( &mode ); } *((unsigned long *)thePixel) = value; break; default: break; } if ( swapMode ) { SwapMMUMode( &mode ); } UnlockPixels( thePixMap ); } ----------------------------------------------------------------------------- (15) How do you draw directly onto the screen without using QuickDraw? Get the pixmap for the monitor that you want to draw on, and send it to the above procedure. For example, to draw a red dot at position 10,10 on the main screen (if the main screen is in 32-bit mode): GDHandle theDevice; theDevice = GetMainDevice(); SetPixel( x, y, 0x00FF0000, (*theDevice)->gdPMap ); If you are drawing directly to the screen, you should always wrap your drawing with calls to ShieldCursor and ShowCursor. Some monitors such as the Radius Pivot series keep a virtual screen, and they don't update the real screen unless they have to. When you write directly to the screen, you're actually writing to the virtual screen, and your drawing won't show up on the real screen until the system has some other reason to update the monitor. Calling ShieldCursor each time you draw will force these systems to update the real screen when you expect them to. ----------------------------------------------------------------------------- (16) How do you register signatures and file types with Apple? Registering a signature and file type is free, and you don't have to be an Apple Partner or Associate. You can ftp the registration form from ftp.apple.com; it's available as /dts/mac/tools/creator-file-type-form.txt. ----------------------------------------------------------------------------- (17) What RGB value does the system use for dimmed buttons, menus and window titles? The gray color does not have a fixed RGB value. It is a weighted average of the foreground and background colors. To obtain the appropriate 'gray' color for a given foreground and background color, the Palette Manager routine GetGray can be used: pascal Boolean GetGray( GDHandle device, const RGBColor *backGround, RGBColor *foreGround ) = {0x303C,0x1219,0xAAA2}; If at least one gray or intermediate color is available, GetGray stores the color in foreGround and returns true. If no gray is available, or, if you supplied two colors, no third distinguishable color is available, the foreGround parameter is unchanged and the function returns false. GetGray is not available in older versions of the system. Use Gestalt to determine whether it is available. ----------------------------------------------------------------------------- (18) What's the difference between the resource ID of a 'MENU' resource and the menuID field of that resource? The resource ID of a 'MENU' resource is just the resource ID - it has no hidden meaning. What is normally expected by beginning programmers is that the number that MenuSelect and MenuKey return is the resource ID of the menu. In fact, the number returned is the value of the menuID field of the menu, and has no relation to the resource ID of the menu. You can set the menuID to any number you want, but by convention it is expected to be the same as the resource ID of the menu. (You can change this value in ResEdit by opening the menu you wish to change, and selecting 'Edit Menu & MDEF ID...' from the MENU menu.) ----------------------------------------------------------------------------- (19) When should I call MoveHHi? MoveHHi is an expensive operation; calling it when you don't need to can significantly slow down your program. Additionally, over-calling of MoveHHi can fragment the top of your heap. Call MoveHHi before locking a handle that is followed by some memory allocation. To effieciently move a handle high in the heap and then lock it, you might want to call HLockHi, a call new with MPW 3.2 and THINK C 5.0 (probably THINK Pascal 4.0 as well). ***************************************************************************** Eternal Debates These questions have no final answers. They pop up every few months and waste a tremendous amount of valuable network resources on discussions that will never be resolved. Most people would be happy if they were never discussed again in this newsgroup. Q: Why doesn't the Mac do preemptive multitasking? A: Pro-preemptives claim the current scheme is too vulnerable to ill-behaved applications and too much trouble for application writers. Anti- preemptives claim that preemptive multitasking would reduce interactive response, and that the current cooperative system works well. ***************************************************************************** Credits / Acknowledgements Many thanks to Ben Haller, who started this whole thing, and did quite a lot of work on this posting before handing it off to me. Thanks to these people for proofreading this list during its development: Ben Haller Wally Wedel John B. Matthews Patrick Beard Steve Zellers Thanks to Chris Webster for the one-liners. Thanks to Peter Lewis for the answers to the following specific questions: How do you get a full pathname? How could anyone love the File Manager? When do you put an ellipsis on the end of a menu item? How do you set the SFGet/PutFile directory? Thanks to Greg Ferrar for the review on TMON Pro. Thanks to John Rinaldo for the review on Jasik's Debugger. And thanks to everyone who has offered suggestions or constructive criticism.... Keep those comments coming!