home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / answers / macintosh / programming-faq < prev    next >
Text File  |  1993-12-20  |  59KB  |  1,491 lines

  1. Newsgroups: comp.sys.mac.programmer,comp.answers,news.answers
  2. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!news.kei.com!eff!news.umbc.edu!europa.eng.gtefsd.com!uunet!pipex!sunic!kth.se!hemul.nada.kth.se!d88-jwa
  3. From: d88-jwa@hemul.nada.kth.se (Jon WΣtte)
  4. Subject: The Mac Programming Public Domain FAQ Answer sheet.
  5. Message-ID: <1993Dec21.120855.19647@kth.se>
  6. Followup-To: comp.sys.mac.programmer
  7. Sender: usenet@kth.se
  8. Nntp-Posting-Host: hemul.nada.kth.se
  9. Organization: Royal Institute of Technology, NADA
  10. Date: Tue, 21 Dec 1993 12:08:55 GMT
  11. Approved: news-answers-request@MIT.Edu 
  12. Lines: 1476
  13. Xref: senator-bedfellow.mit.edu comp.sys.mac.programmer:77849 comp.answers:3110 news.answers:16056
  14.  
  15. Archive-name: macintosh/programming-faq 
  16.  
  17. The Public Domain Mac Programming FAQ Answer sheet.
  18. Last update: 931023
  19.  
  20. This sheet was started by and is presently maintained by Jon 
  21. W{tte, whom you may reach as h+@nada.kth.se. If there is 
  22. anything you find errant, missing or in need of an update, 
  23. please send me your submission and I will include it (I can't 
  24. promise correct attributions, but I will try) All FAQ Answer 
  25. submissions sent to me will be considered to be in the public 
  26. domain unless stated otherwise (in which case they will not be 
  27. included in this FAQ sheet) 
  28.  
  29. This sheet is currently archived on nada.kth.se where you can 
  30. reach it using afs as /afs/nada.kth.se/public/ftp/pub/hacks/mac-f
  31. aq/CSMP_PD_FAQ or using anonymous FTP (GIVE YOUR E-MAIL ADDRESS 
  32. AS PASSWORD!) as pub/hacks/mac-faq/CSMP_PD_FAQ 
  33.  
  34. I will try to update this sheet every two weeks or so. Changes 
  35. since first revision: 
  36.  
  37. Fixed spelling and formatting. Added question numbering. 
  38. Files and Networks: [Mattias Ullrich] 
  39. Lisp and SmallTalk: [Rainer Joswig] 
  40. Free development languages: [Bob Loewenstein] 
  41. Various: [Pete Gontier] 
  42. Lots of suggestions: [Peter Lewis] 
  43. Wake Up And Smell The Glue: [Matthias Neeracher] 
  44. Development environments: [Howard Berkey]
  45. SmallTalk: [Alun ap Rhisiart]
  46. CustomGetFile: [Jim Walker ]
  47.  
  48. This sheet is divided into several parts; each of which covers a 
  49. general area which often gets asked about in the Internet 
  50. newsgroup comp.sys.mac.programmer. Please download a copy of 
  51. this answer sheet and search it before you post to the 'net, to 
  52. help reduce bandwidth. 
  53.  
  54. There is NO or VERY LIMITED error checking in these code 
  55. examples, FOR BREVITY ONLY. You should make sure you ALWAYS 
  56. check ALL return codes, and handle any that you are not prepared 
  57. to deal with appropriately. 
  58.  
  59. The coding style used in the example C code is my own, and 
  60. you'll have to live with it.
  61.  
  62. The groups are (you may search for *<number>* to jump directly 
  63. to a group with its questions and answers) 
  64.  
  65. 0) Development and debugging tools and documentation for the Mac 
  66.  
  67. 1) Files and the File Manager 
  68.  
  69. 2) Serial ports 
  70.  
  71. 3) TCP/IP and sockets 
  72.  
  73. 4) AppleEvents and the Apple Object Model 
  74.  
  75. 5) AppleScript
  76.  
  77. 6) Drawing using QuickDraw 
  78.  
  79. 7) Drawing NOT using QuickDraw (aka directly to screen) 
  80.  
  81. 8) Cache issues and other processor differences 
  82.  
  83. 9) What about pre-emptive multitasking? 
  84.  
  85. 10) Handles; they are driving me crazy; Memory issues 
  86.  
  87. 11) _Gestalt and compatibility 
  88.  
  89. 12) Standalone code and dynamic linking 
  90.  
  91. 13) Reading the keyboard for games and screen savers 
  92.  
  93. 14) QuickTime 
  94.  
  95. 15) Ice Cream and Frozen Yoghurt 
  96.  
  97. *0* Development and debugging tools for the Macintosh 
  98.  
  99. 0.1) Q: What do I need to start writing Macintosh software? 
  100.  
  101. A: A Mac, a lot of time, and a few hundred $. Although you can 
  102. develop software on a Classic-type machine, it is not to be 
  103. attempted by the weak of heart or stressed of time. If you're 
  104. doing paid work and/or work for a company, a Quadra-class 
  105. machine or Centris 650 or better is almost a must; remember that 
  106. your time costs your employer much more than just your salary. 8 
  107. MB is a minimum to run at all comfortably, and Virtual Memory is 
  108. not suited for development work. Similarly; if you don't have at 
  109. least 20 MB free on your hard disk (40 MB for MPW) you need to 
  110. buy more space. 
  111.  
  112. You need a development system such as Think C, Think Pascal , 
  113. MPW C or Prograph, you need at least some of the New Inside Mac 
  114. books (Toolbox Essentials, Files, Memory come to mind) and a 
  115. good entry-level third-party book may help. 
  116.  
  117. Once you are up to speed on the general layout of the Mac and 
  118. its toolboxes, you should call APDA and order the monthly 
  119. developer mailing, which will give you a CD chock full of 
  120. documentation, utilities and system software once a month. You 
  121. will also, obviously, need a CD player; one of which Apple's own 
  122. CD300 is a very good buy at the time of writing this. If you 
  123. don't have the dough for the monthly mailing ($250/year) you can 
  124. order a _develop_ subscription; this quarterly magazine 
  125. ($30-$50/year) comes with a CD containing all Inside Mac 
  126. documentation.
  127.  
  128. Another tool which many find a must-have is the Think Reference 
  129. version 2.0, containing reference material on the most used 
  130. parts of the Mac toolbox with lightning-fast look-up and mostly 
  131. correct usage hints and code snippets. 
  132.  
  133. 0.2) Q: What is the most used Macintosh development language? 
  134.  
  135. A: Out of products on the market, I have no idea; both MPW and 
  136. Think products appear to be used. Among hobbyists, the Think 
  137. products from Symantec are most popular because of the low 
  138. price, and steep educational discounts, and, of course, the 
  139. easily approachable interface! 
  140.  
  141. The Think C linker only strips dead code on a FILE level basis 
  142. (and this is when you turn on "Smart Linking") The MPW linker 
  143. (of no specified IQ, as someone so eloquently put it :-) strips 
  144. dead code by the function. That may be part of the reason the 
  145. Think C linker is ten times faster than the MPW linker. 
  146.  
  147. In the beginning, the Mac was programmed using Mc68000 assembly 
  148. or Pascal; this was reflected in the Old Inside Mac volumes 
  149. which only gave Pascal-style and assembly-style interfaces to 
  150. the Mac toolbox. These days, Apple tells us to use C or even 
  151. better C++ for developing new applications, as that will speed 
  152. up the transition to PowerPC and also coming cross-platform 
  153. efforts. 
  154.  
  155. There are also at least two Fortran compilers, at least three 
  156. SmallTalk implementations (ObjectWorks, SmallTalk/V and 
  157. SmallTalkAgents), a world-class LISP/CLOS implementation 
  158. (Macintosh Common Lisp 2.0) and a Modula/2 implementation. 
  159. Apparently, using Envy/packager, you can strip out unused code 
  160. pretty effectively from Digitalk and PP apps, which are then 
  161. smaller (and of course more memory efficient) than C++ apps. 
  162.  
  163. Metrowerks have a Pascal and a Modula II compiler. Rumour has it 
  164. they're building C and C++ for both 68k and coming PPC Macs.
  165.  
  166. CSI has MacForth, of which I only know the name and someone who 
  167. says it's pretty good.
  168.  
  169. There is another good Common Lisp implementation: Procyon Common 
  170. Lisp. I don't know if it is actively supported, but Procyon CL 
  171. is also available for DOS, OS/2 and Windows (as Allegro CL/PC) 
  172. and actively developed. 
  173.  
  174. 0.3) Q: Where do I find a public domain C compiler for the Mac. 
  175. Is there a GCC for the mac? What about the FSF boycott of Apple 
  176. products? 
  177.  
  178. A: There is no really good solution for a "for-free" C 
  179. development system for the Mac. GCC has been ported, but 
  180. requires the MPW shell and MPW assembler to run; these have to 
  181. be bought from APDA. There is a standalone port of GCC 1.37 
  182. underway, but it is presently on hold because of licensing 
  183. issues. There was a freely available C compiler called Harvest 
  184. C, which was somewhat unstable but usable for smaller programs; 
  185. it was abandoned by the original author Eric W Sink because of a 
  186. lack of time.
  187.  
  188. The FSF boycott of Apple products means they will not talk to 
  189. you if you ask them for help in doing a Mac port, and they will 
  190. not incorporate your changes into their main code base. However, 
  191. they still allow others to port GNU stuff to the Mac, and it has 
  192. been done with most of the application-like GNU programs (bison, 
  193. flex, perl (not really part of GNU), ...) 
  194.  
  195. 0.4) Q: Are there any other free Mac development platforms? 
  196.  
  197. A: Yerk and Mops. These are object oriented languages based on 
  198. the old product Neon which itself was based on Forth. They are 
  199. available with Manuals at oddjob.uchicago.edu (anonymous FTP). 
  200.  
  201. Plus, there's MacGambit, MacScheme, xlisp, and MacMETH which is 
  202. the actual ETH (read: Nick Wirth's group) Modula 2, all for free 
  203. via FTP.
  204.  
  205. And OpenProlog. And SIOD (Scheme in One Defun) And [mail in more 
  206. if you dare]
  207.  
  208. 0.5) Q: What's the difference between the MPW and Think 
  209. environments? 
  210.  
  211. A: The main difference is that Think is an integrated 
  212. environment, while MPW provides you with a command-line shell 
  213. for your Mac and tools to use in it. MPW also has a slightly 
  214. higher systems demand and a much slower linker. 
  215.  
  216. The good thing about MPW is that you can write scripts and make 
  217. files to do anything you want in the way you want it. Think 
  218. still doesn't have a viable solution to do a build that requires 
  219. more than one link operation, or has more than one destination 
  220. file. 
  221.  
  222. For the MPW environment, there are three source level debuggers; 
  223. SADE, SourceBug and Voodoo Monkey. The latter is an experimental 
  224. debugger with support for threads debugging; the middle is 
  225. bundled with MPW while SADE has to be bought separately (but is 
  226. fully scriptable in its own scripting language) 
  227.  
  228. The Think environments have their own integrated debuggers; the 
  229. Think Pascal one has a lot of useful features while the Think 
  230. C/C++ one is a little more basic (but is gaining in 
  231. functionality with each release) Stepping through source code 
  232. and looking at variables is generally faster and easier in Think 
  233. than the MPW debuggers. 
  234.  
  235. Any commercial Mac developer should have both Think and MPW of 
  236. whatever language they prefer (Pascal, C or C++) 
  237.  
  238. 0.6) Q: What is a good low-level debugger for the Mac? 
  239.  
  240. A: MacsBug is freely available for ftp from ftp.apple.com; log 
  241. in as user anonymous and give your FULL e-mail address as 
  242. password. MacsBug is your basic monitor-type debugger that takes 
  243. a few hundred Ks of memory, and lets you break, step, 
  244. disassemble, look at the stack etc of most anything running on 
  245. your Mac. Since it's free (it's also on the developer CDs) and 
  246. provides most of the functionality you need, this is a popular 
  247. choice. 
  248.  
  249. TMON is another debugger which sports a more mac-like interface; 
  250. it provides windows and uses the mouse. It can take as little or 
  251. much memory as you want by excluding or including certain areas 
  252. of functionality. A nice touch is the 6502 disassembler that you 
  253. can use to de-bug the code the IOP processors run on the Mac 
  254. IIfx and Quadra 900/950. 
  255.  
  256. Jasik Designs have a debugger called The Debugger which can do 
  257. both low- and high-level debugging, with or without source and 
  258. for all types of code, application, code resources, everything. 
  259. This is the debugger of choice for many large developers because 
  260. of its high power and many features not found anywhere else. 
  261. However; newcomers beware! This is the Lamborghini of debuggers; 
  262. if you know how to drive it, it is the fastest way from A to B; 
  263. if you don't, you'll just end up in the ditch.
  264.  
  265. 0.7) Q: Are there any visual developments environments for the 
  266. Mac (comparable to Visual C++)?
  267.  
  268. A: There is no Visual C++ as such. However, there is a C++ 
  269. parser/editor called ObjectMaster which provides good browsing 
  270. and editing capabilities if you already have a C++ compiler. 
  271. Think C++ also comes with a browser built-in, and you can draw 
  272. dialogs/windows using plain old ResEdit, even for your custom 
  273. view types. 
  274.  
  275. AppMaker is a GUI builder/code generator.  Granted, it's not as 
  276. nice as VC++, but it's quite a product in any case.
  277.  
  278. Also, Neuron Data has their UI tool called Open Interface, which 
  279. is better than VC++ and creates code portable across 35 
  280. platforms. Unfortunately it's $2500 per developer per platform. 
  281. (There's also two other cross-platform products called XVT and 
  282. Galaxy, the former has gotten flak on UseNet while the latter 
  283. reportedly has decent networking support)
  284.  
  285. There is a fully visual, dynamic, object oriented data-flow-drive
  286.   n programming language for the Mac called Prograph Corporate 
  287. Programming Something-or-other (CPX). It is expensive ($1500) 
  288. but offers a built-in database, easy interfaces to existing data 
  289. bases, very high productivity in implement-test-debug cycling 
  290. and also offers cross-platform capabilities (it comes with a 
  291. class library which, when your code is written using it, works 
  292. under Windows after re-compilation) 
  293.  
  294. There is a crossing between SmallTalk and C++ that is called 
  295. Component Workshop; although it seems large and slowly evolving, 
  296. it does offer some promising features not found in C++ itself. 
  297.  
  298. There is also something called SmallTalkAgents that makes it 
  299. easy to create Mac applications using SmallTalk. If you'd rather 
  300. do Common Lisp, Macintosh Common Lisp offers a Common Lisp 
  301. Object System with support for most Mac interface items; you can 
  302. edit code while it is running and build stand-alone 
  303. applications. 
  304.  
  305. However, all of these tools generate rather larger binaries with 
  306. larger system demands than a program written in C. On the other 
  307. hand; C++ programs require more memory and disk space than 
  308. programs written in assembly. It's a trade-off, and I believe 
  309. this type of tools is the wave of the near future. 
  310.  
  311. 0.8) Q: What class libraries are there for the Mac? 
  312.  
  313. A: Apart from the libraries mentioned above, there are three 
  314. contenders: MacApp, TCL, and OOPC. On the horizon may be 
  315. Bedrock. 
  316.  
  317. MacApp is a heavy-duty class library that has tons of features 
  318. and a steep learning curve; it runs under MPW with Pascal or 
  319. C++, and also under Think Pascal 4.0 A major application written 
  320. in MacApp is PhotoShop. 
  321.  
  322. TCL stands for Think Class Library and comes with Think Pascal, 
  323. C or C++. It is a smaller library that still fills most peoples 
  324. needs; since Think C implements a subset of C++ (the most 
  325. important OO concepts such as virtual functions and inheritance) 
  326. and the TCL is carefully written not to take advantage of any 
  327. C++ features not in Think C, you can use it with Think C. A 
  328. major application written in TCL is Lotus 1-2-3. 
  329.  
  330. OOPC is a newcomer in the field, and uses plain ANSI C. However, 
  331. it mangles the pre-processor to provide you with a system with 
  332. full inheritance, virtual functions, and dynamic re-binding of 
  333. functions for classes or individual objects. Start-up is slow, 
  334. since all "linking" of virtual functions and classes is made at 
  335. run-time, but performance otherwise is good. A Windows version 
  336. is promised for later this year. 
  337.  
  338. 0.9) Q: How should I debug and test my software? 
  339.  
  340. A: Get ahold of, and install, the extensions DoubleTrouble, 
  341. DisposeResource and EvenBetterBusError. They will catch 80% of 
  342. any memory related bugs you may have, including many bugs that 
  343. follow NULL handles or pointers. 
  344.  
  345. A low-level debugger is required, and while you install it, 
  346. install the "leaks" dcmd which will help you catch memory leaks 
  347. in your application. All of these tools are available from 
  348. ftp.apple.com. 
  349.  
  350. *1* Files and the File Manager 
  351.  
  352. 1.1) Q: How do I tell fopen() to open a file the user has 
  353. selected using StandardGetFile? 
  354.  
  355. A: The "standard" ANSI C file functions are less than well 
  356. suited for the Macintosh way of doing things. However, if you 
  357. are doing a port for your own enjoyment and benefit (or maybe 
  358. for in-house work) you can use the following function: (see 
  359. below about converting a wdRefNum into a vRefNum/parID pair) 
  360.  
  361. *code*
  362. FILE *
  363. fopen_mac ( short vRefNum , long parID , char * fileName , char * mode ) {
  364. short oldVol ;
  365. short aVol ;
  366. long aDir , aProc ;
  367. FILE * ret = NULL ;
  368.     if ( GetVol ( NULL , & oldVol ) ) {
  369.         return NULL ;
  370.     }
  371. if ( GetWDInfo ( oldVol , & aVol , & aDir , & aProc ) ) { return NULL  ;
  372.     }
  373.     if ( HSetVol ( NULL , vRefNum , parID ) ) {
  374.         return NULL ;
  375.     }
  376.     ret = fopen ( fileName , mode ) ;
  377.     if ( HSetVol ( aVol , aDir ) ) {
  378.         /* an error we can't currently handle */
  379.     }
  380.     if ( SetVol ( oldVol ) ) {
  381.         /* an error we can't currently handle */
  382.     }
  383.     return ret ;
  384. }
  385. *end*
  386.  
  387. All of the above is necessary for one reason or another - if you 
  388. are interested, by all means look HSetVol up in Think Reference 
  389. 2.0 or New Inside Mac: Files. 
  390.  
  391. In older versions of MPW; this wouldn't work since the MPW 
  392. libraries used to do a GetVol and explicitly use that value by 
  393. itself. 
  394.  
  395. 1.2) Q: When can I use the HOpen, HCreate etc file calls? Are 
  396. they only System 7 calls? 
  397.  
  398. A: All the HXxx calls that take a vRefNum and parID as well as 
  399. the file name are implemented in glue that works on any system 
  400. that has HFS (meaning 3.2 and up with the HD20 INIT, and all 
  401. systems from System 6 and up) 
  402.  
  403. The glue is available in MPW 3.2 and up, and Think C 5.0 and up. 
  404. This goes for all HXxx calls except HOpenDF; therefore, if you 
  405. are interested in System 6 compatibility, use HOpen instead and 
  406. make sure you don't allow file names beginning with a period. 
  407.  
  408. 1.3) Q: Why do you say wdRefNum sometimes and vRefNum sometimes? 
  409. Why do you say parID sometimes and dirID sometimes? 
  410.  
  411. A: When the Mac first made an appearance in 1984, it identified 
  412. files by using a vRefNum (volume reference number meaning a 
  413. floppy disk or later hard disk) and a name. Once HFS saw the 
  414. light of day, folders within folders became a reality, and you 
  415. needed a dirID as well to point out what folder you really meant 
  416. on the volume. However, older programs that wasn't being 
  417. rewritten still knew nothing about directory IDs, so Apple had 
  418. SFGetFile make up "fake" vRefNums that didn't just specify a 
  419.  
  420. volume, but also a parent folder. These are called wdRefNums 
  421. (for working directory) and were a necessary evil invented in 
  422. 1985. You should not create (or, indeed, use) wdRefNums 
  423. yourself. 
  424.  
  425. There is a system-wide table that maps wdRefNums onto 
  426. vRefNum/parID pairs. There is a limit to the size of this table. 
  427. A dirID and a parID is almost the same thing; you say "parID" 
  428. when you mean the folder something is in, while you say a 
  429. "dirID" when you mean the folder itself. If you for instance 
  430. have a folder called "Foo" with a folder called "Bar" in it, the 
  431. parID for "Bar" would be the dirID for "Foo." 
  432.  
  433. 1.4) Q: How do I convert a wdRefNum as returned by SFGetFile 
  434. into a vRefNum/parID pair to use with the HXxx calls. 
  435.  
  436. A: Use GetWDInfo, which is declared as: 
  437.  
  438. Pascal OSErr GetWDInfo ( short wdRefNum , short * vRefNum , long 
  439. * parID , OSType * procID ) ; 
  440.  
  441. The procID parameter must be non-NULL and point to an OSType 
  442. variable, but the value of that variable can and should be 
  443. ignored. 
  444.  
  445. It is recommended that, as soon as you get your hands on a 
  446. wdRefNum, for instance from SFGetFile, you directly convert it 
  447. into a vRefNum/parID pair and always use the latter to reference 
  448. the folder. 
  449.  
  450. 1.5) Q: How do I select a folder using SFGetFile? 
  451.  
  452. A: This requires a custom dialog with a filter proc. It is too 
  453. complicated to show here, but not totally impossible to 
  454. comprehend. There is sample code on ftp.apple.com, in the 
  455. directory dts/snippets, on how to do this. 
  456.  
  457. 1.6) Q: How do I get the full path of a file referenced by a 
  458. vRefNum, parID and name? 
  459.  
  460. A: You don't. 
  461.  
  462. OK, I cheated you. There is exactly ONE valid reason to get the 
  463. full path of a file (or folder, for that matter) and that is to 
  464. display its location to the user in, say, a settings dialog. To 
  465. actually save the location of the file you should do this: 
  466. (assuming the file is in an FSSpec called theFile - you can use 
  467. FSSpecs in your program even if you don't run under System 7; 
  468. just make your own MyFSMakeFSSpec that fills in the FSSpec 
  469. manually if it's not implemented) 
  470.  
  471. *code*
  472. if ( ! aliasManagerAvailable ) { /* System 6 ? */
  473. GetVolumeName ( theFile -> vRefNum , vName ) ; GetVolumeModDate ( vRefNum , & date ) ;
  474. Save ( vName , date , parID , fileName ) ;
  475. } else {
  476. NewAlias ( NULL , theFile , & theAlias ) ;
  477.     Save ( theAlias ) ;
  478.     DisposeHandle ( ( Handle ) theAlias ) ;
  479. }
  480. *end*
  481.  
  482. If you are really concerned about these issues (of course you 
  483. are!) you should save BOTH of these methods when available, and 
  484. load back whatever is there that you can handle; since users may 
  485. be using your application in a mixed System 6/System 7 
  486. environment. 
  487.  
  488. To get back to the file is left as an exercise for the reader. 
  489.  
  490. To open a file using fopen() or the Pascal equivalent, see above 
  491. about using and not using HSetVol. 
  492.  
  493. 1.7) Q: What about actually getting the full path for a file? I 
  494. promise I will only use it to show the location of a file to the 
  495. user! 
  496.  
  497. A: Enter PBGetCatInfo, the Vegimatic of the Mac file system. Any 
  498. Mac hacker of knowledge has taken this system call to his heart. 
  499. What you do is this: 
  500.  
  501. *code*
  502. OSErr
  503. GetFolderParent ( FSSpec * fss , FSSpec * parent ) {
  504. CInfoPBRec rec ;
  505. short err ;
  506.     * parent = * fss ;
  507.     rec . hFileInfo    . ioNamePtr = parent -> name ;
  508.     rec . hFileInfo    . ioVRefNum = parent -> vRefNum ;
  509.     rec . hFileInfo    . ioDirID = parent -> parID ;
  510.     if ( parent -> name [ 0 ] ) {
  511.         rec . hFileInfo . ioFDirIndex = 0 ;
  512.     } else {
  513.         rec . hFileInfo . ioFDirIndex = -1 ;
  514.     }
  515.     rec . hFileInfo    . ioFVersNum = 0 ;
  516.     err = PBGetCatInfoSync ( & rec ) ;
  517. if ( ! ( rec . hFileInfo . ioFlAttrib & 0x10 ) ) { /* Not a folder */ if ( ! err ) {
  518.             err = dirNFErr ;
  519.         }
  520.     }
  521.     parent -> parID = rec . dirInfo . ioDrParID ;
  522.     parent -> name [ 0 ] = 0 ;
  523.     return err ;
  524. }
  525. OSErr
  526. GetFullPathHandle ( FSSpec * fss , Handle * h )
  527. {
  528.     Handle  tempH = NULL ;
  529.     short err ;
  530.     FSSpec fs = * fss ;
  531.     while ( fs . parID > 1 ) {
  532.         tempH = NULL ;
  533. PtrToHand ( & fs . name [ 1 ] , & tempH , fs . name [ 0 ] ) ; PtrAndHand ( ( void * ) ":" , tempH , 1 ) ;
  534.         HandAndHand ( * h , tempH ) ;
  535. SetHandleSize ( * h , 0L ) ; HandAndHand ( tempH , * h ) ; DisposeHandle ( tempH ) ; tempH = NULL ; 
  536. GetFolderParent ( & fs , & sSpec ) ;
  537.         fs = sSpec ;
  538.     }
  539.     GetVolName ( fs    . vRefNum , fs . name ) ;
  540. PtrToHand ( & fs . name [ 1 ] , & tempH , fs . name [ 0 ] ) ; PtrAndHand ( ( void * ) ":" , tempH , 1 ) ;
  541.     HandAndHand ( * h , tempH ) ;
  542.     SetHandleSize ( * h , 0L ) ;
  543.     HandAndHand ( tempH , * h ) ;
  544.     DisposeHandle ( tempH ) ;
  545.     tempH = NULL ;
  546.     if ( ! IsFolder ( fss ) ) {
  547.     SetHandleSize ( * h , GetHandleSize ( * h ) - 1 ) ; // Remove colon }
  548.     return 0 ;
  549. }
  550. *end*
  551.  
  552. 1.8) Q: So how do I get the names of the files in a directory? 
  553.  
  554. A: You use PBGetCatInfo again, but this time you set ioFDirIndex 
  555. to 1 or more (you need to know the dirID and vRefNum of the 
  556.  
  557. folder you're interested in) You then call PBGetCatInfoSync for 
  558. values of ioFDirIndex from 1 and up, until you get an fnfErr. 
  559. Any other err means you are not allowed to get info about THAT 
  560. item, but you may be for the next. Then collect the names in the 
  561. string you made ioNamePtr point to as you go along. Note that 
  562. you need to fill in the ioDirID field for each iteration through 
  563. the loop, and preferrably clear the ioFVersNum as well. 
  564.  
  565. Note that the contents of a directory may very well change while 
  566. you are iterating over it; this is most likely on a file server 
  567. that more than one user uses, or under System 7 where you run 
  568. Personal File Share. 
  569.  
  570. 1.9) Q: How do I find the name of a folder for which I only know 
  571. the dirID and vRefNum? 
  572.  
  573. A: You call (surprise!) PBGetCatInfo! Make ioNamePtr point to an 
  574. empty string (but NOT NULL) of length 63 (like, an Str63) and 
  575. ioFDirIndex negative (-1 is a given winner) - this makes 
  576. PBGetCatInfo return information about the vRefNum/dirID folder 
  577. instead of the file/folder specified by vRefNum, parID and name. 
  578. 1.10) Q: How do I make the Finder see a new file that I created? 
  579. Or if I changed the type of it; how do I display a new icon for 
  580. it? 
  581.  
  582. A: You call (surprise!) PBGetCatInfo followed by PBSetCatInfo 
  583. for the FOLDER the file is in. Inbetween, you should set 
  584. ioDrMdDat to the current date&time. Code: 
  585.  
  586. *code*
  587. OSErr
  588. TouchFolder ( short vRefNum , long parID ) {
  589. CInfoPBRec rec ;
  590. Str63 name ;
  591. short err ;
  592. rec . hFileInfo . ioNamePtr = name ; name [ 0 ] = 0 ;
  593. rec . hFileInfo . ioVRefNum = vRefNum ; rec . hFileInfo . ioDirID = parID ; rec . hFileInfo . ioFDirIndex = -1 ; rec . hFileInfo . ioFVersNum = 0 ; err = PBGetCatInfo ( & rec ) ;
  594.     if ( err ) {
  595. return err ;
  596.     }
  597. GetDateTime ( & rec . dirInfo . ioDrMdDat ) ; rec . hFileInfo . ioVRefNum = vRefNum ;
  598. rec . hFileInfo . ioDirID = parID ; rec . hFileInfo . ioFDirIndex = -1 ; rec . hFileInfo . ioFVersNum = 0 ;
  599.     err = PBSetCatInfo ( & rec ) ;
  600.     return err ;
  601. }
  602. *end*
  603.  
  604. 1.11) Q: Aren't we done with PBGetCatInfo soon? 
  605.  
  606. A: Well, it turns out that you can also find out whether an 
  607. FSSpec is a file or a folder by calling PBGetCatInfo and check 
  608. bit 4 (0x10) of ioFlAttr to see whether it is a folder. You may 
  609. prefer to call ResolveAliasFile for this instead. 
  610.  
  611. You can also check the script of the file's title using 
  612. PBGetCatInfo and check the ioFlFndrXInfo field if you want to 
  613. work with other script systems than the Roman system. 
  614.  
  615. Another common use is to find out how many items are in a 
  616. folder; the modification date of something or the correct 
  617. capitalization of its name (since the Mac file system is case 
  618. independent BUT preserves the case the user uses) 
  619.  
  620. 1.12) Q: How do I set what folder should initially be shown in 
  621. the SFGetFile boxes? 
  622.  
  623. A: You stuff the dirID you want to show into the lo-mem global 
  624. CurDirStore, and the NEGATIVE of the vRefNum you want into the 
  625. lo-mem global SFSaveDisk. 
  626.  
  627. If you are using CustomGetFile and return sfSelectionChanged 
  628. from an "init" message handler, you must remember to clear the 
  629. script code, else the selection will not change. 
  630.  
  631. 1.13) Q: How do I find the folder my application started from? 
  632. How do I find the application file that's running?
  633.  
  634. A: Under System 7, you call GetCurrentProcess, followed by 
  635. GetProcessInformation with a pointer to an existing FSSpec in 
  636. the parameter block. This will give you your file, and, by using 
  637. the vRefNum and parID, the folder the application is in.
  638.  
  639. Beware from writing to your applications resource or data forks; 
  640. the former breaks on CDs/write protected floppies/file 
  641. servers/virus checkers, the latter fails on PowerPC as well as 
  642. in the above cases.
  643.  
  644. *2* Serial ports 
  645.  
  646. 2.1) Q: How do I get at the serial ports? 
  647.  
  648. A: You call OpenDriver for the names "\p.AOut" and "\p.AIn" to 
  649. get at the modem port, and "\p.BOut" and "\p.BIn" for the 
  650. printer port. The function RAMSDOpen was designed for the 
  651. original Mac with 128 kB of memory and 64 kB of ROM, and has 
  652. been extinct for several years. 
  653.  
  654. However, many users use their serial ports for MIDI, LocalTalk, 
  655. graphic tablets, or what have you and have installed an 
  656. additional serial port card to get more ports. What you SHOULD 
  657. do as a good application is to use the Comms Toolbox Resource 
  658. Manager to search for serial resources; this requires that the 
  659. Comms Toolbox is present (true on earlier System 6 with an INIT, 
  660. on later System 6 and System 7 always, as well as on A/UX) and 
  661. that you have initialized the comms resource manager. The exact 
  662. code follows (adapted from Inside Mac Comms Toolbox): 
  663.  
  664. *code*
  665. #include <CommsResources.h>
  666. OSErr
  667. FindPorts ( Handle * portOutNames , Handle * portInNames , Handle * names , Handle * iconHandles ) {
  668. OSErr ret = noErr ;
  669. short old = 0 ;
  670. CRMRec theCRMRec , * found ; CRMSerialRecord * serial ;
  671. * portOutNames = NewHandle ( 0L ) ; * portInNames = NewHandle ( 0L ) ; * names = NewHandle ( 0L ) ;
  672. * iconHandles = NewHandle ( 0L ) ; while ( ! ret ) {
  673.         theCRMRec . crmDeviceType = crmSerialDevice ;
  674.         theCRMRec . crmDeviceID = old ;
  675.         found = ( CRMRec * ) CRMSearch ( ( QElementPtr ) & theCRMRec ) ;
  676.         if ( found ) {
  677.             serial = ( CRMSerailRec * ) found -> crmAttributes ;
  678.             old = found -> crm DeviceID ;
  679. PtrAndHand ( & serial -> outputDriverName , * portOutNames , sizeof ( serial -> outputDriverName ) ) ;
  680. PtrAndHand ( & serial -> inputDriverName , * portInNames , sizeof ( serial -> inputDriverName ) ) ;
  681.             PtrAndHand ( & serial -> name , * names , 
  682.                 sizeof ( serial -> name ) ) ;
  683. PtrAndHand ( & serial -> deviceIcon , * iconHandles , sizeof ( serial -> deviceIcon ) ) ;
  684.         } else {
  685.             break ;
  686.         }
  687.     }
  688.     return err ;
  689. }
  690. *end*
  691.  
  692. This will create four handles with the driver names, device 
  693. names and driver icon handles for all of the available serial 
  694. devices. Then let the user choose with a pop-up menu or 
  695. scrolling list, and save the choice in your settings file. 
  696.  
  697. You can use OpenDriver, SetReset, SetHShake, SetSetBuf, 
  698. SerGetBuf and the other Serial Manager functions on these 
  699. drivers. To write to the serial port, use FSWrite for 
  700. synchronous writes that wait until all is written, or PBWrite 
  701. asynchronously for queuing up data that is supposed to go out 
  702. but you don't want to wait for it. At least once each tim 
  703.  
  704. e through your event loop, you should call SerGetBuf on the in 
  705. driver reference number you got from OpenDriver, and call FSRead 
  706. for that many bytes - neither more nor less. 
  707.  
  708. If you are REALLY interested in doing the right thing, you will 
  709. use the Communications Toolbox Connection Manager instead; this 
  710. will give you access to modems, direct lines, and networks of 
  711. various kinds using the same API! Great for stuff like BBSes 
  712. that may be on a network as well etc. The Comms Toolbox also 
  713. priovides modularized terminal emulat 
  714.  
  715. ion and file transfer tools, although the Apple-suplied VT102 
  716. tool is pretty lame, as is the VT102 mode of the VT320 tool. 
  717.  
  718. *3* TCP/IP and sockets 
  719.  
  720. 3.1) Q: Where is a Berkley sockets library for the Mac? 
  721.  
  722. A: There are some problems with that. MacTCP, the Mac Toolbox 
  723. implementation of TCP/IP, doesn't have an API that looks at all 
  724. like Berkley sockets. For instance, there is ONE paramater-block 
  725. call to do a combined listen()/accept()/bind() - sort of. I have 
  726. heard that there may be a socket library available by ftp from 
  727. MIT but haven't seen it myself. 
  728.  
  729. There is also a pretty good C++ TCP implementation called GUSI 
  730. which is easily handled, and it also is callable from C using 
  731. the Berkley socket API. Apart from TCP, it also handles 
  732. "standard" Mac network protocols such as ADSP. The big 
  733. disadvantage is that it is currently only implemented for MPW. 
  734. The ftp site is nic.switch.ch, software/mac/src/mpw_c. 
  735.  
  736. I can also recommend the Communications Toolbox; for the price 
  737. of using an API that is simpler than the Berkley sockets, you 
  738. get the benefit of being able to use any kind of connection (TCP 
  739. tools are available) 
  740.  
  741. Novell and Wollogong offer commercial socket-like libraries. 
  742.  
  743. 3.2) Q: Where do I find MacTCP? 
  744.  
  745. A: You can buy the MacTCP developers kit from APDA. It is also 
  746. available on E T O, and if you want saner headers than those, 
  747. try ftp to seeding.apple.com. 
  748.  
  749. *4* AppleEvents and the AppleEvent Object Model 
  750.  
  751. 4.1) Q: What are AppleEvents? 
  752.  
  753. A: AppleEvents are a level-5 network protocol. If you are not 
  754. familiar with the ISO network stack, this means it's a way of 
  755. structuring sessions between network entities (programs) that is 
  756. not dependent on the underlying protocol (such as PPC or TCP/IP) 
  757. Despite being a network protocol, they can be very useful on 
  758. Macs that are not on a network. In short, they provide 
  759. applications with a comprehensive way to send arbitrary 
  760. structured data to other applications (or themselves) which 
  761. receive the events through their main event loop. 
  762.  
  763. The AppleEvent Object Model is a way of looking at applications 
  764. and the data they contain, and also a level-6 network protocol. 
  765. You _can_ send AppleEvent Object Model data through AppleEvents 
  766. (and the standard AppleEvents defined in the AppleEvent Registry 
  767. use it) but you don't have to - unless you want to talk with 
  768. other applications, of course, then the AEOM is a lingua franca. 
  769. 4.2) Q: What are the four required AppleEvents? 
  770.  
  771. A: There are four events your application really must implement 
  772. if you want to sell it: the kCoreEventClass class, 
  773. kAEOpenApplication, kAEQuitApplication, kAEOpenDocuments and 
  774. kAEPrintDocuments events IDs. When you support these events (or 
  775. any AppleEvents) you will not get startup info through 
  776. GetAppParams() anymore, unless you run under System 6 of course. 
  777. The kAEOpenApplication event will be sent to you when the user 
  778. double-clicks your app and it's not started yet. When receiving 
  779. it, you can put up a new untitled window. 
  780.  
  781. kAEOpenDocuments is sent when the user double-clicks your apps 
  782. documents. Note that if the first AppleEvent you receive is a 
  783. kAEOpenDocuments event, the user started your app by 
  784. double-clicking its documents. 
  785.  
  786. kAEPrintDocuments is sent when the user selects your documents 
  787. and chooses "Print" in the Finder menu. If this is the first 
  788. AppleEvent you receive, you should print the documents and then 
  789. quit the application again; if you received a kAEOpenApplication 
  790. or kAEOpenDocuments event before this, you should just print the 
  791. documents and close them when you're done. 
  792.  
  793. kAEQuitApplication is sent to you when the user chooses 
  794. "Shutdown" or "Restart" from the Apple Menu. You should ask the 
  795. user whether he wants to save any unsaved changed documents, and 
  796. then quit unless the user presses Cancel. 
  797.  
  798. Interestingly enough, you can use these four AppleEvents to send 
  799. even to non-AE-aware applications, and the system will translate 
  800. these events into fake menu selections for you. 
  801.  
  802. A good way of shutting down the Finder is to send it a Quit 
  803. AppleEvent. You should send a Quit AppleEvent to File Sharing 
  804. Extension before you shut down the Finder, though; the FSE is 
  805. found by looking for a process with the creator 'hhgg'. 
  806.  
  807. 4.3) Q: Are there any limits or tradeoffs with AppleEvents? 
  808.  
  809. A: As always, more power means more responsibility. 
  810.  
  811. AppleEvents sent to applications on other Macs require 
  812. authentification the first time they are sent. If the remote Mac 
  813. allows Guests to link to programs, the INIT AutoGuest 2.0 might 
  814. help (or the code solution that comes with it and you can build 
  815. into your application) 
  816.  
  817. In the first version of the AppleEvent manager, there was a 
  818. total 64K limit on the size of data and overhead. This limit has 
  819. been lifted with the version of the AppleEvent manager that 
  820. comes with AppleScript. 
  821.  
  822. AppleEvents require a lot of memory copying and handle resizing 
  823. in their construction; this means that large AppleEvents may be 
  824. slow in construction, especially when compared to a pure PPC 
  825. Toolbox or ADSP/ASDSP link. 
  826.  
  827. You should use your own application signature as event class for 
  828. AppleEvents you make up, in order not to collide with anybody 
  829. else. Other than that, you are free to make your own events for 
  830. your own needs, though supporting the required events and at 
  831. least a subset of the Core event suite will buy you a lot of 
  832. functinality from within AppleScript. Especially important are 
  833. the Get Current Selection and Set Current Selection events 
  834. (which are really Get/Set Data on the contents of the current 
  835. selection of the application) 
  836.  
  837. The signature for your application SHOULD be registered with DTS 
  838. to avoid conflicts; this is done through e-mail to 
  839. DEVSUPPORT@AppleLink.Apple.Com and the form you use is located 
  840. on the developer CDs and found on ftp.apple.com. 
  841.  
  842. *5* AppleScript 
  843.  
  844. 5.1) Q: How does AppleEvents interface with AppleScript? 
  845.  
  846. A: AppleEvents are the meat and potatoes of AppleScript. If you 
  847. support the AppleEvent Object Model from within your 
  848. application, users can control you through AppleScript. 
  849.  
  850. The first thing you should do is get ahold of Inside Mac: 
  851. Interapplication Communication, and a copy of the AppleEvents 
  852. Registry. The former tells you all you ever need to know about 
  853. AppleEvents, while the latter is paramount for implementing the 
  854. right standard events. If everybody use the standard events, 
  855. dynamic data interchange between any applications will become 
  856. sweet reality! 
  857.  
  858. Then there is the 'aete' resource which lets you put names on 
  859. the events you support, so that users can "Open Terminology" on 
  860. your application from within the Apple Script Editor and use the 
  861. proper AppleScript commands in their scripts. The format of an 
  862. aete resource is defined in Inside Macintosh: Interapplication 
  863. Communication. 
  864.  
  865. 5.2) Q: Can I compile and run scripts from within my 
  866. application? 
  867.  
  868. A: Yes, this is very simple. There are toolbox calls for reading 
  869. scripts, compiling scripts, and executing scripts. (OSACompile, 
  870. OSAExecute) These are all documented in Inside Mac: 
  871. Interapplication Communication. 
  872.  
  873. 5.3) Q: Is this a good way of getting a macro language almost 
  874. for free? 
  875.  
  876. A: "Good" is an understatement. Just let users write scripts, 
  877. load them into menu items and go. Total systems integration in 
  878. under a week, including adding support for the AEOM to your 
  879. application. 
  880.  
  881. There is source code for an application called "MenuScipter" on 
  882. the developer CD which shows you how to do an application with 
  883. all of the menus being AppleScript scripts. 
  884.  
  885. *6* Drawing using QuickDraw 
  886.  
  887. 6.1) Q: Why is CopyBits so slow? 
  888.  
  889. A: It is not. It just requires some hand-holding to get good 
  890. results. The main rules are: Make sure the source and 
  891. destination pixMaps are of the same depth. 
  892.  
  893. Make sure the front color is black and the back color is white. 
  894.  
  895. Use srcCopy and don't use a masking region. 
  896.  
  897. Copy to an unclipped window (the frontmost window). 
  898.  
  899. Make sure the ctSeed values of the source pixMap and dest pixMap 
  900. match. 
  901.  
  902. Copying few and large pixMaps is faster than copying many and 
  903. small ones. Icon-sized sprites count as small ones. 
  904.  
  905. Make sure your source bitmap or pixelMap has the same alignment, 
  906. when adjusted for the source and destination rect expressed in 
  907. global screen coordinates. The necessary alignment is 32 bits (4 
  908. bytes), although 128 bit (16 byte) alignment is probably even 
  909. better on 68040 macs and won't hurt on other macs. 
  910.  
  911. Example of global alignment: 
  912.  
  913. Your window is positioned at (42,100) (H,V) 
  914.  
  915. Your destination rectangle is (10,20)-(74,52) 
  916.  
  917. The alignment coefficient of the rectangle in global coordinates 
  918. is (42+10)*bitDepth where bitDepth is one of 1,2,4,8,16 or 32. 
  919.  
  920. Make sure your source pixmap rect has the same coeffecient 
  921. modulo your alignment factor (in bits) For black&white macs, 
  922. this is still true, although bitDepth is fix at 1. Offscreen 
  923. pixMaps can calculate with a "global posistion" of 0,0 and get 
  924. correct results. 
  925.  
  926. 6.2) Q: Why is CopyBits still too slow? 
  927.  
  928. A: Because there is always some overhead involved in calling 
  929. QuickDraw; you have the trap dispatcher, clipping checks, and 
  930. checking whether the CopyBits call is being recorded in a PICT 
  931. handle (if you called OpenPicture) 
  932.  
  933. If you can't live with this, look at *7* below, but PLEASE try 
  934. and make CopyBits work, and retain the CopyBits code in your 
  935. application, so users with special monitors (accellerator cards, 
  936. PowerBook color screens, Radius Pivot screens) can still play 
  937. your game. (non-game applications don't need more speed than 
  938. CopyBits can give at its max. Promise!) 
  939.  
  940. 6.3) Q: What is the fastest way to set one pixel? 
  941.  
  942. A: NOT SetCPixel()! Assuming you have the correct ForeColor() 
  943. set, you can set the pen size to (1,0) and call Line (0,1) 
  944.  
  945. I have heard PaintRect is good for this but requires slightly 
  946. more code.  Using PaintRect eliminates a trap call. 
  947.  
  948. 6.4) Q: Why do pictures I record suddenly draw as empty space or 
  949. not draw at all? 
  950.  
  951. A: When recording pictures, you have to set the clipping area to 
  952. exactly the frame of the picture you are recording. This is 
  953. because it is initally set at -32768,32727 in both directions, 
  954. and offsetting the picture even one pixel when drawing it will 
  955. result in the region wrapping around and becoming empty. 
  956.  
  957. When recording pictures, do this: 
  958.  
  959. *code*
  960. PicHandle h = OpenPicture ( & theRect ) ; ClipRect ( & theRect ) ;
  961.     /* draw the picture */
  962.     ClosePicture ( ) ;
  963. *end*
  964.  
  965. 6.5) Q: Where can I find the format of picture files and 
  966. resources? 
  967.  
  968. A: The format of a picture resource version 1 is defined in a 
  969. technical note. This format is obsolete. 
  970.  
  971. The format of a picture resource version 2 is defined in Old 
  972. Inside Mac vol V, with addenda in Old Inside Mac vol VI. 
  973.  
  974. Some things happen with QuickTime compressed pictures; try the 
  975. Inside Mac: QuickTime book or wait for Inside Mac: Imaging which 
  976. is the definite reference on QuickDraw. 
  977.  
  978. The format of a picture file is the same as that of a picture 
  979. resource with 512 added 0 bytes in front. 
  980.  
  981. 6.6) Q: GWorlds? 
  982.  
  983. A: What about them? They're great. Look them up in Old Inside 
  984. Mac vol VI. Don't forget to SetGWorld back to what it was before 
  985. calling WaitNextEvent. 
  986.  
  987. 6.7) Q: How do I find the current depth of the screen? 
  988.  
  989. A: My question to you is: What screen? Many macs have more than 
  990. one screen attached. You can use GetDeviceList and walk the 
  991. devices to find the screen you're looking for (use 
  992. TestDeviceAttrib to see whether it's a screen) or you can call 
  993. GetMaxDevice() to find the deepest device your window 
  994. intersects. 
  995.  
  996. Once you have the device handle, finding the depth is just a 
  997. matter of looking at the dgPMap pixMapHandle, and dereference it 
  998. to the pmSize field. Done. 
  999.  
  1000. *7* Drawing directly to screen 
  1001.  
  1002. 7.1) Q: Why is it a bad idea to draw directly to screen? 
  1003.  
  1004. A: Because of several reasons: 
  1005.  
  1006. - You will be incompatible with future display hardware. 
  1007.  
  1008. - You will be incompatible with some present-day display 
  1009. hardware, such as Radius Pivots and PowerBook color screens. 
  1010.  
  1011. - You have to think about a lot of things; testing it all on 
  1012. your own machine is not possible and the chances of crashing are 
  1013. great. 
  1014.  
  1015. - You will be incompatible with future hardware where devices 
  1016. may live in some unaccessible I/O space. 
  1017.  
  1018. 7.2) Q: But I really need to do it. I can't make my animation 
  1019. into a QuickTime movie, and CopyBits is too slow, even when 
  1020. syncing to the screen retrace. 
  1021.  
  1022. A: You have to prepare yourself, and ask these questions: 
  1023.  
  1024. 1) Do I want to support all screens, or just 8-bit devices? 
  1025.  
  1026. 2) Do I have a few weeks of free time to make it work? 
  1027.  
  1028. 3) Do I want to get nasty mail when I break on some hardware and 
  1029. have to rev the application - even if I may not be able to get 
  1030. ahold of the hardware that makes it break? 
  1031.  
  1032. If all you're doing is rendering an image pixel-by-pixel or 
  1033. line-by-line, maybe you can draw directly into an offscreen 
  1034. pixMap/GWorld and then CopyBits the entire GWorld to screen? 
  1035. That will be more compatible, especially if you use the 
  1036. keepLocal flag when creating the GWorld. 
  1037.  
  1038. 7.3) Q: Okay, so how do I get the base address of the screen? 
  1039.  
  1040. A: "The" screen? Which screen? There may be several. The base 
  1041. address may be on an accellerated screen card. There may be more 
  1042. than one screen covering the same desktop area. 
  1043.  
  1044. Due to unfortunate circumstances, there is a bug in 
  1045. GetPixBaseAddr() that causes it to return incorrect results for 
  1046. some versions of System 7. Instead, get the baseAddr directly 
  1047. from the gdPMap handle of the GDHandle for the screen you draw 
  1048. to. This address may need switching to 32bit mode to be valid. 
  1049.  
  1050. 7.4) Q: Quit stalling and give me code! 
  1051.  
  1052. A: Okay, but I'll let you sweat over Inside Mac to figure out 
  1053. what it does. All of it is important; believe me! To make this 
  1054. code run faster, a lot of the things it does can be done once 
  1055. before starting to draw. 
  1056.  
  1057. Make sure that you have a window that covers the area where you 
  1058. are drawing, so other windows will not be overdrawn. Also make 
  1059. sure that you do not do direct-to-screen-drawing while you are 
  1060. in the background. 
  1061.  
  1062. *code*
  1063. /* This is presently untested code */
  1064. /* value is dependent on what depth the screen has */
  1065. /* this code doesn't work on non-color-quickdraw Macs (i e the MacClassic) */
  1066. /* where is in GLOBAL coordinates */
  1067. void
  1068. SetPixel ( Point where , unsigned long value ) {
  1069. Rect r ;
  1070. GDHandle theGD ;
  1071. char * ptr ;
  1072. long rowBytes ;
  1073. short bitsPerPixel ;
  1074. PixMapHandle pmh ;
  1075. Boolean oldMode ;
  1076.     r . left = where . h ;
  1077.     r . top = where    . v ;
  1078.     r . right = r . left + 1 ;
  1079. r . bottom = r . top + 1 ;
  1080.     theGD = GetMaxDevice ( & r ) ;
  1081.     if ( theGD ) {
  1082. where . v -= ( * theGD ) -> gdRect . left ; where . h -= ( * theGD ) -> gdRect . top ; pmh = ( * theGD ) -> gdPMap ;
  1083. rowBytes = ( ( * pmh ) -> rowBytes ) & 0x3fff ; ptr = ( char * ) ( * pmh ) -> baseAddr ; bitsPerPixel = ( * pmh ) -> pixelSize ; oldMode = true32b ;
  1084.         ptr += where . v * rowBytes ;
  1085. SwapMMUMode ( & oldMode ) ; switch ( bitsPerPixel ) { case 1 :
  1086. if ( value & 1 ) { 
  1087. ptr [ where . h >> 3 ] |= ( 128 >> ( where . h & 7 ) ) ;
  1088.             } else {
  1089.                 ptr [ where . h >> 3 ] &= ~( 128 >> ( where . h & 7 ) ) ;
  1090.             }
  1091.             break ;
  1092.         case 2 :
  1093.             ptr [ where . h >> 2 ] &= ( 192 >> 2 * ( where . h & 3 ) ) ;
  1094. ptr [ where . h >> 2 ] |= ( value & 3 ) << 2 * ( 3 - ( where . h & 3 ) ) ; break ;
  1095.         case 4 :
  1096.             ptr [ where . h >> 1 ] &= ( where . h & 1 ) ? 0xf : 0xf0 ;
  1097. ptr [ where . h >> 1 ] |= ( value & 15 ) << 4 * ( 1 - ( where . h & 1 ) ) ; break ;
  1098.         case 8 :
  1099.             ptr [ where . h ] = value ;
  1100.             break ;
  1101.         case 16 :
  1102. ( ( unsigned short * ) ptr ) [ where . h ] = value ;
  1103.             break ;
  1104.         case 32 :
  1105. ( ( unsigned long * ) ptr ) [ where . h ] = value ;
  1106.             break ;
  1107.         }
  1108.         SwapMMUMode ( & oldMode ) ;
  1109.     }
  1110. }
  1111. *end*
  1112.  
  1113. *8* Cache issues and other processor differences 
  1114.  
  1115. 8.1) Q: Why does my application work on an SE with accellerator 
  1116. (or a Mac II or Quadra), but not on one without? 
  1117.  
  1118. A: Assuming you're not calling Color QuickDraw (which is not 
  1119. available on accellerated SEs), you most probably have an 
  1120. odd-aligned word access somewhere. 
  1121.  
  1122. The 68000 does not allow words or longwords to be read from odd 
  1123. addresses, while the 68020 and up relaxes this restriction (it 
  1124. still is slower than aligned-word access though) 
  1125.  
  1126. This may or may not crash depending on your compiler: 
  1127.  
  1128. *code*
  1129. struct foo {
  1130.     char c1 ;
  1131.     char c2 ;
  1132.     char c3 ;
  1133.     char c4 ;
  1134.     char c5 ;
  1135. } bar ;
  1136.     long * x = ( long * ) & bar . c2 ;
  1137.     * x = 0x12345678 ; /* X is odd if compiler doesn't pad */
  1138. This WILL crash on an SE/Plus/Classic/PB100:
  1139. char foo [ 10 ] ;
  1140.     long * x = ( long * ) & foo [ 1 ] ;
  1141.     * x = 0x12345678 ;
  1142. *end*
  1143.  
  1144. 8.2) Q: Why does my application work on a IIci but not on a 
  1145. Quadra? 
  1146.  
  1147. A: Two reasons: 
  1148.  
  1149. 1) The Quadras 900 and 950 have special processors that handle 
  1150. the serial ports; if you write directly to the serial chips, you 
  1151. will crash (this goes for the IIfx as well) 
  1152.  
  1153. 2) The Quadras have 68040 processors, as have the Centrises. 
  1154. These processors have separate instruction and data caches (like 
  1155. the 68030) but they are larger (4K each) and unlike the 68030 
  1156. which is write-through data cached, the 68040 is copy-back data 
  1157. cached. This means that changes you make to "your code" aren't 
  1158. really changed all the time, since the changes may still be in 
  1159. the data cache and not written to memory when the CPU reads that 
  1160. part of memory into its I-cache. Even worse; that part might 
  1161. already have been read into the I-cache before you change it in 
  1162. the D-cache, meaning that writing out the D-cache will still not 
  1163. be enough. You need to flush both the caches when writing 
  1164. self-modifying code. 
  1165.  
  1166. Self-modifying code includes code that builds its own jump 
  1167. tables and code that decrypts itself and code that "stubs" MDEFs 
  1168. or WDEFs to jump back into the application code. 
  1169.  
  1170. You flush the cache using FlushDataCache() which is implemented 
  1171. if Gestalt says you have a 68020 or better processor (or if the 
  1172. _HwDispatch trap is implemented) 
  1173.  
  1174. 8.3) Q: Why does my application work on my Quadra but not on my 
  1175. accellerated SE? 
  1176.  
  1177. A: You're probably calling Color QuickDraw without first 
  1178. checking if it's available. The following machines do not have 
  1179. color QuickDraw in ROM nor RAM: 
  1180.  
  1181. Mac Plus, Mac SE, Mac Classic, Mac Luggable, PowerBook 100, 
  1182. Outbound 
  1183.  
  1184. 8.4) Q: I do check for color quickdraw, but crash nevertheless. 
  1185.  
  1186. A: _Gestalt lies under some versions of System 7; it says that 
  1187. non-color machines HAVE color QuickDraw when you test using the 
  1188. gestaltQuickdrawFeatures selector. 
  1189.  
  1190. Instead, check the gestaltQuickdrawVersion selector, if it 
  1191. returns >= gestalt8BitQuickdraw then you can safely use 
  1192. gestaltQuickdrawFeatures, else you only have b/w QuickDraw. 
  1193.  
  1194. 8.5) Q: Why are there no compilers that optimize for the 
  1195. Mc68040? 
  1196.  
  1197. A: Beats me; optimizing for the 68040 can make programs up to 
  1198. 50% faster on that chip while still losing nothing, or very 
  1199. little (less than 10%) on older chips. 
  1200.  
  1201. *9* Inflammatory subjects 
  1202.  
  1203. 9.1) Q: What about pre-emptive multitasking? 
  1204.  
  1205. A: To the user, the Mac multitasking method, which builds upon 
  1206. each application calling WaitNextEvent, GetNextEvent or 
  1207. EventAvail every so often and the Process Manager/MultiFinder 
  1208. switching applications only at such calls, is at least as good 
  1209. as preemtive multitasking, because the present system 
  1210. priotitizes user interface responsiveness over everything else. 
  1211. The only shortfall about this is formatting floppies, which 
  1212. locks up the Mac CPU. This is because the Mac floppy controller 
  1213. is really stupid, and would happen even if the Mac multitasked 
  1214. preemptively. 
  1215.  
  1216. There IS "real" pre-emptive multitasking available for use in 
  1217. Mac applications; the expensive way is buying A/UX 3.0 which can 
  1218. have Mac applications written as UNIX processes; the cheap way 
  1219. is installing the Thread Manager which will allow you to create 
  1220. pre-emptive threads. However, the restrictions on those threads 
  1221. are the same as those on Time Manager tasks: don't call any 
  1222. function in an unloaded segment, and don't call QuickDraw or any 
  1223. toolbox call which may move memory (which are most ToolBox 
  1224. calls; paradoxally, BlockMove is safe :-) as are, surprisingly, 
  1225. FSRead and FSWrite) 
  1226.  
  1227. There are several problems with making the Mac OS preemptive; 
  1228. including apps that draw outside their windows or directly to 
  1229. screen, user dragging and other issues. 
  1230.  
  1231. 9.2) Q: What about protected memory? I'm sick and tired of 
  1232. re-booting when my application crashes. 
  1233.  
  1234. A: Write better software! 
  1235.  
  1236. Or install The Debugger from Jasik Designs, which can provide 
  1237. your application with write-protection of critical parts of 
  1238. memory. This may only work for 030 Macs, though. 
  1239.  
  1240. Making the Mac OS memory-protected is tricky, because 
  1241. applications expect to be able to write to low memory, the 
  1242. system heap, temporary memory, window lists, and even each 
  1243. other's heaps in some interapplication communication solutions 
  1244. that date back to before AppleEvents and the PPC Toolbox. 
  1245.  
  1246. *10* Handles; they are driving me crazy 
  1247.  
  1248. 10.1) Q: What is a handle? 
  1249.  
  1250. A: A handle is a pointer to a pointer to something. However, it 
  1251. is more than that; creating a handle by taking the address of 
  1252. one of your own pointers does NOT create a Handle; the Memory 
  1253. Manager will only deal properly with Handles that are created 
  1254. using NewHandle or something that calls it (such as NewRgn or 
  1255. GetResource) 
  1256.  
  1257. 10.2) Q: When do I have to lock a Handle? 
  1258.  
  1259. A: The contents of a Handle may move, and when it does, the 
  1260. pointer your handle is pointing to is changed to point to the 
  1261. new address so your handle is always valid. The toolbox may call 
  1262. the memory manager to allocate more memory pretty much anytime 
  1263.  
  1264. you call it (the toolbox) and when memory is allocated, your 
  1265. handle may move in memory. Don't dereference a handle into a 
  1266. pointer (or take the address of a field in a record a handle is 
  1267. double-pointing to) and then call the toolbox and expect the 
  1268. pointer to still be valid. The only way to ensure that the 
  1269. pointer will still be valid is to call HLock on the handle to 
  1270. lock it. 
  1271.  
  1272. Use HGetState and HSetState to save & restore the "locked" state 
  1273. of a handle when you lock it. 
  1274.  
  1275. 10.3) Q: How do I dispose of Handles? 
  1276.  
  1277. A: DisposeHandle (formerly called DisposHandle) once and ONLY 
  1278. once will do the trick. Trying to dispose of an already disposed 
  1279. Handle is an error. DoubleTrouble (see above) will catch such 
  1280. bugs when they do occur. 
  1281.  
  1282. 10.4) Q: What about resources? 
  1283.  
  1284. A: Calling GetResource returns NULL if the resource is not found 
  1285. or there is not enough memory, else it returns a handle to the 
  1286. resource. This handle may be moved or locked like any other 
  1287. handle, but DO NOT call DisposeHandle to get rid of a resource 
  1288. handle - call ReleaseResource. DisposeResource (see above) will 
  1289. catch this kind of bug. 
  1290.  
  1291. Remember that AddResource makes a resource handle out of an 
  1292. ordinary handle, and RmveResource or DetachResource makes an 
  1293. ordinary handle out of a resource handle. You cannot call 
  1294. AddResource with a resource handle; you have to DetachResource 
  1295. it first. 
  1296.  
  1297. Resource handles are automagically disposed when the resource 
  1298. file they belong to is closed. 
  1299.  
  1300. 10.5) Q: I'm trying to use a largish array in Think C, but get a 
  1301. "code overflow" error. This is valid C, why doesn't it work? 
  1302.  
  1303. A: The ANSI standard does not guarantee that any structure 
  1304. larger than 32767 bytes be correctly handled. Because of 
  1305. historical constraints, the Mac memory model is built around 
  1306. several small blocks of size 32K or less; these are used both 
  1307. for code and global/static data. If you want to use more code or 
  1308. data, you have to turn on "far code" or "far data" - you still 
  1309. will not get around the restriction of 32K code or data per 
  1310. compiled file, though. 
  1311.  
  1312. As opposed to, say, DOS or Windows, however, you can allocate as 
  1313. much memory as you want (and there is in the machine) and step 
  1314. through it using ordinary pointers; it's just that global and 
  1315. static data space is addressed off the A5 register using a 16bit 
  1316. displacement addressing mode in the 68000 processor. 
  1317.  
  1318. *11* _Gestalt and compatibility 
  1319.  
  1320. 11.1) Q: I see all these people call Gestalt without first 
  1321. checking whether it's implemented. Isn't that bad? 
  1322.  
  1323. A: No; Gestalt and a few other traps (the HXxx file manager 
  1324. traps, and FindFolder) are implemented using glue so they do the 
  1325. right thing even if the trap is not implemented. 
  1326.  
  1327. If you want to get rid of the glue, you can #define 
  1328. SystemSevenOrLater (and, using Think C/C++, re-pre-compile 
  1329. MacHeaders) However, then you will be responsible for checking 
  1330. for these features before you use them. 
  1331.  
  1332. 11.2) Q: What more functions are implemented in glue? 
  1333.  
  1334. A: Wake Up and Smell the Glue! [by Matthias Neeracher] 
  1335.  
  1336. How often have you wished you could use that cool new ToolBox 
  1337. call, but didn't want to make your application System 7 
  1338. dependent? Well, it might be that you *could* in fact have used 
  1339. the call. Several traps are implemented in glue, that is, much 
  1340. of their functionality is linked into your application and thus 
  1341. available even if you are running under an old System. 
  1342.  
  1343. This list applies to MPW 3.2 and should also be valid for the 
  1344. current version of Think C. If you find any inaccuracies, please 
  1345. report them to me. (neeri@iis.ee.ethz.ch) 
  1346.  
  1347. FSOpen: Tries first OpenDF, then Open. 
  1348.  
  1349. HOpenResFile: Full functionality emulated if trap not available 
  1350.  
  1351. HCreateResFile: Full functionality emulated if trap not 
  1352. available 
  1353.  
  1354. FindFolder: Under System 6, understands the following values for 
  1355. folderType and returns the System Folder for all of them: 
  1356.  
  1357. kAppleMenuFolderType 
  1358.  
  1359. kControlPanelFolderType 
  1360.  
  1361. kExtensionFolderType 
  1362.  
  1363. kPreferencesFolderType 
  1364.  
  1365. kPrintMonitorDocsFolderType 
  1366.  
  1367. kStartupFolderType 
  1368.  
  1369. kSystemFolderType 
  1370.  
  1371. kTemporaryFolderType 
  1372.  
  1373. SysEnvirons: Full functionality emulated if trap not available 
  1374.  
  1375. NewGestalt: Returns an error if not implemented 
  1376.  
  1377. ReplaceGestalt: Returns an error if not implemented 
  1378.  
  1379. Gestalt: The following selectors are always implemented: 
  1380.  
  1381. vers    mach    sysv    proc    fpu     
  1382.  
  1383. qd      kbd     atlk    ram     lram    
  1384.  
  1385. 11.3) Q: I have to support System 6, don't I? 
  1386.  
  1387. A: It would be foolish to lock yourself out of the many benefits 
  1388. the System 7 API provides for software that you start to write 
  1389. now. Some of the System 6 and older things (likely SFGetFile and 
  1390. wdRefNums among others) will be phased out of the interfaces and 
  1391. lose support; especially on future platforms. 
  1392.  
  1393. The installed base of System 7 is larger than that of System 6; 
  1394. this is not surprising because Apple has been shipping System 7 
  1395. for several years with all new machines, including the LCII, 
  1396. Classic II, Performas and Color Classic. Another argument is 
  1397. that newer computer owners (having System 7) are much more 
  1398. likely to buy new software than old computer owners who have 
  1399. systems that already do what they want them to. 
  1400.  
  1401. The added work to support both System 6 and System 7 is 
  1402. significant; if you have the time and money you may want to do 
  1403. it, but only supporting System 6 and not System 7 is doomed to 
  1404. fail in the market of today. 
  1405.  
  1406. Some may call this position subjective; I call it business sense 
  1407. based on market demographics. A rule of thumb may be that if you 
  1408. target color machines only, you can just as well demand System 7 
  1409. as well. 
  1410.  
  1411. *12* Standalone code and dynamic linking 
  1412.  
  1413. 12.1) Q: I've got a CODE resource off in limboland (sometimes 
  1414. called the resource fork) and I want to open it... what do I do? 
  1415. A: You open the file you have the code resource in, load the 
  1416. resource and lock it high (don't unlock it first, since someone 
  1417. else may be using it). Then you cast the handle to a function 
  1418. pointer, and call it normally. 
  1419.  
  1420. Suppose your code resource is compiled as a SACD id 128, and is 
  1421. defined as: 
  1422.  
  1423. *code*
  1424. long
  1425. main ( MyParams * params ) {
  1426.     switch ( params -> message ) {
  1427.     case messageInit :
  1428.         return init ( params ) ;
  1429.     ...
  1430.     }
  1431.     return 0L ;
  1432. }
  1433. *end*
  1434.  
  1435. Also suppose you already have the vRefNum, parID and name of the 
  1436. resource file you want to use. Do this: 
  1437.  
  1438. *code*
  1439.     setup_paramblock ( & the_params ) ;
  1440.     the_params . message = messageInit ;
  1441.     refNum = HOpenResFile ( vRefNum , parID , name , fsRdPerm ) ;
  1442.     if ( refNum < 1 ) {
  1443.         fail ( ResError ( ) ) ;
  1444.     }
  1445.     the_code = GetResource ( 'SACD' , 128 ) ;
  1446.     HLockHi ( the_code ) ;
  1447.     retval = ( * ( ( long ( * ) ( MyParams * ) ) * the_code ) ) ( & the_params ) ;
  1448.     ...
  1449. *end*
  1450.  
  1451. Exactly how you structure your calling conventions is up to you; 
  1452. there is no accepted standard (except for HyperCard XCMDs, but 
  1453. that is probably overkill for you). 
  1454.  
  1455. *13* 
  1456.  
  1457. 13.1) Q: How do I read the modifier keys of the keyboard? 
  1458.  
  1459. A: Just call EventAvail and check the event.modifiers field. 
  1460. Only works when you are in the foreground. You can also use 
  1461. GetKeys(), or (as a last resort) check the lo-mem global KeyMap 
  1462. directly. 
  1463.  
  1464. *14* QuickTime 
  1465.  
  1466. 14.1) Q: I want to write a Amiga QuickTime player and need the 
  1467. CODEC format details. 
  1468.  
  1469. A: Although the structure of QuickTime movies is well documented 
  1470. in Inside Mac: QuickTime, the inner workings of the Apple 
  1471. compression modules is a trade secret that Apple will only 
  1472. license to you at great cost. Perhaps it's time for a freeware, 
  1473. cross-platform QuickTime codec? 
  1474.  
  1475. *15* Ice Cream and Frozen Yoghurt 
  1476.  
  1477. 15.1) Q: Dessert? 
  1478.  
  1479. A: Honey Hill Farms Cookie Jar Frozen Yoghurt or Haagen-Dazs 
  1480. Raspberry & Cream Ice Cream.
  1481.  
  1482. Hokey-Pokey icecream with chocolate sauce and (for those who 
  1483. like their brain food firmer) Armond and Double Chocolate 
  1484. CookieTime cookies!? [Denis Birnie]
  1485.  
  1486. -- 
  1487.  -- Jon W{tte, h+@nada.kth.se, Mac Hacker Deluxe --
  1488.  
  1489.   "From now on I will re-label the EQ on the deck as Fizz and Wobble
  1490.    instead of HF and LF."
  1491.