home *** CD-ROM | disk | FTP | other *** search
/ Mac-Source 1994 July / Mac-Source_July_1994.iso / C and C++ / Science⁄Math / VideoToolbox / VideoToolboxSources / GDVideo.c < prev    next >
Encoding:
Text File  |  1993-12-29  |  50.0 KB  |  1,438 lines  |  [TEXT/KAHL]

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