home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 July / macformat-026.iso / mac / Shareware City / Developers / video-toolbox-95-01-14-c / VideoToolbox / VideoToolboxSources / GDVideo.c < prev    next >
Encoding:
Text File  |  1995-01-12  |  57.7 KB  |  1,571 lines  |  [TEXT/MPCC]

  1. /* 
  2. GDVideo.c
  3. Copyright © 1989-1994 Denis G. Pelli
  4.  
  5. Complete set of routines to control video drivers directly, bypassing
  6. QuickDraw's Color and Palette Managers. There is a separate function call for
  7. each of the Control and Status Calls (csc) implemented by video drivers. They
  8. are described in Designing Cards and Drivers, 3rd Ed., chapter 9. A few new
  9. calls are documented in the Display Device Driver Guide Developer Note, which
  10. appeared on the January '94 Developer CD.
  11.  
  12. This file also contains several other helpful routines that deal with video
  13. device drivers. For background, read “Video synch”.
  14.  
  15. THE MORE-USEFUL (HIGH-LEVEL) ROUTINES: (in alphabetical order)
  16.  
  17. char *GDCardName(GDHandle device);
  18. Returns the address of a C string containing the name of the video card. You
  19. should call DisposePtr() on the returned string when you no longer need it.
  20. Takes about 1.5 ms because Apple's slot routines are very slow. 
  21.  
  22. short GDClutSize(GDHandle device);
  23. Returns the number of entries in the video driver's clut in the current video
  24. mode (i.e. current pixel size). VideoToolbox.h defines a preprocessor macro
  25. GDCLUTSIZE(device) that expands to equivalent inline code.
  26.  
  27. long GDColors(GDHandle device)
  28. Number of colors, in the current mode.
  29.  
  30. short GDDacSize(GDHandle device)
  31. Figures out how many bits in the video dac.
  32.  
  33. OSErr GDGetDisplayMode(GDHandle device,unsigned short *displayModePtr
  34.     ,unsigned long *spIDPtr,unsigned short *pagePtr,Ptr *baseAddrPtr);
  35. Calls cscGetCurMode, documented in Apple's new Display Device Driver Guide
  36. Developer Note on the January '94 Developer CD. The "display mode" is a new
  37. parameter, to support multi-resolution displays. Each display mode may have
  38. multiple pixel depths (which, confusingly, have also been called "modes"). This
  39. call will only be useful if the Display Manager is present (requires PowerPC or
  40. System 7.5) and if you're using the Display Manager, which is documented in a
  41. chapter in Inside Macintosh:Advanced Color Imaging, which thus far has appeared
  42. only in draft form on the December '94 Developer CD. The call returns an error
  43. if the video driver does not support the Display Manager. UNTESTED!!
  44.  
  45. OSErr GDGetEntries(GDHandle device,short start,short count,ColorSpec *table);
  46. Calls cscGetEntries. This is much as you'd expect after reading GDSetEntries
  47. below. Note that unless the gamma table is linear, the values returned may not
  48. be the same as those originally passed by GDSetEntries. So call
  49. GDUncorrectedGamma first. Try the demo TimeVideo.
  50.  
  51. OSErr GDGetGamma(GDHandle device,GammaTbl **myGammaTblHandle);
  52. Calls cscGetGamma. Returns a pointer to the Gamma table in the specified video
  53. device. (I.e. you pass it a pointer to your pointer, a handle, which it uses to
  54. load your pointer.)
  55.  
  56. OSErr GDGetPageCnt(GDHandle device,short mode,short *pagesPtr);
  57. Calls cscGetPageCnt. Called "GetPages" in Designing Cards and Drivers, 3rd Ed.
  58. You tell it which mode you're interested in. It tells you how many pages of
  59. video ram are available in that mode.
  60.  
  61. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr);
  62. Returns 0 if no such video mode, returns 1 if mode is available.
  63. If pixelSizePtr is not NULL, then sets *pixelSizePtr to pixelSize or -1 if unknown.
  64. If pagesPtr is not NULL, then sets *pagesPtr to pages.
  65.  
  66. unsigned char *GDName(GDHandle device);
  67. Returns a pointer to the name of the driver (a pascal string). This is quick.
  68. The string is part of the driver itself, so don't modify it or try to dispose of it.
  69.  
  70. unsigned char *GDNameStr(GDHandle device);
  71. Returns a pointer to the name of the driver, as a C string. 
  72. The string is static, and will be overwritten by the next call to GDNameStr().
  73.  
  74. ColorSpec *GDNewLinearColorTable(GDHandle device);
  75. Creates a default table for use when gdType==directType.
  76.  
  77. OSErr GDPrintGammaTable(FILE *o,GDHandle device);
  78.  
  79. OSErr GDRestoreDeviceClut(GDHandle device);
  80. Nominally equivalent to Apple's RestoreDeviceClut(), which is only available
  81. since System 6.05. However, I find that Apple's routine sometimes does nothing,
  82. whereas this routine always works. Passing a NULL argument causes restoration of
  83. cluts of all video devices.
  84.  
  85. OSErr GDSaveGamma(GDHandle device);
  86. OSErr GDRestoreGamma(GDHandle device);
  87. Use an internal cache to save and restore the device's gamma-correction table. Call
  88. GDRestoreGamma before GDRestoreDeviceClut.
  89.  
  90. OSErr GDSetEntries(GDHandle device,short start,short count,ColorSpec *table);
  91. Does a cscSetEntries call to the video card's driver, loading any
  92. number of clut entries with arbitrary rgb triplets. (Note that the driver will
  93. transform your rgb triplets via the gamma table before loading them into the
  94. clut; so call GDUncorrectedGamma first.) "device" specifies which video device's
  95. clut you want to load. "start" is either in the range 0 to clutSize-1,
  96. indicating which clut entry to load first (in "sequence mode"), or is -1
  97. (requesting "index mode"). "count" is the number of entries to be modified,
  98. minus 1. "table" is a ColorSpec array (not a ColorTable) containing the rgb
  99. triplets that you want to load into the clut. In sequence mode "start" must be
  100. in the range 0 to clutSize-1, the i-th element of table corresponds to the
  101. i+start entry in the clut, and the "value" field of each element of table is
  102. ignored. In index mode "start" must be -1, and the "value" field of each element
  103. of table indicates which clut entry to load it into. The arguments start, count,
  104. and table are the same as for the Color Manager call SetEntries(), documented in
  105. Inside Macintosh V-143. (Most drivers wait for blanking before modifying the
  106. clut. For a full discussion, read the VideoToolbox "Video synch" file.) You may
  107. also want to look at the file SetEntriesQuickly.c, which provides the
  108. functionality of GDSetEntries and GDDirectSetEntries, but bypasses the video
  109. driver to access the hardware directly.
  110.  
  111. OSErr GDSetEntriesByType(GDHandle device,short start,short count,ColorSpec *table);
  112. Checks the (**device).gdType field and calls cscSetEntries, cscDirectSetEntries,
  113. or nothing, as appropriate.
  114.  
  115. OSErr GDSetEntriesByTypeHighPriority(GDHandle device,short start,short count
  116.     ,ColorSpec *table);
  117. Calls GDSetEntriesByType() while the processor priority has been temporarily 
  118. raised to 7.
  119.  
  120. OSErr GDSetGamma(GDHandle device, GammaTbl *gamma);
  121. Calls cscSetGamma. Loads a Gamma table into the specified video device. The
  122. video driver will make a copy of your table. You can discard your table after
  123. making this call. Note that the video driver only uses the gamma table when
  124. performing SetEntries, i.e. when actually loading the clut. The structure of the
  125. gamma table is (finally!) documented in Designing Cards and Drivers, 3rd
  126. edition, pages 215-216. Beware of a discrepancy between the documentation and
  127. the definition in QuickDraw.h: gFormulaData is described as a byte array in the
  128. text, but is declared as a short array in the QuickDraw.h header file. NOTE: a
  129. few video drivers (Radius PowerView and SuperMac ColorCard) do not support gamma
  130. tables. The SuperMac ColorCard is well behaved, giving the appropriate error
  131. code, returned by GDSetGamma and GDGetGamma. The Radius PowerView reports no
  132. error yet ignores the GDSetGamma call and returns a table full of zeroes in
  133. response to GDGetGamma. See NOTE from Tom Busey below. However, if all you want
  134. to do is call GDUncorrectedGamma, then these limitations won't affect you,
  135. because the drivers that lack gamma tables always give you precisely the
  136. behaviour that one requests by calling GDUncorrectedGamma.
  137.  
  138. OSErr GDSetPageDrawn(GDHandle device,short page);
  139. Choose which page of video memory will be used by future drawing operations. 
  140. Untested.
  141.  
  142. OSErr GDSetPageShown(GDHandle device,short page);
  143. Choose which page of video memory we see. Untested.
  144.  
  145. OSErr GDUncorrectedGamma(GDHandle device);
  146. Asks GDSetGamma to load a linear gamma table, i.e. no correction. (The gamma
  147. correction implemented by table-lookup in the video driver is too crude for
  148. experiments that want accurate luminance control.)
  149.  
  150. int GDVersion(GDHandle device)
  151. Returns the version number of the driver. From the first word-aligned word after
  152. the name string. This is quick.
  153.  
  154. LESS-USEFUL (LOW LEVEL) ROUTINES:
  155.  
  156. OSErr GDControl(int refNum,int csCode,Ptr csParamPtr)
  157. Uses low-level PBControl() call to implement a "Control()" call that works! 
  158. I don't know why this wasn't discussed in Apple Tech Note 262.
  159.  
  160. OSErr GDDirectSetEntries(GDHandle device,short start,short count,ColorSpec *table);
  161. Calls cscDirectSetEntries. If your pixel depth is >8 then the setEntries call is
  162. disabled, and you must use this instead of GDSetEntries().
  163.  
  164. VideoDriver *GDDriverAddress(GDHandle device);
  165. Returns a pointer to the driver, whether in ROM or RAM. Neither this prototype
  166. nor the definition of the VideoDriver structure are included in VideoToolbox.h.
  167.  
  168. OSErr GDGetDefaultMode(GDHandle device,short *modePtr)
  169. Calls cscGetDefaultMode. It tells you what the default mode is. I'm not sure
  170. what this means.
  171.  
  172. OSErr GDGetGray(GDHandle device,Boolean *flagPtr);
  173. Calls cscGetGray. Get gray flag. 0 for color. 1 if all colors mapped to
  174. luminance-equivalent gray tones.
  175.  
  176. OSErr GDGetInterrupt(GDHandle device,Boolean *flagPtr);
  177. Calls cscGetInterrupt. Get flag. 1 if VBL interrupts of this card are enabled. 0
  178. if disabled.
  179.  
  180. OSErr GDGetMode(GDHandle device,short *modePtr,short *pagePtr,Ptr *baseAddrPtr);
  181. Calls cscGetMode. It tells you the current mode, page of video memory, and the
  182. base address of that page.
  183.  
  184. OSErr GDGetPageBase(GDHandle device,short page,Ptr *baseAddrPtr);
  185. Calls cscGetPageBase. (Called "cscGetBaseAddr" in Designing Cards and Drivers, 3rd
  186. Ed.) You tell it which page of video memory you're interested in (in the current
  187. video mode). It tells you the base address of that page.
  188.  
  189. OSErr GDGrayPage(GDHandle device,short page);
  190. Calls cscGrayPage. (Called "cscGrayScreen" in Designing Cards and Drivers, 3rd
  191. Ed.) Fills the specified page with gray, i.e. the dithered desktop pattern. I'm
  192. not aware of any particular advantage in using this instead of FillRect().
  193. Designing Cards and Drivers, 3rd Edition, Chapter 9, says that for direct
  194. devices, i.e. >8 bit pixels, the driver will also load a linear,
  195. gamma-corrected, gray color table.
  196.  
  197. OSErr GDReset(GDHandle device, short *modePtr, short *pagePtr, Ptr *baseAddrPtr);
  198. Calls cscReset. Initialize the video card to its startup state, usually 1 bit
  199. per pixel. Returns the parameters of that state.
  200.  
  201. OSErr GDSetDefaultMode(GDHandle device,short mode);
  202. Calls cscSetDefault. Supposedly, you tell it what mode you want to start up with
  203. when you reboot. (I've never been able to get this to work. No error and no
  204. effect. Perhaps I've misunderstood its purpose.)
  205.  
  206. OSErr GDSetGray(GDHandle device,Boolean flag);
  207. Calls cscSetGray. Set gray flag. 0 for color. 1 if all colors mapped to
  208. luminance-equivalent gray tones.
  209.  
  210. OSErr GDSetInterrupt(GDHandle device,Boolean flag);
  211. Calls cscSetInterrupt. Set flag to 1 to enable VBL interrupts of this card, or 0
  212. to disable.
  213.  
  214. OSErr GDSetMode(GDHandle device,short mode,short page,Ptr *baseAddrPtr);
  215. Calls cscSetMode. You tell it what mode and video page you want. It sets 'em and
  216. returns the base address of that page in video memory. Also, because Apple said
  217. so, the video driver sets the entire clut to 50% gray. Note that this changes
  218. things behind QuickDraw's back. For most applications life will be simpler if
  219. you overtly ask QuickDraw to take charge by calling Apple's SetDepth() instead
  220. of GDSetMode(). WARNING: Apple now considers the mode numbers merely ordinal.
  221. E.g. on the 8•24 video card the 32-bit mode has mode number 0x84, not 0x85 as
  222. you might have expected on the basis of old Apple documentation and other Apple
  223. video cards.
  224.  
  225. OSErr GDStatus(int refNum,int csCode,Ptr csParamPtr)
  226. Uses low-level PBStatus() call to implement a "Status()" call that works! The
  227. need for this is explained in Apple Tech Note 262, which was issued in response
  228. to my bug report in summer of '89.
  229.  
  230. PatchMacIIciVideoDriver();
  231. Fixes a bug in the Mac IIci built-in video driver that would crash GDGetEntries.
  232. The patch persists until reboot. It is unlikely that you will need to call this
  233. explicitly, PatchMacIIciVideoDriver() is automatically invoked the first time
  234. GDGetEntries is called. The Mac IIci built-in video driver
  235. (.Display_Video_Apple_RBV1 driver, version 0) has a bug that causes it to crash
  236. if you try to do a GetEntries Status request. PatchMacIIciVideoDriver() finds
  237. and patches the copy of the buggy driver residing in memory. (If the driver is
  238. ROM-based it first moves it to RAM, and then patches that.) Only two
  239. instructions are modified, to save & restore more registers. This fix persists
  240. only until the next reboot. If the patch is successfully applied the version
  241. number is increased by 100.
  242.  
  243. NOTES:
  244.  
  245. Several bugs in version 2 (in System ≤6.03) of the video driver for Apple's
  246. "Toby Frame Buffer" video card that affected use of the GetGamma call were
  247. fixed in version 3 (in System 6.04), apparently in response to my bug report to
  248. Apple.
  249.  
  250. The control/status-call parameter in a GDControl or GDStatus call specifies what
  251. you want done. See Designing Cards and Drivers, 3rd Edition, Chapter 9. (A few
  252. new calls are documented in the Display Device Driver Guide Developer Note.)
  253.  Note that sometime around 1990 Apple renamed some of the Control and Status
  254. calls, giving them names that better reflect their function. I followed suit.
  255. However, Apple neglected to update their book, Designing Cards and Drivers, now
  256. in its 3rd edition. Fortunately, they define both names in their Video.h header
  257. file. To avoid confusion, here are the equivalences. Note that "csc" stands for
  258. "Control and Status Call"
  259. Control call:
  260.  cscGrayPage =  cscGrayScreen = 5
  261. Status calls:
  262.  cscGetPageCnt = cscGetPages = 4
  263.  cscGetPageBase = cscGetBaseAddr = 5
  264.  
  265. Based on:
  266. Inside Macintosh-II (Device Manager)
  267. Designing Cards and Drivers, 3rd Edition, Chapter 9.
  268. Display Device Driver Guide Developer Note on the January '94 Developer CD.
  269. Tech Note 262: "Controlling Status Calls"
  270. "GreyScale Information" from AppleLink "Apple Technical Info"
  271. "Video Configuration ROM Software Specification" also from AppleLink,
  272. in "Developer Tech Support:Macintosh:32 Bit QuickDraw"
  273.  
  274. NOTES:
  275. Tom Busey (busey@indiana.edu) writes: "I'm using an 8-bit SuperMac ColorCard
  276. that a used computer dealer gave me when I ordered a Toby card. I discovered
  277. that the status and control calls for GDUncorrectedGamma return -17 and -18
  278. respectively, which means that the driver doesn't support different gammas.
  279. GDUncorrectedGamma returns an error message, but GDOpenWindow doesn't use the
  280. error message or pass it back to the calling program. I'm wondering if there are
  281. people using GDOpenWindow who think that they are getting a linear gamma but who
  282. are actually getting an error message and not learning about it."
  283.      Tom's facts are right, but he needn't worry. A few video drivers, e.g.
  284. Radius PowerView, and apparently the SuperMac ColorCard, don't implement gamma
  285. tables at all, but the error from GDUncorrectedGamma is probably not a concern.
  286. The real test is to run TimeVideo. TimeVideo does a write-and-read-back test of
  287. the clut of your video card. If that test passes then you can safely conclude
  288. that there's no gamma translation going on. So, as nearly every document in the
  289. VideoToolbox says: run TimeVideo and read the report.
  290.      Here's how gamma tables work. According to the Apple manual (Designing
  291. Cards and Drivers), the values in the rgb triplets that you supply in a
  292. cscSetEntries call to the video driver are first translated via the gamma table
  293. (each r,g, and b component separately) before being loaded into the CLUT
  294. hardware table. Most drivers maintain a gamma table internally (in computer
  295. memory) and allow you to get and set it via the cscGetGamma and cscSetGamma
  296. calls. A few video drivers (Radius PowerView, SuperMac ColorCard) don't support
  297. gamma tables. They load your rgb values directly into the CLUT, without
  298. translation. However, for users of the VideoToolbox that's usually fine, since
  299. that's exactly the behavior that we routinely request by calling
  300. GDUncorrectedGamma. Of course, if you want to load a custom gamma table, other
  301. than the identity transformation, then you'll be calling GDSetGamma, and you
  302. should make sure it does not return an error. (Alas, the Radius PowerView driver
  303. more or less ignores the cscSetGamma and cscGetGamma requests--GDGetGamma
  304. returns a table that's all zeroes--but the driver fails to report an error. I
  305. wrote to the Radius programmer a year ago, but they're no longer interested in
  306. working on that product.)
  307.     Patrick Flanagan (flanagan@deakin.edu.au) writes: "Can I be 100% sure, if I
  308. select "Special Gamma", in the Monitors Control Panel and choose "uncorrected
  309. gamma" for a video card, that this is the same as using GDUncorrectedGamma?"
  310. REPLY: That is what I would expect from reading all the relevant documentation.
  311. However, to be 100% certain of anything I would want to check it myself.
  312. TimeVideo calls GDUncorrectedGamma and then confirms that write-then-read tests
  313. of the CLUT return what was written. (Gamma-table translation is only done on
  314. the write, not undone on the read.) Thus TimeVideo will confirm for you that
  315. after calling GDUncorrectedGamma your video card has what Apple calls an
  316. "uncorrected" gamma table. However, TimeVideo does not check what you would get
  317. by merely selecting "uncorrected" gamma in the Monitors Control Panel. It would
  318. be reasonable to assume that you would get the same result since Monitors
  319. interacts with the video driver by the same Control and Status Calls as
  320. GDVideo.c does, so it must use the same cscSetGamma call as is used by
  321. GDUncorrectedGamma.
  322.  
  323. HISTORY:
  324. 9/29/89     dgp    added caution above that successive calls to SetEntries may be on one 
  325.                 frame.
  326. 11/21/89    dgp    corrected mode list: 0x80... as pointed out by Chuck Stein
  327. 11/30/89    dgp    added note above from Don Kelly.
  328.                 Added cautionary note above about GDSetEntries().
  329. 3/1/90        dgp    updated comments.
  330. 3/3/90        dgp    included Video.h instead of defining VDSetEntryRecord and VDPageInfo.
  331. 3/20/90        dgp    made compatible with MPW C.
  332. 3/23/90        dgp    changed char to unsigned char in VDDefModeRec
  333.                 and VDFlagRec to prevent undesirable sign extension.
  334. 4/2/90        dgp    Deleted mode argument from GDGrayScreen().
  335. 7/28/90        dgp Fixed stack overflow in GDGrayScreen, by declaring SysEnvRec static.
  336. 10/20/90    dgp    Apple has renamed the control and status calls, so I followed suit:
  337.                 •GDGetPageBase replaces GDGetBaseAddr
  338.                 •GDReset replaces GDInit
  339.                 •GDGrayPage replace GDGrayScreen
  340.                 •GDGetPageCnt replaces GDGetPages
  341. 2/12/91        dgp Discovered that the old bug in GDGrayPage is still present in System
  342.                 6.05, so I removed the conditional around the bug fix. TestGDVideo
  343.                 now works with: Mac II Video Card, Mac II Display Card (4•8), 
  344.                 Mac IIci Built-in Video, TrueVision NuVista, Mac IIsi Built-in Video.
  345. 7/22/91        dgp    Changed definition of csGTable from GammaTblPtr to Ptr, 
  346.                 to conform with MPW C.
  347. 8/24/91        dgp    Made compatible with THINK C 5.0.
  348. 10/22/91    dgp    With help from Bart Farell, converted all functions headers to
  349.                 Standard C style.
  350. 8/26/92        dgp    added a few miscellaneous comments
  351.                 In all routines, *baseAddrPtr is now set only if baseAddrPtr is not NULL.
  352. 10/10/92    dgp    Added GDRestoreDeviceClut(). Removed obsolete support for THINK C 4.
  353. 11/30/92    dgp corrected error in comment documenting values of argument to GDSetGray().
  354.                 Set flag to zero for color,1 for luminance-mapped gray.
  355. 12/9/92        dgp    Enhanced GDRestoreDeviceClut(). Passing a NULL argument now requests
  356.                 application to all devices. I only just learned that Apple's
  357.                 RestoreDeviceClut() behaves in this way.
  358. 12/15/92    dgp Renamed GDRestoreDeviceClut to GDRestoreDeviceClut to be consistent
  359.                 with Apple's capitalization of RestoreDeviceClut.
  360. 12/16/92    dgp Updated comments to be consistent with 3rd edition of Designing Cards
  361.                 and Drivers. •Renamed myGDHandle to "device", which is easier to read.
  362.                 Renamed GDLinearGamma to GDUncorrectedGamma, and generalized it
  363.                 to work with any size DAC. For compatibility with old programs
  364.                 VideoToolbox.h now has a #define statement making GDLinearGamma
  365.                 an alias for GDUncorrectedGamma.
  366. 12/30/92    dgp Updated some of the comments. Eliminated Files.h.
  367. 12/30/92    dgp Use GDClutSize() to determine clut size.
  368. 1/4/93        dgp In GDClutSize, check for fixedType.
  369. 1/5/93        dgp In GDClutSize, only set last clut entry.
  370.                 Added PatchMacIIciVideoDriver() to the end of this file, and 
  371.                 automatically invoke it the first time GDGetEntries is called.
  372. 1/6/93        dgp    Cleaned up GDClutSize. It now seems to work correctly in the direct modes.
  373. 1/18/93    dgp    Spruced up the documentation.
  374.             •Added all the code formerly in GDIdentify.c, but omitted the obsolete 
  375.             function GDIdentify(), which simply printed GDName() and GDVersion.
  376.             •Enhanced GDGetEntries() to avoid calling drivers that are known
  377.             to crash, returning a statusErr instead.
  378.             •Recoded PatchMacIIciVideoDriver() so as not to call GetScreenDevice.c.
  379. 2/1/93    dgp    Fixed endless loop in PatchMacIIciVideoDriver. Enhanced to deal with
  380.             ROM-based drivers as well.
  381. 2/5/93    dgp    Expanded the documentation of GDSetEntries above, and supplied sample
  382.             code showing how to load the clut.
  383. 2/7/93    dgp Fixed endless loop in PatchMacIIciVideoDriver.
  384. 2/20/93    dgp    Fixed bug in GDUncorrectedGamma() that was causing TestCluts to fail
  385.             for video devices that have nonstandard gamma tables. 
  386. 3/18/93    dgp    Fixed divide by zero error in GDClutSize.
  387. 4/6/93    dgp    GDGetPageCnt() now sets *pagePtr argument only if no error occurs.
  388.             Deleted GDModeName(). Removed assumption, in all routines, that there
  389.             is any particular correspondence between the video mode number and
  390.             the pixel size. Added two new routines, GDPixelSize and GDType,
  391.             that return the pixelSize and gdType (i.e. fixedType, clutType, or 
  392.             directType) of the device. Completely rewrote GDClutSize.
  393. 4/16/93    dgp    Streamlined GDClutSize() to make it fast enough for routine use.
  394. 4/19/93    dgp    Added GDNewLinearColorTable.
  395. 4/25/93    dgp    Made CntrlParam automatic instead of static.
  396. 4/25/93    dgp    Added GDColors(device) and GDPrintGammaTable(). Alphabetized the lists
  397.             of functions in the documentation above.
  398. 5/11/93    dgp    Changed GDPrintGammaTable() to accept a simple file pointer instead of
  399.             an array of two file pointers.
  400. 7/7/93    dgp enhanced GDDacSize() to return 8 unless the gamma table is present and
  401.             reasonable.
  402. 7/29/94    dgp    added GDNameStr().
  403. 9/5/94 dgp removed assumption in printf's that int==short.
  404. 10/25/94 dgp check for missing driver, (*device)->gdRefNum==0, and treat that case
  405.             just like  device==NULL. Devices created by NewGWorld have no driver.
  406. 12/29/94 dgp added GDGetDisplayMode(), calls cscGetCurMode, based on Apple's new
  407.             Display Device Driver Guide Developer Note on the January '94 Developer CD.
  408. */
  409.  
  410. #include "VideoToolbox.h"
  411. #include <assert.h>
  412. #include <ROMDefs.h>
  413. //#include <Displays.h>
  414. #define dRAMBased 0x0040
  415.  
  416. #if !UNIVERSAL_HEADERS
  417.     /* these declarations appear in the latest Video.h */
  418.     struct VDSwitchInfoRec{
  419.         unsigned short csMode;
  420.         unsigned long csData;
  421.         unsigned short csPage;
  422.         Ptr csBaseAddr;
  423.         unsigned long csReserved;
  424.     };
  425.     typedef struct VDSwitchInfoRec VDSwitchInfoRec;
  426.     enum{cscGetCurMode=10};
  427. #endif
  428.  
  429. typedef struct VDFlagRec {
  430.     unsigned char flag;
  431.     char pad;
  432. } VDFlagRec;
  433.  
  434. typedef struct VDDefModeRec{
  435.     unsigned char spID;
  436.     char pad;
  437. } VDDefModeRec;
  438.  
  439. typedef struct {
  440.     short flags;
  441.     short blanks[3];
  442.     short open;
  443.     short prime;
  444.     short control;
  445.     short status;
  446.     short close;
  447.     Str255 name;
  448. } VideoDriver;
  449. VideoDriver *GDDriverAddress(GDHandle device);
  450.  
  451. typedef struct {
  452.     short csCode;        // control code
  453.     short length;        // total parameter block bytes
  454.     char param[];        // control call data
  455. } ScrnCtl;
  456.  
  457. typedef struct {
  458.     short spDrvrHw;        // Slot Manager ID
  459.     short slot;            // Number of slot
  460.     long dCtlDevBase;    // Start of device's address space
  461.     short mode;            // screen characteristics
  462.     short flagMask;        // Which flag bits are used
  463.     short flags;        // device state: bit 0 = 0 = mono; bit 0 = 1 = color;
  464.                         // bit 11 =  1 = startup device; bit 15 = 1 = active
  465.     short colorTable;    // 'clut' id, default = -1
  466.     short gammaTable;    // Selects color intensity, default (MacII) = -1
  467.     Rect globalRect;    // global rectangle, main device topLeft = 0,0
  468.     short ctlCount;        // total control calls
  469.     ScrnCtl ctl;
  470. } Scrn;
  471.  
  472. typedef struct {
  473.     short scrnCount;    // Total devices
  474.     Scrn scrn;
  475. } Scrns;                // 'scrn' resource
  476.  
  477. Scrn **GDGetScrn(GDHandle device);
  478.  
  479. OSErr GDGetDisplayMode(GDHandle device,unsigned short *displayModePtr,unsigned long *spIDPtr
  480.     ,unsigned short *pagePtr,Ptr *baseAddrPtr)
  481. /*
  482. It tells you the current display mode, etc., but only if the video driver 
  483. supports the Display Manager.
  484. */
  485. {
  486.     VDSwitchInfoRec vdSwitchInfo;
  487.     int error;
  488.  
  489.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  490.     error=GDStatus((*device)->gdRefNum,cscGetCurMode,(Ptr) &vdSwitchInfo);
  491.     if(displayModePtr!=NULL) *displayModePtr=vdSwitchInfo.csMode;
  492.     if(spIDPtr!=NULL) *spIDPtr=vdSwitchInfo.csData;
  493.     if(pagePtr!=NULL) *pagePtr=vdSwitchInfo.csPage;
  494.     if(baseAddrPtr!=NULL) *baseAddrPtr=vdSwitchInfo.csBaseAddr;
  495.     return error;
  496. }
  497.  
  498. OSErr GDSetPageDrawn(GDHandle device,short page)
  499. // Select a page of video memory to draw into.
  500. // Untested.
  501. {
  502.     int error;
  503.     short flags;
  504.     Ptr baseAddr;
  505.     static long qD=-1;
  506.  
  507.     if(qD==-1)Gestalt(gestaltQuickdrawVersion,&qD);
  508.     error=GDGetPageBase(device,page,&baseAddr);
  509.     if(!error){
  510.         if(qD>=gestalt32BitQD){
  511.             flags=GetPixelsState((**device).gdPMap);
  512.             LockPixels((**device).gdPMap);
  513.         }
  514.         (**(**device).gdPMap).baseAddr=baseAddr;
  515.         if(qD>=gestalt32BitQD){
  516.             GDeviceChanged(device);
  517.             SetPixelsState((**device).gdPMap,flags);
  518.         }
  519.     }
  520.     return error;
  521. }
  522.  
  523. OSErr GDSetPageShown(GDHandle device,short page)
  524. // Select a page of video memory for display.
  525. // Untested.
  526. {
  527.     int error;
  528.     short mode;
  529.  
  530.     error=GDGetMode(device,&mode,NULL,NULL);
  531.     if(error)return error;
  532.     return GDSetMode(device,mode,page,NULL);
  533. }
  534.  
  535. short GDType(GDHandle device)
  536. // Returns what would normally be in (**device).gdType, for occasions when
  537. // the GDevice record might be invalid because you called GDSetMode().
  538. {
  539.     int error;
  540.     static ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  541.  
  542.     error=GDSetEntries(device,0,0,&white);
  543.     if(!error)return clutType;
  544.     error=GDDirectSetEntries(device,0,0,&black);
  545.     if(!error)return directType;
  546.     return fixedType;
  547. }
  548.  
  549. short GDPixelSize(GDHandle device)
  550. // Returns what would normally be in (**(**device).gdPMap).pixelSize, for occasions
  551. // when the GDevice record might be invalid because you called GDSetMode().
  552. {
  553.     int error;
  554.     short mode;
  555.  
  556.     error=GDGetMode(device,&mode,NULL,NULL);
  557.     return GDModePixelSize(device,mode);
  558. }
  559.  
  560. short GDModePixelSize(GDHandle device,short mode)
  561. // Returns the pixelSize associated with a given video mode.
  562. // If you've changed the mode by calling GDSetMode and you're running a System 
  563. // older than 6.0.5 the answer may may be wrong for some of the newer video cards,
  564. // because they have ideosynchratic associations of video mode and pixel size.
  565. {
  566.     short j;
  567.     long version;
  568.  
  569.     if(mode==(**device).gdMode)return (**(**device).gdPMap).pixelSize;
  570.     Gestalt(gestaltSystemVersion,&version);
  571.     if(version>=0x605){            // Need new Palette Manager for reliable answer.
  572.         for(j=5;j>=0;j--)if(mode==HasDepth(device,1<<j,0,0))return 1<<j;
  573.     } else return 1<<(mode&7);    // Unreliable.
  574.     return 0;
  575. }
  576.  
  577. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr);
  578.  
  579. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr)
  580. // Returns 0 if no such mode, returns 1 if mode is available.
  581. // If pixelSizePtr is not NULL, then sets *pixelSizePtr to pixelSize or -1 if unknown.
  582. // If pagesPtr is not NULL, then sets *pagesPtr to pages.
  583. {
  584.     short pixelSize,i,hasDepthWorks,pages;
  585.     int error;
  586.     long system;
  587.     
  588.     Gestalt(gestaltSystemVersion,&system);
  589.     // On Mac IIci, Sys 6.07, HasDepth returns "mode" of 0x100 at all legal depths.
  590.     hasDepthWorks= system>=0x605     // New Palette Manager.
  591.         && HasDepth(device,(**(**device).gdPMap).pixelSize,0,0)==(**device).gdMode;
  592.     if(hasDepthWorks){
  593.         for(i=0;i<6;i++){
  594.             pixelSize=1<<i;
  595.             if(mode!=HasDepth(device,pixelSize,0,0))continue;
  596.             if(pixelSizePtr!=NULL)*pixelSizePtr=pixelSize;
  597.             if(pagesPtr!=NULL){
  598.                 error=GDGetPageCnt(device,mode,&pages);
  599.                 if(error)pages=1;
  600.                 *pagesPtr=pages;
  601.             }
  602.             return 1;
  603.         }
  604.         return 0;
  605.     }else{
  606.         // If HasDepth doesn't work properly then we can still find out whether the
  607.         // mode is available by asking the video driver for a page count, but
  608.         // I don't know of any discreet way to find out the pixelSize.
  609.         // Calling SetDepth would work, but that would irritate the user who has to
  610.         // watch and wait. 
  611.         error=GDGetPageCnt(device,mode,&pages);
  612.         if(error)pages=0;
  613.         if(pagesPtr!=NULL)*pagesPtr=pages;
  614.         if(mode==(**device).gdMode)pixelSize=(**(**device).gdPMap).pixelSize;
  615.         else pixelSize=-1;        // Unknown.
  616.         if(pixelSizePtr!=NULL)*pixelSizePtr=pixelSize;
  617.         return (pages>0);
  618.     }
  619. }
  620.  
  621. short gdClutSizeTable[33]={0,1<<1,1<<2,0,1<<4,0,0,0,1<<8,0,0,0,0,0,0,0,1<<5
  622. ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1<<8};
  623.  
  624. long GDColors(GDHandle device)
  625. // Returns the number of colors, in the current mode.
  626. {
  627.     long colors=0;
  628.     short pixelSize;
  629.     
  630.     if(device==NULL)return 2;    // for compatibility with 1-bit QuickDraw
  631.     pixelSize=(**(**device).gdPMap).pixelSize;
  632.     if(pixelSize>=1 && pixelSize<=8)colors=1<<pixelSize;
  633.     if(pixelSize==16)colors=1L<<15;
  634.     if(pixelSize==32)colors=1L<<24;
  635.     return colors;
  636. }
  637.  
  638. short GDClutSize(GDHandle device)
  639. // Returns the number of entries in the clut, in the current mode.
  640. {
  641.     short clutSize;
  642.     
  643.     // Method 1. Estimate clut size from pixel size.
  644.     clutSize=gdClutSizeTable[(**(**device).gdPMap).pixelSize];
  645.  
  646.     #if 0
  647.     // Method 2. Measure the clut's size by trying to load it.
  648.     if(GDType(device)==directType){
  649.         int error,i;
  650.         static const ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  651.         ColorSpec *table;
  652.         for(clutSize=256;clutSize>1;clutSize>>=1){
  653.             table=GDNewLinearColorTable(device);
  654.             if(table==NULL)PrintfExit("GDClutSize: out of memory.\n");
  655.             error=GDDirectSetEntries(device,0,clutSize-1,table);
  656.             DisposePtr((Ptr)table);
  657.             if(!error)break;
  658.         }
  659.     }
  660.     #endif
  661.     
  662.     return clutSize;
  663. }
  664.  
  665. short GDDacSize(GDHandle device)
  666. // Figures out how many bits in the video dac. Answers for each device are cached.
  667. {
  668.     short dacSize,i;
  669.     static short dacSizeCache[MAX_SCREENS];
  670.     static GDHandle deviceCache[MAX_SCREENS];
  671.     int error;
  672.     GammaTbl *gammaTblPtr=NULL;
  673.  
  674.     for(i=0;i<MAX_SCREENS;i++)if(device==deviceCache[i])return dacSizeCache[i];
  675.     error=GDGetGamma(device,&gammaTblPtr);        // Takes 200 µs.
  676.     if(error || gammaTblPtr==NULL || gammaTblPtr->gDataWidth==0)dacSize=8;                            // Oops. Take a guess.
  677.     else dacSize=gammaTblPtr->gDataWidth;
  678.     for(i=0;i<MAX_SCREENS;i++)if(NULL==deviceCache[i]){
  679.         deviceCache[i]=device;
  680.         dacSizeCache[i]=dacSize;
  681.         break;
  682.     }
  683.     return dacSize;
  684. }
  685.  
  686. ColorSpec *GDNewLinearColorTable(GDHandle device)
  687. // Creates a default table for use when gdType==directType.
  688. {
  689.     short clutSize,i;
  690.     ColorSpec *table,*linearTable;
  691.     
  692.     clutSize=GDClutSize(device);
  693.     table=linearTable=(ColorSpec *)NewPtr(clutSize*sizeof(linearTable[0]));
  694.     if(linearTable!=NULL)for(i=0;i<clutSize;i++){
  695.         table->rgb.red=table->rgb.green=table->rgb.blue
  696.             =(0xffffL*i+clutSize/2)/(clutSize-1);
  697.         table++;
  698.     }
  699.     return linearTable;
  700. }
  701.  
  702. /*
  703. Nominally equivalent to Apple's RestoreDeviceClut(), which is only available
  704. since System 6.05. However, I find that Apple's routine sometimes does nothing,
  705. whereas this routine always works. Passing a NULL argument causes restoration of
  706. cluts of all video devices.
  707. */
  708. OSErr GDRestoreDeviceClut(GDHandle device)
  709. {
  710.     int error,lastError;
  711.     short count;
  712.  
  713.     // If NULL, then recursively call ourselves for each device.
  714.     if(device==NULL){
  715.         lastError=0;
  716.         device=GetDeviceList();
  717.         while(device!=NULL) {
  718.             if(TestDeviceAttribute(device,screenDevice))
  719.                 error=GDRestoreDeviceClut(device);
  720.             if(error)lastError=error;
  721.             device=GetNextDevice(device);
  722.         }
  723.         return lastError;
  724.     }
  725.     if(GDType(device)!=directType){
  726.         count=(**(**(**device).gdPMap).pmTable).ctSize;
  727.         error=GDSetEntries(device,0,count
  728.             ,((**(**(**device).gdPMap).pmTable)).ctTable);
  729.     } else error=GDSetGamma(device,NULL);
  730.     return error;
  731. }
  732.  
  733. GammaTbl **savedGammaTable[MAX_SCREENS];
  734.  
  735. OSErr GDSaveGamma(GDHandle device)
  736. {
  737.     GammaTbl *gamma;
  738.     int error;
  739.     long size;
  740.     int i;
  741.  
  742.     if(device==NULL || (*device)->gdType==fixedType)return 0;
  743.     i=GetScreenIndex(device);
  744.     if(i>=MAX_SCREENS)return 1;
  745.      error=GDGetGamma(device,&gamma);
  746.     if(error)return error;
  747.     size=gamma->gChanCnt*gamma->gDataCnt;
  748.     if(gamma->gDataWidth>8)size*=2;
  749.     size+=sizeof(GammaTbl)+gamma->gFormulaSize;
  750.     if(savedGammaTable[i]!=NULL){
  751.         DisposeHandle((Handle)savedGammaTable[i]);
  752.         savedGammaTable[i]=NULL;
  753.     }
  754.     error=PtrToHand(gamma,(Handle *)&savedGammaTable[i],size);
  755.     return error;
  756. }
  757.  
  758. OSErr GDRestoreGamma(GDHandle device)
  759. {
  760.     int i,error;
  761.     
  762.     if((*device)->gdType==fixedType)return 0;
  763.     i=GetScreenIndex(device);
  764.     if(i>=MAX_SCREENS || savedGammaTable[i]==NULL)return 1;
  765.     error=GDSetGamma(device,*savedGammaTable[i]);
  766.     if(error)return error;
  767.     DisposeHandle((Handle)savedGammaTable[i]);
  768.     savedGammaTable[i]=NULL;
  769.     return 0;
  770. }    
  771.  
  772. OSErr GDGetDefaultGamma(GDHandle device,GammaTbl **gammaTbl)
  773. // Looks for a default gamma table in both places that Apple says to look,
  774. // but usually comes up empty handed.
  775. {
  776.     int error,i,slot;
  777.     Scrn **scrn;
  778.     GammaTbl **gammaHandle,*gamma;
  779.     SpBlock spBlock;
  780.     Ptr ptr;
  781.  
  782.     gammaHandle=NULL;
  783.     if(CountResources('gama')>0){// Any 'gama' resources available in System file?
  784.         // Check to see if 'scrn' resource in System file specifies a 'gama' resource.
  785.         scrn=GDGetScrn(device);
  786.         if(scrn!=NULL && (**scrn).gammaTable!=-1)
  787.             gammaHandle=(GammaTbl **)GetResource('gama',(**scrn).gammaTable);
  788.         DisposeHandle((Handle)scrn);
  789.     }
  790.     if(gammaHandle!=NULL){
  791.         // Got gamma table from 'gama' resource.
  792.         gamma=(GammaTbl *)NewPtr(GetHandleSize((Handle)gammaHandle));
  793.         if(gamma==NULL)return MemError();
  794.         BlockMove(*gammaHandle,gamma,GetHandleSize((Handle)gammaHandle));
  795.         DisposeHandle((Handle)gammaHandle);
  796.     }else{
  797.         // Try to get this device's default gamma table from Slot Manager.
  798.         spBlock.spSlot=slot=GetDeviceSlot(device);
  799.         spBlock.spID=0;
  800.         spBlock.spExtDev=0;
  801.         spBlock.spTBMask=3;            // match only spCategory and spCType
  802.         spBlock.spCategory=catDisplay;
  803.         spBlock.spCType=typeVideo;    // this might be too restrictive, excludes LCD
  804.         do{
  805.             error=SNextTypeSRsrc(&spBlock);
  806.             if(error)return error;
  807.         }while(spBlock.spSlot!=slot || spBlock.spRefNum!=(**device).gdRefNum);
  808.         
  809.         if(0){
  810.             // Print sResource name
  811.             spBlock.spID=sRsrcName;
  812.             error=SGetCString(&spBlock);
  813.             printf("Slot resource “%s”\n",spBlock.spResult);
  814.             if(error)return error;
  815.             DisposePtr((Ptr)spBlock.spResult);
  816.         }
  817.         
  818.         // Look for gamma directory. Unfortunately many video devices don't have one.
  819.         spBlock.spID=sGammaDir;
  820.         error=SFindStruct(&spBlock);
  821.         if(error)return error;
  822.         
  823.         // Retrieve default gamma table
  824.         spBlock.spID=0x80;
  825.         error=SGetBlock(&spBlock);
  826.         if(error)return error;
  827.         gamma=(GammaTbl *)spBlock.spResult;
  828.         ptr=(Ptr)spBlock.spResult+6;
  829.         if(0)printf("Gamma table “%s”, %ld bytes\n",ptr,GetPtrSize((Ptr)gamma));
  830.         ptr+=strlen(ptr)+1;                // table is just past string
  831.         ptr=(Ptr)((long)(ptr+1)&~1L);    // round up to even address
  832.         i=ptr-(Ptr)gamma;
  833.         BlockMove(ptr,(Ptr)gamma,GetPtrSize((Ptr)gamma)-i);
  834.         SetPtrSize((Ptr)gamma,GetPtrSize((Ptr)gamma)-i);
  835.     }
  836.     *gammaTbl=gamma;
  837.     return 0;
  838. }
  839.  
  840. Scrn **GDGetScrn(GDHandle device)
  841. // Returns handle to a copy of the specific scrn resource for this device,
  842. // or NULL if none.
  843. {
  844.     int error=0,i,j;
  845.     Scrns **scrns;
  846.     Scrn *scrn,**scrnHandle;
  847.     ScrnCtl *ctl;
  848.     int scrnCount;
  849.     long size;
  850.  
  851.     scrns=(Scrns **)GetResource('scrn',0);
  852.     if(ResError())return NULL;
  853.     HLockHi((Handle)scrns);
  854.     scrnCount=(**scrns).scrnCount;
  855.     scrn=&(**scrns).scrn;
  856.     for(i=0;i<scrnCount;i++){
  857.         if(0 && scrn->slot==GetDeviceSlot(device)){
  858.             printf("Slot %d,",(int)scrn->slot);
  859.             printf("mode %d,",(int)scrn->mode);
  860.             printf("colorTable %d,",(int)scrn->colorTable);
  861.             printf("gammaTable %d,",(int)scrn->gammaTable);
  862.             printf("%d control calls:",(int)scrn->ctlCount);
  863.         }
  864.         ctl=&scrn->ctl;
  865.         for(j=0;j<scrn->ctlCount;j++){
  866.             if(0 && scrn->slot==GetDeviceSlot(device))printf(" %d",(int)ctl->csCode);
  867.             ctl=(ScrnCtl *)((long)(ctl+1)+ctl->length);
  868.         }
  869.         if(0 && scrn->slot==GetDeviceSlot(device))printf("\n");
  870.         size=(long)ctl-(long)scrn;
  871.         if(scrn->slot==GetDeviceSlot(device))break;
  872.         scrn=(Scrn *)ctl;
  873.     }
  874.     if(i<scrnCount){
  875.         if(error)return NULL;
  876.         scrnHandle=(Scrn **)NewHandle(size);
  877.         BlockMove(scrn,*scrnHandle,size);
  878.     }else scrnHandle=NULL;
  879.     ReleaseResource((Handle)scrns);
  880.     return scrnHandle;
  881. }
  882.  
  883. OSErr GDUncorrectedGamma(GDHandle device)
  884. /*
  885. Loads a linear gamma table into the specified video device, to defeat the
  886. driver's attempt to do gamma correction.
  887.  
  888. According to Designing Cards and Drivers, 3rd edition, passing a NULL
  889. GammaTblPtr instructs the driver to create a linear table. So you may wish to
  890. just call GDSetGamma(device,NULL) instead of calling GDUncorrectedGamma(device).
  891. However, I'm not sure how old that rule is, and don't know if all the older
  892. drivers support it. Therefore the following code first examines the current
  893. gamma table, and, if it's a plain vanilla table, as described in Designing Cards
  894. and Drivers, then we write in the desired linear table. If it's fancy (or if the
  895. driver doesn't support GDGetGamma) then we pass a NULL pointer, letting the driver
  896. create the new table. Hopefully this will work with all drivers.
  897. */
  898. {
  899.     int error,i;
  900.     GammaTbl *gamma=NULL;
  901.     char *gData;
  902.  
  903.     error=GDGetGamma(device,&gamma);
  904.     if(!error && gamma->gVersion==0 && gamma->gChanCnt==1 && gamma->gDataWidth<=8){
  905.         // Overwrite the standard table
  906.         gData = (char *)&gamma->gFormulaData+gamma->gFormulaSize;
  907.         for(i=0;i<gamma->gDataCnt;i++)gData[i]=i;
  908.     }else{
  909.         // A fancy table implies a new driver, so let it do the work.
  910.         gamma=NULL;
  911.     }
  912.     error=GDSetGamma(device,gamma);
  913.     return error;
  914. }
  915.  
  916. /* KillIO doesn't do anything, so I didn't bother to implement it. */
  917.  
  918. OSErr GDPrintGammaTable(FILE *o,GDHandle device)
  919. {
  920.     unsigned char *byte;
  921.     unsigned short *word;
  922.     int error,i,j,identity;
  923.     GammaTbl *gamma;
  924.     
  925.     if((**device).gdType==fixedType)return statusErr;
  926.     error=GDGetGamma(device,&gamma);
  927.     if(error){
  928.         fprintf(o,"GetGamma: GDGetGamma() error %d\n",error);
  929.         if(error==statusErr)
  930.             fprintf(o,"The video driver doesn't support this call.\n");
  931.         return error;
  932.     }
  933.     byte=(unsigned char *)gamma->gFormulaData+gamma->gFormulaSize;
  934.     word=(unsigned short *)byte;
  935.     identity=1;
  936.     if(gamma->gDataWidth<=8)
  937.         for(i=0;i<gamma->gDataCnt;i++)identity &= (i==byte[i]);
  938.     else
  939.         for(i=0;i<gamma->gDataCnt;i++)identity &= (i==word[i]);
  940.     if(identity){
  941.         fprintf(o,"Gamma Table: identity transformation\n");
  942.     }else{
  943.         fprintf(o,"Gamma Table:\n");
  944.         fprintf(o,"at 0x%lx,gDataWidth %d,gDataCnt %d,gVersion %d,gType %d,gFormulaSize %d,gChanCnt %d\n"
  945.             ,gamma,(int)gamma->gDataWidth,(int)gamma->gDataCnt,(int)gamma->gVersion
  946.             ,(int)gamma->gType,(int)gamma->gFormulaSize,(int)gamma->gChanCnt);
  947.         for(i=0;i<gamma->gDataCnt;i+=64) {
  948.             fprintf(o,"%3d: ",i);
  949.             if(gamma->gDataWidth<=8)
  950.                 for(j=0;j<16;j++) fprintf(o," %3u",byte[i+j]);
  951.             else
  952.                 for(j=0;j<16;j++) fprintf(o," %3u",word[i+j]);
  953.             fprintf(o,"\n");
  954.         }
  955.     }
  956.     return 0;
  957. }
  958.  
  959. OSErr GDReset(GDHandle device, short *modePtr, short *pagePtr, Ptr *baseAddrPtr)
  960. /*
  961. Initialize the video card to its startup state, usually 1 bit per pixel. Returns
  962. the parameters of that state.
  963. */
  964. {
  965.     VDPageInfo myVDPageInfo;
  966.     int error;
  967.  
  968.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  969.     myVDPageInfo.csMode= *modePtr;
  970.     myVDPageInfo.csPage= *pagePtr;
  971.     error=GDControl((*device)->gdRefNum,cscReset,(Ptr) &myVDPageInfo);
  972.     *modePtr=myVDPageInfo.csMode;
  973.     *pagePtr=myVDPageInfo.csPage;
  974.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  975.     return error;
  976. }
  977.  
  978. OSErr GDSetMode(GDHandle device,short mode,short page,Ptr *baseAddrPtr)
  979. {
  980.     VDPageInfo myVDPageInfo;
  981.     int error;
  982.  
  983.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  984.     myVDPageInfo.csMode=mode;
  985.     myVDPageInfo.csPage=page;
  986.     error=GDControl((*device)->gdRefNum,cscSetMode,(Ptr) &myVDPageInfo);
  987.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  988.     return error;
  989. }
  990.  
  991. OSErr GDSetEntriesByType(GDHandle device,short start,short count,ColorSpec *table)
  992. // Calls GDSetEntries or GDDirectSetEntries or nothing, as appropriate.
  993. // Assumes that the GDevice record is valid, i.e. that the user has not
  994. // called GDSetMode.
  995. {
  996.     switch((*device)->gdType){
  997.     case fixedType:
  998.         return statusErr;
  999.     case clutType:
  1000.         return GDSetEntries(device,start,count,table);
  1001.     case directType:
  1002.         return GDDirectSetEntries(device,start,count,table);
  1003.     }
  1004.     return 1;
  1005. }
  1006.  
  1007. OSErr GDSetEntriesByTypeHighPriority(GDHandle device,short start,short count
  1008.     ,ColorSpec *table)
  1009. {
  1010.     char priority;
  1011.     int error;
  1012.  
  1013.     priority=7;
  1014.     SwapPriority(&priority);
  1015.     error=GDSetEntriesByType(device,start,count,table);
  1016.     SwapPriority(&priority);
  1017.     return error;
  1018. }
  1019.  
  1020. OSErr GDSetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1021. {
  1022.     VDSetEntryRecord vDSetEntryRecord;
  1023.     int error;
  1024.  
  1025.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1026.     vDSetEntryRecord.csStart=start;
  1027.     vDSetEntryRecord.csCount=count;
  1028.     vDSetEntryRecord.csTable=table;
  1029.     error=GDControl((*device)->gdRefNum,cscSetEntries,(Ptr) &vDSetEntryRecord);
  1030.     return error;
  1031. }
  1032.  
  1033. OSErr GDSetGamma(GDHandle device, GammaTbl *gamma)
  1034. {
  1035.     int error;
  1036.     VDGammaRecord myVDGammaRecord;
  1037.  
  1038.     myVDGammaRecord.csGTable=(Ptr)gamma;
  1039.     error=GDControl((*device)->gdRefNum,cscSetGamma,(Ptr) &myVDGammaRecord);
  1040.     return error;
  1041. }
  1042.  
  1043. OSErr GDGrayPage(GDHandle device,short page)
  1044. /*
  1045. Called "GrayScreen" in Designing Cards and Drivers, 3rd Ed. Fills the specified
  1046. page with gray, i.e. the dithered desktop pattern. I'm not aware of any
  1047. particular advantage in using this instead of FillRect().
  1048.  
  1049. Designing Cards and Drivers, 3rd Edition, Chapter 9, says that for direct
  1050. devices, i.e. >8 bit pixels, the driver will also load a linear,
  1051. gamma-corrected, gray color table.
  1052.  
  1053. Contrary to the documentation, version 2 (in System 6.03) of the video driver
  1054. for Apple's old video card requires that one supply the current mode as well.
  1055. Supplying a garbage mode screwed up the screen and soon hung the software. So
  1056. this code first obtains the current mode, and then supplies it in the GrayPage
  1057. Control call.
  1058. */
  1059. {
  1060.     VDPageInfo myVDPageInfo;
  1061.     int error;
  1062.     /* The rest of the arguments are used soley for the bug fix */
  1063.     short mode=0;        /* should be ignored, but isn't */
  1064.     short actualPage;    /* ignored */
  1065.     Ptr baseAddr;        /* ignored */
  1066.  
  1067.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1068.     
  1069.     /* Work around driver bug: get the mode */
  1070.     error=GDGetMode(device,&mode,&actualPage,&baseAddr);
  1071.     if(error)return error;
  1072.     myVDPageInfo.csMode=mode;
  1073.     
  1074.     myVDPageInfo.csPage=page;
  1075.     error=GDControl((*device)->gdRefNum,cscGrayPage,(Ptr) &myVDPageInfo);
  1076.     return error;
  1077. }
  1078.  
  1079. OSErr GDSetGray(GDHandle device,Boolean flag)
  1080. /*
  1081. Tells the driver whether you want colors (flag==0), or prefer that all colors be 
  1082. mapped to luminance-equivalent gray tones? (flag==1).
  1083. */
  1084. {
  1085.     VDFlagRec myVDFlagRec;
  1086.     int error;
  1087.  
  1088.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1089.     myVDFlagRec.flag=flag;
  1090.     error=GDControl((*device)->gdRefNum,cscSetGray,(Ptr) &myVDFlagRec);
  1091.     return error;
  1092. }
  1093.  
  1094. OSErr GDSetInterrupt(GDHandle device,Boolean flag)
  1095. /*
  1096. Set flag to 1 to enable VBL interrupts of this card, or 0 to disable. 
  1097. I don't know when it's appropriate to call this.
  1098. */
  1099. {
  1100.     VDFlagRec myVDFlagRec;
  1101.     int error;
  1102.  
  1103.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1104.     myVDFlagRec.flag=flag;
  1105.     error=GDControl((*device)->gdRefNum,cscSetInterrupt,(Ptr) &myVDFlagRec);
  1106.     return error;
  1107. }
  1108.  
  1109. OSErr GDDirectSetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1110. /*
  1111. If your pixel depth is >8 then the setEntries Control call is disabled, and you use
  1112. this instead. Except for that, GDDirectSetEntries is identical to GDSetEntries.
  1113. */
  1114. {
  1115.     VDSetEntryRecord vDSetEntryRecord;
  1116.     int error;
  1117.  
  1118.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1119.     vDSetEntryRecord.csStart=start;
  1120.     vDSetEntryRecord.csCount=count;
  1121.     vDSetEntryRecord.csTable=table;
  1122.     error=GDControl((*device)->gdRefNum,cscDirectSetEntries,(Ptr) &vDSetEntryRecord);
  1123.     return error;
  1124. }
  1125.  
  1126. OSErr GDSetDefaultMode(GDHandle device,short mode)
  1127. /*
  1128. Supposedly, you tell it what mode you want to start up with when you reboot.
  1129. (I've never been able to get this to work. No error and no effect. Perhaps I've
  1130. misunderstood its purpose.)
  1131. */
  1132. {
  1133.     VDDefModeRec myVDDefModeRec;
  1134.     int error;
  1135.  
  1136.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1137.     myVDDefModeRec.spID=mode;
  1138.     error=GDControl((*device)->gdRefNum,cscSetDefaultMode,(Ptr) &myVDDefModeRec);
  1139.     return error;
  1140. }
  1141.  
  1142. OSErr GDGetMode(GDHandle device,short *modePtr,short *pagePtr,Ptr *baseAddrPtr)
  1143. /*
  1144. It tells you the current mode, page of video memory, and the base address of that
  1145. page.
  1146. */
  1147. {
  1148.     VDPageInfo myVDPageInfo;
  1149.     int error;
  1150.  
  1151.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1152.     error=GDStatus((*device)->gdRefNum,cscGetMode,(Ptr) &myVDPageInfo);
  1153.     if(modePtr!=NULL)*modePtr=myVDPageInfo.csMode;
  1154.     if(pagePtr!=NULL)*pagePtr=myVDPageInfo.csPage;
  1155.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1156.     return error;
  1157. }
  1158.  
  1159. OSErr GDGetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1160. /*
  1161. This is much as you'd expect after reading GDSetEntries above. Note that unless
  1162. the gamma table is linear, the values returned may not be the same as those
  1163. originally passed by GDSetEntries. So call GDUncorrectedGamma first. Note that
  1164. version 2 (in System 6.03) of the video driver for Apple's old video card had a
  1165. bug and did not support "indexed" mode, i.e. start==-1. This is fixed in System
  1166. 6.05. Apple's .Display_Video_Apple_RBV1 v. 0 video driver (built-in to Mac IIci)
  1167. crashes if you attempt to make this call. However, that's a thing of the past,
  1168. because we now first patch the driver to fix the bug. Try the demo TimeVideo.
  1169. */
  1170. {
  1171.     VDSetEntryRecord vDSetEntryRecord;
  1172.     int error;
  1173.     static int bugsPatched=0;
  1174.     unsigned char *name;
  1175.     int version;
  1176.  
  1177.     if(device==NULL || (*device)->gdRefNum==0)return statusErr;
  1178.     if(!bugsPatched){
  1179.         PatchMacIIciVideoDriver();
  1180.         bugsPatched=1;
  1181.     }
  1182.  
  1183.     // Contrary to Apple's rules, these drivers crash if we attempt
  1184.     // a getEntries call. So let's be polite and instead simply return
  1185.     // an error message indicating that this call is not available.
  1186.     name=GDName(device);
  1187.     version=GDVersion(device);
  1188.     if(EqualString(name,"\p.Display_Video_Apple_RBV1",1,1) && version==0)return statusErr;
  1189.     if(EqualString(name,"\p.Color_Video_Display",1,1) && version==9288)return statusErr;
  1190.  
  1191.     vDSetEntryRecord.csStart=start;
  1192.     vDSetEntryRecord.csCount=count;
  1193.     vDSetEntryRecord.csTable=table;
  1194.     error=GDStatus((*device)->gdRefNum,cscGetEntries,(Ptr) &vDSetEntryRecord);
  1195.     return error;
  1196. }
  1197.  
  1198. OSErr GDGetPageCnt(GDHandle device,short mode,short *pagesPtr)
  1199. /*
  1200. Called "GetPages" in Designing Cards and Drivers, 3rd Ed. You tell it what mode
  1201. you're interested in. It tells you how many pages of video ram are available.
  1202. */
  1203. {
  1204.     VDPageInfo myVDPageInfo;
  1205.     int error;
  1206.  
  1207.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1208.     myVDPageInfo.csMode=mode;
  1209.     error=GDStatus((*device)->gdRefNum,cscGetPageCnt,(Ptr) &myVDPageInfo);
  1210.     if(!error)*pagesPtr=myVDPageInfo.csPage;
  1211.     return error;
  1212. }
  1213.  
  1214. OSErr GDGetPageBase(GDHandle device,short page,Ptr *baseAddrPtr)
  1215. /*
  1216. Called "GetBaseAddr" in Designing Cards and Drivers, 3rd Ed. You tell it what
  1217. page of video memory you're interested in (in the current video mode). It tells
  1218. you the base address of that page.
  1219. */
  1220. {
  1221.     VDPageInfo myVDPageInfo;
  1222.     int error;
  1223.  
  1224.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1225.     myVDPageInfo.csPage=page;
  1226.     error=GDStatus((*device)->gdRefNum,cscGetPageBase,(Ptr) &myVDPageInfo);
  1227.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1228.     return error;
  1229. }
  1230.  
  1231. OSErr GDGetGray(GDHandle device,Boolean *flagPtr)
  1232. // It tells you what the flag is set to. Do you want colors? (flag==0) Or do you
  1233. // want all colors mapped to luminance-equivalent gray tones? (flag==1).
  1234. {
  1235.     VDFlagRec myVDFlagRec;
  1236.     int error;
  1237.  
  1238.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1239.     error=GDStatus((*device)->gdRefNum,cscGetGray,(Ptr) &myVDFlagRec);
  1240.     *flagPtr=myVDFlagRec.flag;
  1241.     return error;
  1242. }
  1243.  
  1244. OSErr GDGetInterrupt(GDHandle device,Boolean *flagPtr)
  1245. // Get flag. 1 if VBL interrupts of this card are enabled. 0 if disabled. 
  1246. {
  1247.     VDFlagRec myVDFlagRec;
  1248.     int error;
  1249.  
  1250.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1251.     error=GDStatus((*device)->gdRefNum,cscGetInterrupt,(Ptr) &myVDFlagRec);
  1252.     *flagPtr=myVDFlagRec.flag;
  1253.     return error;
  1254. }
  1255.  
  1256. OSErr GDGetGamma(GDHandle device,GammaTbl **myGammaTblHandle)
  1257. /*
  1258. Returns a pointer to the Gamma table in the specified video device. (I.e. you
  1259. pass it a pointer to your pointer, a handle, which it uses to load your
  1260. pointer.)
  1261.  
  1262. Note that version 2 (in System ≤6.03) of the video driver for Apple's old video
  1263. card does not support this call due to a bug in the driver code. The later
  1264. versions of the driver (3, 4, and 5, in System 6.04 and later) work correctly.
  1265. */
  1266. {
  1267.     int error;
  1268.     VDGammaRecord myVDGammaRecord;
  1269.  
  1270.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1271.     myVDGammaRecord.csGTable=NULL;    // default address is NULL
  1272.     error=GDStatus((*device)->gdRefNum,cscGetGamma,(Ptr) &myVDGammaRecord);
  1273.     *myGammaTblHandle=(GammaTblPtr)myVDGammaRecord.csGTable;
  1274.     return error;
  1275. }
  1276.  
  1277. OSErr GDGetDefaultMode(GDHandle device,short *modePtr)
  1278. // It tells you what the default mode is. I'm not sure what this means.
  1279. {
  1280.     VDDefModeRec myVDDefModeRec;
  1281.     int error;
  1282.  
  1283.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1284.     error=GDStatus((*device)->gdRefNum,cscGetDefaultMode,(Ptr) &myVDDefModeRec);
  1285.     *modePtr=(unsigned char)myVDDefModeRec.spID;
  1286.     return error;
  1287. }
  1288.  
  1289. OSErr GDControl(int refNum,int csCode,Ptr csParamPtr)
  1290. // Uses low-level PBControl() call to implement a "Control()" call that works! 
  1291. // I don't know why this wasn't discussed in Apple Tech Note 262.
  1292. {
  1293.     CntrlParam control;
  1294.     int error;
  1295.     
  1296.     control.ioCompletion=NULL;
  1297.     control.ioCRefNum=refNum;
  1298.     control.csCode=csCode;
  1299.     *((Ptr *) &control.csParam[0]) = csParamPtr;
  1300.     error=PBControl((ParmBlkPtr) &control,0);
  1301.     return error;
  1302. }
  1303.  
  1304. OSErr GDStatus(int refNum,int csCode,Ptr csParamPtr)
  1305. // Uses low-level PBStatus() call to implement a "Status()" call that works! The
  1306. // need for this is explained in Apple Tech Note 262, which was issued in response
  1307. // to my bug report in summer of '89.
  1308. {
  1309.     CntrlParam control;
  1310.     int error;
  1311.     
  1312.     control.ioCompletion=NULL;
  1313.     control.ioCRefNum=refNum;
  1314.     control.csCode=csCode;
  1315.     *((Ptr *) &control.csParam[0]) = csParamPtr;
  1316.     error=PBStatus((ParmBlkPtr) &control,0);
  1317.     return error;
  1318. }
  1319.  
  1320. #if 0
  1321. /*
  1322. From: absurd@apple.apple.com (Tim Dierks, software saboteur)
  1323. Date: Fri, 20 Nov 1992 00:38:14 GMT
  1324. Organization: MacDTS Marauders
  1325.  
  1326. Here's the right way to get the slot number of a monitor, given its
  1327. GDevice:  (as a bonus, this also gets the name of the card in
  1328. question; to just get the slot, chop off all the lines after the
  1329. *slot = ... line.
  1330. */
  1331.  
  1332. OSErr GetSlotAndName(GDHandle gDev,short *slot,char *name)
  1333. {   OSErr       err;
  1334.     short       refNum;
  1335.     SpBlock     spb;
  1336.     
  1337.     refNum = (**gDev).gdRefNum;    // video driver refNum for this GDevice
  1338.     *slot = (**(AuxDCEHandle)GetDCtlEntry(refNum)).dCtlSlot;
  1339.                                    // slot in which this video card sits
  1340.     spb.spSlot = *slot;         // In the slot we're interested in
  1341.     spb.spID = 0;
  1342.     spb.spExtDev = 0;
  1343.     spb.spCategory = 1;         // Get the board sResource
  1344.     spb.spCType = 0;
  1345.     spb.spDrvrSW = 0;
  1346.     spb.spDrvrHW = 0;
  1347.     spb.spTBMask = 0;
  1348.     err = SNextTypeSRsrc(&spb);
  1349.     if (err)return err;
  1350.     spb.spID = 2;               // Getting the description string
  1351.                                 // spSPointer was set up by SNextTypesResource
  1352.     err = SGetCString(&spb);
  1353.     if (err)return err;
  1354.     strcpy(name,(char *)spb.spResult);  // Get the returned string
  1355.     DisposPtr((Ptr)spb.spResult);    // Undocumented; we have to dispose of it
  1356.     c2pstr(name);
  1357.     return noErr;
  1358. }
  1359. #endif
  1360.  
  1361. char *GDCardName(GDHandle device)
  1362. /*
  1363. Returns the address of a C string containing the name of the video card. You
  1364. should call DisposPtr() on the returned address when you no longer need it.
  1365. Takes about 1.5 ms; I don't know why Apple's slot routines are so slow. This
  1366. routine sets up the flags in the SNextTypeSRsrc() call quite differently from
  1367. the above example, but I don't know if that matters, since I've been using this
  1368. routine for a year or so without any problems.
  1369. */
  1370. {
  1371.     AuxDCE **auxDCEHandle;
  1372.     SpBlock SPB,SPB1;
  1373.     
  1374.     if(device==NULL || (*device)->gdRefNum==0)return "";
  1375.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1376.     SPB.spSlot = (**auxDCEHandle).dCtlSlot;
  1377.     SPB.spCategory = 0;
  1378.     SPB.spCType =     0;
  1379.     SPB.spDrvrSW =     0;
  1380.     SPB.spDrvrHW =     1;
  1381.     SPB.spTBMask = 0xf;
  1382.     SPB.spID = 0;
  1383.     SPB.spExtDev = 0;
  1384.     if(SNextTypeSRsrc(&SPB) == noErr) {
  1385.         SPB1.spsPointer = SPB.spsPointer;
  1386.         SPB1.spID = 2;
  1387.         SGetCString(&SPB1);
  1388.         return (char *)SPB1.spResult;
  1389.     }
  1390.     else return "";
  1391. }
  1392.  
  1393. unsigned char *GDName(GDHandle device)
  1394. // Returns a pointer to the name of the driver (a pascal string). 
  1395. {
  1396.     VideoDriver *videoDriverPtr;
  1397.  
  1398.     if(device==NULL || (*device)->gdRefNum==0)return "\p";
  1399.     videoDriverPtr=GDDriverAddress(device);
  1400.     return videoDriverPtr->name;
  1401. }
  1402.  
  1403. char *GDNameStr(GDHandle device)
  1404. // Returns the driver name as a C string.
  1405. {
  1406.     unsigned char *sp;
  1407.     static char name[32];
  1408.     
  1409.     sp=GDName(device);
  1410.     memcpy(name,sp,sp[0]+1);
  1411.     return p2cstr((unsigned char *)name);
  1412. }
  1413.  
  1414.  
  1415. int GDVersion(GDHandle device)
  1416. // Returns the version number of the driver. From the first word-aligned word after
  1417. // the name string.
  1418. {
  1419.     int version;
  1420.     unsigned char *bytePtr;
  1421.  
  1422.     if(device==NULL || (*device)->gdRefNum==0)return 0;
  1423.     bytePtr=GDName(device);
  1424.     bytePtr += 1+bytePtr[0];    /* go to end of Pascal string */
  1425.     bytePtr = (unsigned char *)((long)(bytePtr+1) & ~1);    // round up to word boundary
  1426.     version = *(short *)bytePtr;
  1427.     return version;
  1428. }
  1429.  
  1430. VideoDriver *GDDriverAddress(GDHandle device)
  1431. // Returns a pointer to the driver, whether in ROM or RAM. 
  1432. {
  1433.     AuxDCE **auxDCEHandle;
  1434.     VideoDriver *videoDriverPtr;
  1435.  
  1436.     if(device==NULL || (*device)->gdRefNum==0)return NULL;
  1437.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1438.     if((**auxDCEHandle).dCtlFlags & dRAMBased){
  1439.         /* RAM-based driver. */
  1440.         videoDriverPtr=*(VideoDriver **) (**auxDCEHandle).dCtlDriver;
  1441.     }
  1442.     else{
  1443.         /* ROM-based driver. */
  1444.         videoDriverPtr=(VideoDriver *) (**auxDCEHandle).dCtlDriver;
  1445.     }
  1446.     return videoDriverPtr;
  1447. }
  1448.  
  1449. /*
  1450. ROUTINE: PatchMacIIciVideoDriver
  1451. PURPOSE:
  1452. It is unlikely that you will need to call this explicitly, because it is called
  1453. automatically by GDGetEntries the first time it is invoked, and the sole purpose
  1454. of this routine is to fix a driver bug that would cause a crash when called by
  1455. GDGetEntries.
  1456.  
  1457. The Mac IIci built-in video driver (.Display_Video_Apple_RBV1 driver, version 0)
  1458. has a bug that causes it to crash if you try to do a getEntries Status request.
  1459. PatchMacIIciVideoDriver() will find and patch the memory-resident copy of the
  1460. buggy driver. Only two instructions are modified, to save and restore more
  1461. registers. This fix persists only until the next reboot. If the patch is
  1462. successfully applied the version number is increased from 0 to 100, to
  1463. distinguish it from versions 0 and 1.
  1464.  
  1465. A returned value of 1 indicates success: the needed patch was applied, either now
  1466. or previously. A return value of 0 indicates no patch was needed.
  1467.  
  1468. This patch is based on a comparison of the version 0 and 1 drivers used by the
  1469. Mac IIci and IIsi, respectively. The patch changes a pair of save and restore
  1470. operations (MOVEM.L to and from the stack) to save and restore registers D1 and
  1471. A1 as well as D4, A3, and A4. There are many other differences between versions
  1472. 0 and 1 of the driver, but this change is enough to keep the version 0 driver
  1473. from crashing when we attempt to read the clut by calling GDGetEntries.
  1474.  
  1475. The only change that the Mac operating system could possibly notice is that,
  1476. when we're done patching, we set the handle to be non-purgeable, since purging
  1477. and reloading the driver would eliminate the patch.
  1478.  
  1479. edward_de_Jong@bmug.org and Robert Savoy (SAVOY@RISVAX.ROWLAND.ORG) reported
  1480. that their Mac IIci computers' built-in video driver is ROM-based, so
  1481. PatchMacIIciVideoDriver was enhanced to deal with a ROM-based driver, by copying
  1482. the driver into RAM, making that the active driver, and patching it. Robert
  1483. Savoy reports that it works fine.
  1484.  
  1485. An alternative, permanent, solution is described in the file "Video synch":
  1486. upgrading to Apple's bug-free version 1 of the driver. However, that solution
  1487. only works if the Mac IIci has more than one monitor.
  1488.  
  1489. */
  1490.  
  1491. int PatchMacIIciVideoDriver(void)
  1492. {
  1493.     GDHandle device;
  1494.     short *w;
  1495.     AuxDCE **auxDCEHandle;
  1496.     Handle handle;
  1497.     enum{badVersion=0};
  1498.     int error;
  1499.     long value;
  1500.     
  1501.     error=Gestalt(gestaltQuickdrawVersion,&value);
  1502.     if(error || value<gestalt8BitQD)return 0;    // need 8-bit quickdraw
  1503.     device = GetDeviceList();
  1504.     while(1) {
  1505.         if(device==NULL || (*device)->gdRefNum==0)return 0;
  1506.         if (!TestDeviceAttribute(device,screenDevice)
  1507.             || !TestDeviceAttribute(device,screenActive)){
  1508.             device=GetNextDevice(device);
  1509.             continue;
  1510.         }
  1511.         if(EqualString("\p.Display_Video_Apple_RBV1",GDName(device),1,1))
  1512.             switch(GDVersion(device)){
  1513.                 case badVersion:
  1514.                     break;
  1515.                 case badVersion+100:    // already patched
  1516.                     return 1;
  1517.                 default:
  1518.                     return 0;
  1519.         }else{
  1520.             device=GetNextDevice(device);
  1521.             continue;
  1522.         }
  1523.         break;
  1524.     }
  1525.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1526.     
  1527.     // Move ROM-based driver into RAM.
  1528.     if(!((**auxDCEHandle).dCtlFlags & dRAMBased)){
  1529.         long bytes;
  1530.         VideoDriver *driver;
  1531.         
  1532.         driver=(VideoDriver *)(**auxDCEHandle).dCtlDriver;
  1533.         // Sometimes the word preceding the driver in ROM seems to be the
  1534.         // driver size, but not always, e.g. the built-in driver on the Mac IIsi.
  1535.         bytes=*((short *)driver-1);
  1536.         // Driver size unknown, guessing (generously) at twice the highest offset.
  1537.         bytes=driver->open;
  1538.         if(bytes<driver->prime)bytes=driver->prime;
  1539.         if(bytes<driver->control)bytes=driver->control;
  1540.         if(bytes<driver->status)bytes=driver->status;
  1541.         if(bytes<driver->close)bytes=driver->close;
  1542.         bytes*=2;
  1543.         // We know the Mac IIci driver size to be 1896
  1544.         // when ROM version is 124 rev. 1, but who knows for later ROMs?
  1545.         //bytes=1896;
  1546.         handle=NewHandleSys(bytes);
  1547.         if(handle==NULL)return 0;    // Insufficient room on System heap.
  1548.         HLockHi(handle);
  1549.         BlockMove((Ptr)driver,*handle,bytes);
  1550.         (**auxDCEHandle).dCtlDriver=(Ptr)handle;
  1551.         (**auxDCEHandle).dCtlFlags |= dRAMBased;        
  1552.     }
  1553.     
  1554.     // Patch RAM-based driver.
  1555.     handle=(Handle)(**auxDCEHandle).dCtlDriver;
  1556.     w=*(short **)handle;
  1557.     if(w[0x51e/2]!=0x818 || w[0x590/2]!=0x1810 || w[0x2c/2]!=badVersion){
  1558.         printf("PatchMacIIciVideoDriver error.\n");
  1559.         return 0;
  1560.     }
  1561.     w[0x51e/2]=0x4858;
  1562.     w[0x590/2]=0x1a12;
  1563.     w[0x2c/2]+=100;                                    // Change version number.
  1564.     if(w[0x51e/2]!=0x4858 || w[0x590/2]!=0x1a12){
  1565.         printf("PatchMacIIciVideoDriver error.\n");
  1566.         return 0;
  1567.     }
  1568.     HNoPurge(handle);
  1569.     return 1;
  1570. }
  1571.