Guest User

GifImage.pas

a guest
May 29th, 2011
965
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 383.16 KB | None | 0 0
  1. unit GIFImage;
  2. ////////////////////////////////////////////////////////////////////////////////
  3. //                                                                            //
  4. // Project: GIF Graphics Object                                           //
  5. // Module:  gifimage                                                      //
  6. // Description: TGraphic implementation of the GIF89a graphics format         //
  7. // Version: 2.2                                                           //
  8. // Release: 5                                                             //
  9. // Date:    23-MAY-1999                                                   //
  10. // Target:  Win32, Delphi 2, 3, 4 & 5, C++ Builder 3 & 4                  //
  11. // Author(s):   anme: Anders Melander, [email protected]                     //
  12. //      fila: Filip Larsen                                            //
  13. //      rps: Reinier Sterkenburg                                      //
  14. // Copyright:   (c) 1997-99 Anders Melander.                                  //
  15. //      All rights reserved.                                          //
  16. // Formatting:  2 space indent, 8 space tabs, 80 columns.                     //
  17. //                                                                            //
  18. ////////////////////////////////////////////////////////////////////////////////
  19. // Changed 2001.07.23 by Finn Tolderlund:                                     //
  20. // Changed according to e-mail from "Rolf Frei" <[email protected]>               //
  21. //   on 2001.07.23 so that it works in Delphi 6.                              //
  22. //                                                                            //
  23. // Changed 2002.07.07 by Finn Tolderlund:                                     //
  24. // Incorporated additional modifications by Alexey Barkovoy ([email protected])
  25. // found in his Delphi 6 GifImage.pas (from 22-Dec-2001).                     //
  26. // Alexey Barkovoy's Delphi 6 gifimage.pas can be downloaded from             //
  27. //   http://clootie.narod.ru/delphi/download_vcl.html                         //
  28. // These changes made showing of animated gif files more stable. The code     //
  29. // from 2001.07.23 could crash sometimes with an Execption EAccessViolation.  //
  30. //                                                                            //
  31. // Changed 2002.10.06 by Finn Tolderlund:                                     //
  32. // Delphi 7 compatible.                                                       //
  33. //                                                                            //
  34. // Changed 2003-03-06 by Finn Tolderlund:                                     //
  35. // Changes made as a result of postings in borland.public.delphi.graphics     //
  36. // from 2003-02-28 to 2003-03-05 where white (255,255,255) in a bitmap        //
  37. // was converted to (254,254,254) in the gif.                                 //
  38. // The doCreateOptimizedPaletteFromSingleBitmap function and                  //
  39. // the CreateOptimizedPaletteFromManyBitmaps function is changed so that      //
  40. // the correct offset 246 is used instead of 245.                             //
  41. // The ReduceColors function is changed according to Anders Melander's post   //
  42. // so that a colour get converted to the precise colour if that colour is     //
  43. // present in the palette when using ColorReduction rmQuantize.               //
  44. //                                                                            //
  45. // Changed 2003-03-09 by Finn Tolderlund:                                     //
  46. // Delphi 7 version is now assumed if unknown compiler version is unknown     //
  47. // for better compatibility with future Delphi versions.                      //
  48. // Hopefully this code is now compatible with future Delphi versions,         //
  49. // unless Borland makes some changes that breaks existing code.               //
  50. //                                                                            //
  51. // Changed 2003-08-04 by Finn Tolderlund:                                     //
  52. // Changed procedure AddMaskOnly so that it doesn't leak a GDI HBitmap-object //
  53. // and it doesn't release the handle of the source bitmap which               //
  54. // is used to assign to the GIF object as in gif.assign(bm);                  //
  55. // These changes were made as a result of a news post made by Renate Schaaf   //
  56. // with the subject "TGifImage HBitmap leak on assign?"                       //
  57. // in borland.public.delphi.graphics on Mon 28 Jul 2003 and Sun 03 Aug 2003.  //
  58. //                                                                            //
  59. // Changed 2004.03.09 by Finn Tolderlund:                                     //
  60. // Added a ForceFrame property to the TGIFImage class.                        //
  61. // The ForceFrame property can be used to make TGIFImage display a apecific   //
  62. // sub frame from an animated gif.                                            //
  63. // How to use: Set the Animate property to False and set the ForceFrame       //
  64. // property to a desired frame number (0-N)                                   //
  65. // Normal display: Set the ForceFrame property to -1 and set Animate to True. //
  66. // If ForceFrame is negative TGIFImage behaves just as before this change.    //
  67. // Note that if the sub frame in the gif only contains part of the image      //
  68. // (i.e. only the changes from previous frames) the result is unpredictable.  //
  69. // The result is best if each sub frame contains a whole image.               //
  70. // If the sub frame is transparent the background is not automatically        //
  71. // restored, you must do so yourself if you want that.                        //
  72. // If you are using a TImage to display the gif you can use                   //
  73. // Image.Parent.Invalidate or Image.Parent.Refresh to restore the background. //
  74. // This change was made as a result of a email correspondance with            //
  75. // Tineke Kosmis (http://www.classe.nl/) which requested such a property.     //
  76. //                                                                            //
  77. // Changed 2006.07.09 by Finn Tolderlund:                                     //
  78. // Added conditional switch as default: FIXHEADER_WIDTHHEIGHT_SILENT          //
  79. // When the switch is defined:                                                //
  80. // When loading a gif all frames are examined. If a frame has a larger        //
  81. // Width/Height than the header values then the header values are updated     //
  82. // with the larger values from the frame.                                     //
  83. // I had a MANTA.GIF where the header said 120x89 but the frames said 200x148 //
  84. // and the frames got clipped. MSIE didn't clip it.                           //
  85. // http://www.graphcomp.com/info/specs/ani_gif.html :                         //
  86. // Do not assume all of your images are the same size. Read through their     //
  87. // sizes and set the logical screen to the largest width & height included    //
  88. // in the file.                                                               //
  89. // By removing the define FIXHEADER_WIDTHHEIGHT_SILENT                        //
  90. // the header is not altered. This makes the unit work as before.             //
  91. //                                                                            //
  92. // Changed 2006.07.10 by Finn Tolderlund:                                     //
  93. // Added conditional switch as default: DEFAULT_GOCLEARLOOP                   //
  94. // When the switch is defined:                                                //
  95. // When loading a gif default DrawOptions include goClearLoop                 //
  96. // Same as adding goClearLoop manually to DrawOptions.                        //
  97. // This will clear an animated gif before first frame on each loop.           //
  98. // Someone sent me a 'conductor.gif' where some of the last frame was retaind //
  99. // when beginning a new loop and that was visually incorrect.                 //
  100. // Without glClearLoop the first frame may look different on the second loop  //
  101. // because some part of the last frame could still be present.                //
  102. // With goClearLoop the first frame will always look the same on each loop.   //
  103. // I think the last is better.                                                //
  104. //                                                                            //
  105. // Changed 2006.07.29 by Finn Tolderlund:                                     //
  106. // Added a check in procedure TGIFSubImage.Decompress to make sure that       //
  107. // the InitialBitsPerCode variable never exeeds the value 15.                 //
  108. // Someone sent an animated iup110296.gif (corrupt I think) which caused      //
  109. // this unit to crash in function NextLZW because InitialBitsPerCode was 20.  //
  110. // This fix prevents the crash and should not cause problems with other gifs. //
  111. // Not sure that the fix is the correct way to handle it. It seems to work.   //
  112. //                                                                            //
  113. // Changed 2006.10.09 by Finn Tolderlund:                                     //
  114. // Received a mail from Michael Thomas Greer with a fix that allows           //
  115. // the TGIFSubImage.Pixels[] property to be writeable. The help file states   //
  116. // that the Pixels property can be written, but it was read-only.             //
  117. // Help file: "Write Pixels to change the color index of individual pixels".  //
  118. //                                                                            //
  119. // Changed 2006.10.16 by Finn Tolderlund:                                     //
  120. // Received a mail from Maurizio Lotauro who was using Delphi 5 and FastMM4.  //
  121. // FastMM4 complains about a memory leak when using Delphi 5.                 //
  122. // I don't have Delphi 5 installed so I can't test if there really is a       //
  123. // memory leak or if it's just FastMM4 which can't detect it correctly.       //
  124. // The problem and fix only applies to Delphi 5 or older.                     //
  125. // Added a fix to keep FastMM4 happy. See more at this link:                  //
  126. // http://sourceforge.net/forum/forum.php?thread_id=1559584&forum_id=443400   //
  127. //                                                                            //
  128. // Changed 2007.01.18 by Finn Tolderlund:                                     //
  129. // The ReduceColors function is changed so that it's now possible to use      //
  130. // the TFastColorLookup class if you use ColorReduction rmQuantize.           //
  131. // The TFastColorLookup class was removed 2003-03-06, but is introduced again //
  132. // because Paul Lopez needed speed when adding images to a gif.               //
  133. // This changes how rmQuantize works: It's now fast but less precise.         //
  134. // This means:                                                                //
  135. // Use rmQuantizeWindows to get precision, use rmQuantize if you need speed.  //
  136. //                                                                            //
  137. // Changed 2008.10.19 by Finn Tolderlund:                                     //
  138. // Now compatible with Delphi 2009.                                           //
  139. // Generally changed use of Char/PChar to AnsiChar/PAnsiChar.                 //
  140. //                                                                            //
  141. // Changed 2009.10.10 by Finn Tolderlund:                                     //
  142. // Now compatible with Delphi 2010.                                           //
  143. // Changed conditional defines to assume Delphi 2010 for future compilers.    //
  144. // Kind thanks to Peter Johnson (www.delphidabbler.com)                       //
  145. //                                                                            //
  146. // Changed 2009.10.14 by Finn Tolderlund:                                     //
  147. // Simplified the list of defines and remove a few warnings in Delphi 2006.   //
  148. //                                                                            //
  149. ////////////////////////////////////////////////////////////////////////////////
  150. //                                                                            //
  151. // Please read the "Conditions of use" in the release notes.                  //
  152. //                                                                            //
  153. ////////////////////////////////////////////////////////////////////////////////
  154. // Known problems:
  155. //
  156. // * The combination of buffered, tiled and transparent draw will display the
  157. //   background incorrectly (scaled).
  158. //   If this is a problem for you, use non-buffered (goDirectDraw) drawing
  159. //   instead.
  160. //
  161. // * The combination of non-buffered, transparent and stretched draw is
  162. //   sometimes distorted with a pattern effect when the image is displayed
  163. //   smaller than the real size (shrinked).
  164. //
  165. // * Buffered display flickers when TGIFImage is used by a transparent TImage
  166. //   component.
  167. //   This is a problem with TImage caused by the fact that TImage was designed
  168. //   with static images in mind. Not much I can do about it.
  169. //
  170. ////////////////////////////////////////////////////////////////////////////////
  171. // To do (in rough order of priority):
  172. // { TODO -oanme -cFeature : TImage hook for destroy notification. }
  173. // { TODO -oanme -cFeature : TBitmap pool to limit resource consumption on Win95/98. }
  174. // { TODO -oanme -cImprovement : Make BitsPerPixel property writable. }
  175. // { TODO -oanme -cFeature : Visual GIF component. }
  176. // { TODO -oanme -cImprovement : Easier method to determine DrawPainter status. }
  177. // { TODO -oanme -cFeature : Import to 256+ color GIF. }
  178. // { TODO -oanme -cFeature : Make some of TGIFImage's properties persistent (DrawOptions etc). }
  179. // { TODO -oanme -cFeature : Add TGIFImage.Persistent property. Should save published properties in application extension when this options is set. }
  180. // { TODO -oanme -cBugFix : Solution for background buffering in scrollbox. }
  181. //
  182. //////////////////////////////////////////////////////////////////////////////////
  183. {$ifdef BCB}
  184. {$ObjExportAll On}
  185. {$endif}
  186.  
  187. interface
  188. ////////////////////////////////////////////////////////////////////////////////
  189. //
  190. //      Conditional Compiler Symbols
  191. //
  192. ////////////////////////////////////////////////////////////////////////////////
  193. (*
  194.   DEBUG             Must be defined if any of the DEBUG_xxx
  195.                 symbols are defined.
  196.                                 If the symbol is defined the source will not be
  197.                                 optimized and overflow- and range checks will be
  198.                                 enabled.
  199.  
  200.   DEBUG_HASHPERFORMANCE     Calculates hash table performance data.
  201.   DEBUG_HASHFILLFACTOR      Calculates fill factor of hash table -
  202.                 Interferes with DEBUG_HASHPERFORMANCE.
  203.   DEBUG_COMPRESSPERFORMANCE Calculates LZW compressor performance data.
  204.   DEBUG_DECOMPRESSPERFORMANCE   Calculates LZW decompressor performance data.
  205.   DEBUG_DITHERPERFORMANCE   Calculates color reduction performance data.
  206.   DEBUG_DRAWPERFORMANCE     Calculates low level drawing performance data.
  207.                 The performance data for DEBUG_DRAWPERFORMANCE
  208.                                 will be displayed when you press the Ctrl key.
  209.   DEBUG_RENDERPERFORMANCE   Calculates performance data for the GIF to
  210.                 bitmap converter.
  211.                 The performance data for DEBUG_DRAWPERFORMANCE
  212.                                 will be displayed when you press the Ctrl key.
  213.  
  214.   GIF_NOSAFETY          Define this symbol to disable overflow- and
  215.                 range checks.
  216.                                 Ignored if the DEBUG symbol is defined.
  217.  
  218.   STRICT_MOZILLA        Define to mimic Mozilla as closely as possible.
  219.                 If not defined, a slightly more "optimal"
  220.                                 implementation is used (IMHO).
  221.  
  222.   FAST_AS_HELL          Define this symbol to use strictly GIF compliant
  223.                 (but too fast) animation timing.
  224.                                 Since our paint routines are much faster and
  225.                                 more precise timed than Mozilla's, the standard
  226.                                 GIF and Mozilla values causes animations to loop
  227.                                 faster than they would in Mozilla.
  228.                                 If the symbol is _not_ defined, an alternative
  229.                                 set of tweaked timing values will be used.
  230.                                 The tweaked values are not optimal but are based
  231.                                 on tests performed on my reference system:
  232.                                 - Windows 95
  233.                                 - 133 MHz Pentium
  234.                                 - 64Mb RAM
  235.                                 - Diamond Stealth64/V3000
  236.                                 - 1600*1200 in 256 colors
  237.                                 The alternate values can be modified if you are
  238.                                 not satisfied with my defaults (they can be
  239.                                 found a few pages down).
  240.  
  241.   REGISTER_TGIFIMAGE            Define this symbol to register TGIFImage with
  242.                 the TPicture class and integrate with TImage.
  243.                                 This is required to be able to display GIFs in
  244.                                 the TImage component.
  245.                                 The symbol is defined by default.
  246.                                 Undefine if you use another GIF library to
  247.                                 provide GIF support for TImage.
  248.  
  249.   PIXELFORMAT_TOO_SLOW      When this symbol is defined, the internal
  250.                 PixelFormat routines are used in some places
  251.                                 instead of TBitmap.PixelFormat.
  252.                                 The current implementation (Delphi4, Builder 3)
  253.                                 of TBitmap.PixelFormat can in some situation
  254.                                 degrade performance.
  255.                                 The symbol is defined by default.
  256.  
  257.   CREATEDIBSECTION_SLOW     If this symbol is defined, TDIBWriter will
  258.                 use global memory as scanline storage, instead
  259.                                 of a DIB section.
  260.                                 Benchmarks have shown that a DIB section is
  261.                                 twice as slow as global memory.
  262.                                 The symbol is defined by default.
  263.                                 The symbol requires that PIXELFORMAT_TOO_SLOW
  264.                                 is defined.
  265.  
  266.   SERIALIZE_RENDER      Define this symbol to serialize threaded
  267.                 GIF to bitmap rendering.
  268.                                 When a GIF is displayed with the goAsync option
  269.                                 (the default), the GIF to bitmap rendering is
  270.                                 executed in the context of the draw thread.
  271.                                 If more than one thread is drawing the same GIF
  272.                                 or the GIF is being modified while it is
  273.                                 animating, the GIF to bitmap rendering should be
  274.                                 serialized to guarantee that the bitmap isn't
  275.                                 modified by more than one thread at a time. If
  276.                                 SERIALIZE_RENDER is defined, the draw threads
  277.                                 uses TThread.Synchronize to serialize GIF to
  278.                                 bitmap rendering.
  279.  
  280.   FIXHEADER_WIDTHHEIGHT_SILENT  Define this symbol to adjust Width and Height
  281.                                 in the header if any of the frames has a larger
  282.                                 Width or Height.
  283.  
  284.   DEFAULT_GOCLEARLOOP           Define this symbol to clear animation on each
  285.                                 loop before first frame.
  286.                                 Same as adding goClearLoop to DrawOptions.
  287.                                 STRICT_MOZILLA does the same,
  288.                                 but STRICT_MOZILLA does something more.
  289.  
  290. *)
  291.  
  292. {$DEFINE REGISTER_TGIFIMAGE}
  293. {$DEFINE PIXELFORMAT_TOO_SLOW}
  294. {$DEFINE CREATEDIBSECTION_SLOW}
  295. {$DEFINE FIXHEADER_WIDTHHEIGHT_SILENT}
  296. {$DEFINE DEFAULT_GOCLEARLOOP}
  297.  
  298. ////////////////////////////////////////////////////////////////////////////////
  299. //
  300. //      Determine Delphi and C++ Builder version
  301. //
  302. ////////////////////////////////////////////////////////////////////////////////
  303.  
  304. // Delphi 1.x
  305. {$IFDEF VER80}
  306.   'Error: TGIFImage does not support Delphi 1.x'
  307. {$ENDIF}
  308.  
  309. // Delphi 2.x
  310. {$IFDEF VER90}
  311.   {$DEFINE VER9x}
  312. {$ENDIF}
  313.  
  314. // C++ Builder 1.x
  315. {$IFDEF VER93}
  316.   // Good luck...
  317.   {$DEFINE VER9x}
  318. {$ENDIF}
  319.  
  320. // Delphi 3.x
  321. {$IFDEF VER100}
  322.   {$DEFINE VER10_PLUS}
  323.   {$DEFINE D3_BCB3}
  324. {$ENDIF}
  325.  
  326. // C++ Builder 3.x
  327. {$IFDEF VER110}
  328.   {$DEFINE VER10_PLUS}
  329.   {$DEFINE VER11_PLUS}
  330.   {$DEFINE D3_BCB3}
  331.   {$DEFINE BAD_STACK_ALIGNMENT}
  332. {$ENDIF}
  333.  
  334. // Delphi 4.x
  335. {$IFDEF VER120}
  336.   {$DEFINE VER10_PLUS}
  337.   {$DEFINE VER11_PLUS}
  338.   {$DEFINE VER12_PLUS}
  339.   {$DEFINE BAD_STACK_ALIGNMENT}
  340. {$ENDIF}
  341.  
  342. // C++ Builder 4.x
  343. {$IFDEF VER125}
  344.   {$DEFINE VER10_PLUS}
  345.   {$DEFINE VER11_PLUS}
  346.   {$DEFINE VER12_PLUS}
  347.   {$DEFINE VER125_PLUS}
  348.   {$DEFINE BAD_STACK_ALIGNMENT}
  349. {$ENDIF}
  350.  
  351. // Delphi 5.x
  352. {$IFDEF VER130}
  353.   {$DEFINE VER10_PLUS}
  354.   {$DEFINE VER11_PLUS}
  355.   {$DEFINE VER12_PLUS}
  356.   {$DEFINE VER125_PLUS}
  357.   {$DEFINE VER13_PLUS}
  358.   {$DEFINE BAD_STACK_ALIGNMENT}
  359. {$ENDIF}
  360.  
  361. (*
  362. // Delphi 6.x
  363. {$IFDEF VER140}
  364.   {$WARN SYMBOL_PLATFORM OFF}
  365.   {$DEFINE VER10_PLUS}
  366.   {$DEFINE VER11_PLUS}
  367.   {$DEFINE VER12_PLUS}
  368.   {$DEFINE VER125_PLUS}
  369.   {$DEFINE VER13_PLUS}
  370.   {$DEFINE VER14_PLUS}
  371.   {$DEFINE BAD_STACK_ALIGNMENT}
  372. {$ENDIF}
  373.  
  374. // Delphi 7.x
  375. {$IFDEF VER150}
  376.   {$WARN SYMBOL_PLATFORM OFF}
  377.   {$DEFINE VER10_PLUS}
  378.   {$DEFINE VER11_PLUS}
  379.   {$DEFINE VER12_PLUS}
  380.   {$DEFINE VER125_PLUS}
  381.   {$DEFINE VER13_PLUS}
  382.   {$DEFINE VER14_PLUS}
  383.   {$DEFINE VER15_PLUS}
  384.   {$DEFINE BAD_STACK_ALIGNMENT}
  385. {$ENDIF}
  386.  
  387. // 2008.10.19 ->
  388. // Delphi 2009
  389. {$IFDEF VER200}
  390.   {$WARN SYMBOL_PLATFORM OFF}
  391.   {$DEFINE VER10_PLUS}
  392.   {$DEFINE VER11_PLUS}
  393.   {$DEFINE VER12_PLUS}
  394.   {$DEFINE VER125_PLUS}
  395.   {$DEFINE VER13_PLUS}
  396.   {$DEFINE VER14_PLUS}
  397.   {$DEFINE VER15_PLUS}
  398.   {$DEFINE VER20_PLUS}
  399.   {$DEFINE BAD_STACK_ALIGNMENT}
  400. {$ENDIF}
  401. // 2008.10.19 <-
  402.  
  403. // 2003.03.09 ->
  404. // Unknown compiler version - assume D7 compatible
  405. {$IFNDEF VER9x}
  406. {$IFNDEF VER10_PLUS}
  407.   {$WARN SYMBOL_PLATFORM OFF}
  408.   {$DEFINE VER10_PLUS}
  409.   {$DEFINE VER11_PLUS}
  410.   {$DEFINE VER12_PLUS}
  411.   {$DEFINE VER125_PLUS}
  412.   {$DEFINE VER13_PLUS}
  413.   {$DEFINE VER14_PLUS}
  414.   {$DEFINE VER15_PLUS}
  415.   {$DEFINE BAD_STACK_ALIGNMENT}
  416. {$ENDIF}
  417. {$ENDIF}
  418. // 2003.03.09 <-
  419.  
  420. // 2009.10.10 ->
  421. // This ensures that future compilers always have same defines as latest compiler listed here.
  422. {$IFDEF CONDITIONALEXPRESSIONS}
  423.   {$IF CompilerVersion >= 21.0}   // >= Delphi 2010
  424.     {$WARN SYMBOL_PLATFORM OFF}
  425.     {$WARN SYMBOL_DEPRECATED OFF}
  426.     {$DEFINE VER10_PLUS}
  427.     {$DEFINE VER11_PLUS}
  428.     {$DEFINE VER12_PLUS}
  429.     {$DEFINE VER125_PLUS}
  430.     {$DEFINE VER13_PLUS}
  431.     {$DEFINE VER14_PLUS}
  432.     {$DEFINE VER15_PLUS}
  433.     {$DEFINE VER20_PLUS}
  434.     {$DEFINE BAD_STACK_ALIGNMENT}
  435.     {$DEFINE VER21_PLUS}
  436.   {$IFEND}
  437. {$ENDIF}
  438. // 2009.10.10 <-
  439. *)
  440.  
  441. // 2009.10.14 ->
  442. // This ensures that future compilers always have same defines as latest compiler listed here.
  443. {$IFDEF CONDITIONALEXPRESSIONS}
  444.    {$IF CompilerVersion >= 14.0}   // >= Delphi 6
  445.      {$WARN SYMBOL_PLATFORM OFF}
  446.      {$WARN SYMBOL_DEPRECATED OFF}
  447.      {$DEFINE VER10_PLUS}
  448.      {$DEFINE VER11_PLUS}
  449.      {$DEFINE VER12_PLUS}
  450.      {$DEFINE VER125_PLUS}
  451.      {$DEFINE VER13_PLUS}
  452.      {$DEFINE VER14_PLUS}
  453.      {$DEFINE BAD_STACK_ALIGNMENT}
  454.    {$IFEND}
  455.    {$IF CompilerVersion >= 15.0}   // >= Delphi 7
  456.      {$DEFINE VER15_PLUS}
  457.    {$IFEND}
  458.    {$IF CompilerVersion >= 20.0}   // >= Delphi 2009
  459.      {$DEFINE VER20_PLUS}
  460.    {$IFEND}
  461.    {$IF CompilerVersion >= 21.0}   // >= Delphi 2010
  462.      {$DEFINE VER21_PLUS}
  463.    {$IFEND}
  464. {$ENDIF}
  465. // 2009.10.14 <-
  466.  
  467. ////////////////////////////////////////////////////////////////////////////////
  468. //
  469. //      Compiler Options required to compile this library
  470. //
  471. ////////////////////////////////////////////////////////////////////////////////
  472. {$A+,B-,H+,J+,K-,M-,T-,X+}
  473.  
  474. // Debug control - You can safely change these settings
  475. {$IFDEF DEBUG}
  476.   {$C+} // ASSERTIONS
  477.   {$O-} // OPTIMIZATION
  478.   {$Q+} // OVERFLOWCHECKS
  479.   {$R+} // RANGECHECKS
  480. {$ELSE}
  481.   {$C-} // ASSERTIONS
  482.   {$IFDEF GIF_NOSAFETY}
  483.     {$Q-}// OVERFLOWCHECKS
  484.     {$R-}// RANGECHECKS
  485.   {$ENDIF}
  486. {$ENDIF}
  487.  
  488. // Special options for Time2Help parser
  489. {$ifdef TIME2HELP}
  490. {$UNDEF PIXELFORMAT_TOO_SLOW}
  491. {$endif}
  492.  
  493. ////////////////////////////////////////////////////////////////////////////////
  494. //
  495. //          External dependecies
  496. //
  497. ////////////////////////////////////////////////////////////////////////////////
  498. uses
  499.   sysutils,
  500.   Windows,
  501.   Graphics,
  502.   Classes;
  503.  
  504. ////////////////////////////////////////////////////////////////////////////////
  505. //
  506. //          TGIFImage library version
  507. //
  508. ////////////////////////////////////////////////////////////////////////////////
  509. const
  510.   GIFVersion        = $0202;
  511.   GIFVersionMajor   = 2;
  512.   GIFVersionMinor   = 2;
  513.   GIFVersionRelease = 5;
  514.  
  515. ////////////////////////////////////////////////////////////////////////////////
  516. //
  517. //          Misc constants and support types
  518. //
  519. ////////////////////////////////////////////////////////////////////////////////
  520. const
  521.   GIFMaxColors  = 256;          // Max number of colors supported by GIF
  522.                     // Don't bother changing this value!
  523.  
  524.   BitmapAllocationThreshold = 500000;   // Bitmap pixel count limit at which
  525.                     // a newly allocated bitmap will be
  526.                                         // converted to 1 bit format before
  527.                                         // being resized and converted to 8 bit.
  528.  
  529. var
  530. {$IFDEF FAST_AS_HELL}
  531.   GIFDelayExp: integer = 10;        // Delay multiplier in mS.
  532. {$ELSE}
  533.   GIFDelayExp: integer = 12;        // Delay multiplier in mS. Tweaked.
  534. {$ENDIF}
  535.                     // * GIFDelayExp:
  536.                     // The following delay values should all
  537.                                         // be multiplied by this value to
  538.                                         // calculate the effective time (in mS).
  539.                                         // According to the GIF specs, this
  540.                                         // value should be 10.
  541.                                         // Since our paint routines are much
  542.                                         // faster than Mozilla's, you might need
  543.                                         // to increase this value if your
  544.                                         // animations loops too fast. The
  545.                                         // optimal value is impossible to
  546.                                         // determine since it depends on the
  547.                                         // speed of the CPU, the viceo card,
  548.                                         // memory and many other factors.
  549.  
  550.   GIFDefaultDelay: integer = 10;    // * GIFDefaultDelay:
  551.                     // Default animation delay.
  552.                     // This value is used if no GCE is
  553.                                         // defined.
  554.                                         // (10 = 100 mS)
  555.  
  556. {$IFDEF FAST_AS_HELL}
  557.   GIFMinimumDelay: integer = 1;     // Minimum delay (from Mozilla source).
  558.                     // (1 = 10 mS)
  559. {$ELSE}
  560.   GIFMinimumDelay: integer = 3;     // Minimum delay - Tweaked.
  561. {$ENDIF}
  562.                     // * GIFMinimumDelay:
  563.                     // The minumum delay used in the Mozilla
  564.                                         // source is 10mS. This corresponds to a
  565.                                         // value of 1. However, since our paint
  566.                                         // routines are much faster than
  567.                                         // Mozilla's, a value of 3 or 4 gives
  568.                                         // better results.
  569.  
  570.   GIFMaximumDelay: integer = 1000;  // * GIFMaximumDelay:
  571.                     // Maximum delay when painter is running
  572.                     // in main thread (goAsync is not set).
  573.                                         // This value guarantees that a very
  574.                                         // long and slow GIF does not hang the
  575.                                         // system.
  576.                                         // (1000 = 10000 mS = 10 Seconds)
  577.  
  578. type
  579.   TGIFVersion = (gvUnknown, gv87a, gv89a);
  580.   TGIFVersionRec = array[0..2] of AnsiChar;
  581.  
  582. const
  583.   GIFVersions : array[gv87a..gv89a] of TGIFVersionRec = ('87a', '89a');
  584.  
  585. type
  586.   // TGIFImage mostly throws exceptions of type GIFException
  587.   GIFException = class(EInvalidGraphic);
  588.  
  589.   // Severity level as indicated in the Warning methods and the OnWarning event
  590.   TGIFSeverity = (gsInfo, gsWarning, gsError);
  591.  
  592. ////////////////////////////////////////////////////////////////////////////////
  593. //
  594. //          Delphi 2.x support
  595. //
  596. ////////////////////////////////////////////////////////////////////////////////
  597. {$IFDEF VER9x}
  598. // Delphi 2 doesn't support TBitmap.PixelFormat
  599. {$DEFINE PIXELFORMAT_TOO_SLOW}
  600. type
  601.   // TThreadList from Delphi 3 classes.pas
  602.   TThreadList = class
  603.   private
  604.     FList: TList;
  605.     FLock: TRTLCriticalSection;
  606.   public
  607.     constructor Create;
  608.     destructor Destroy; override;
  609.     procedure Add(Item: Pointer);
  610.     procedure Clear;
  611.     function  LockList: TList;
  612.     procedure Remove(Item: Pointer);
  613.     procedure UnlockList;
  614.   end;
  615.  
  616.   // From Delphi 3 sysutils.pas
  617.   EOutOfMemory = class(Exception);
  618.  
  619.   // From Delphi 3 classes.pas
  620.   EOutOfResources = class(EOutOfMemory);
  621.  
  622.   // From Delphi 3 windows.pas
  623.   PMaxLogPalette = ^TMaxLogPalette;
  624.   TMaxLogPalette = packed record
  625.     palVersion: Word;
  626.     palNumEntries: Word;
  627.     palPalEntry: array [Byte] of TPaletteEntry;
  628.   end; { TMaxLogPalette }
  629.  
  630.   // From Delphi 3 graphics.pas. Used by the D3 TGraphic class.
  631.   TProgressStage = (psStarting, psRunning, psEnding);
  632.   TProgressEvent = procedure (Sender: TObject; Stage: TProgressStage;
  633.     PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string) of object;
  634.  
  635.   // From Delphi 3 windows.pas
  636.   PRGBTriple = ^TRGBTriple;
  637. {$ENDIF}
  638.  
  639. ////////////////////////////////////////////////////////////////////////////////
  640. //
  641. //          Forward declarations
  642. //
  643. ////////////////////////////////////////////////////////////////////////////////
  644. type
  645.   TGIFImage = class;
  646.   TGIFSubImage = class;
  647.  
  648. ////////////////////////////////////////////////////////////////////////////////
  649. //
  650. //          TGIFItem
  651. //
  652. ////////////////////////////////////////////////////////////////////////////////
  653.   TGIFItem = class(TPersistent)
  654.   private
  655.     FGIFImage: TGIFImage;
  656.   protected
  657.     function GetVersion: TGIFVersion; virtual;
  658.     procedure Warning(Severity: TGIFSeverity; Message: string); virtual;
  659.   public
  660.     constructor Create(GIFImage: TGIFImage); virtual;
  661.  
  662.     procedure SaveToStream(Stream: TStream); virtual; abstract;
  663.     procedure LoadFromStream(Stream: TStream); virtual; abstract;
  664.     procedure SaveToFile(const Filename: string); virtual;
  665.     procedure LoadFromFile(const Filename: string); virtual;
  666.     property Version: TGIFVersion read GetVersion;
  667.     property Image: TGIFImage read FGIFImage;
  668.   end;
  669.  
  670. ////////////////////////////////////////////////////////////////////////////////
  671. //
  672. //          TGIFList
  673. //
  674. ////////////////////////////////////////////////////////////////////////////////
  675.   TGIFList = class(TPersistent)
  676.   private
  677.     FItems: TList;
  678.     FImage: TGIFImage;
  679.   protected
  680.     function GetItem(Index: Integer): TGIFItem;
  681.     procedure SetItem(Index: Integer; Item: TGIFItem);
  682.     function GetCount: Integer;
  683.     procedure Warning(Severity: TGIFSeverity; Message: string); virtual;
  684.   public
  685.     constructor Create(Image: TGIFImage);
  686.     destructor Destroy; override;
  687.  
  688.     function Add(Item: TGIFItem): Integer;
  689.     procedure Clear;
  690.     procedure Delete(Index: Integer);
  691.     procedure Exchange(Index1, Index2: Integer);
  692.     function First: TGIFItem;
  693.     function IndexOf(Item: TGIFItem): Integer;
  694.     procedure Insert(Index: Integer; Item: TGIFItem);
  695.     function Last: TGIFItem;
  696.     procedure Move(CurIndex, NewIndex: Integer);
  697.     function Remove(Item: TGIFItem): Integer;
  698.     procedure SaveToStream(Stream: TStream); virtual;
  699.     procedure LoadFromStream(Stream: TStream; Parent: TObject); virtual; abstract;
  700.  
  701.     property Items[Index: Integer]: TGIFItem read GetItem write SetItem; default;
  702.     property Count: Integer read GetCount;
  703.     property List: TList read FItems;
  704.     property Image: TGIFImage read FImage;
  705.   end;
  706.  
  707. ////////////////////////////////////////////////////////////////////////////////
  708. //
  709. //          TGIFColorMap
  710. //
  711. ////////////////////////////////////////////////////////////////////////////////
  712.   // One way to do it:
  713.   //  TBaseColor = (bcRed, bcGreen, bcBlue);
  714.   //  TGIFColor = array[bcRed..bcBlue] of BYTE;
  715.   // Another way:
  716.   TGIFColor = packed record
  717.     Red: byte;
  718.     Green: byte;
  719.     Blue: byte;
  720.   end;
  721.  
  722.   TColorMap = packed array[0..GIFMaxColors-1] of TGIFColor;
  723.   PColorMap = ^TColorMap;
  724.  
  725.   TUsageCount = record
  726.     Count       : integer;  // # of pixels using color index
  727.     Index       : integer;  // Color index
  728.   end;
  729.   TColormapHistogram = array[0..255] of TUsageCount;
  730.   TColormapReverse = array[0..255] of byte;
  731.  
  732.   TGIFColorMap = class(TPersistent)
  733.   private
  734.     FColorMap       : PColorMap;
  735.     FCount      : integer;
  736.     FCapacity       : integer;
  737.     FOptimized      : boolean;
  738.   protected
  739.     function GetColor(Index: integer): TColor;
  740.     procedure SetColor(Index: integer; Value: TColor);
  741.     function GetBitsPerPixel: integer;
  742.     function DoOptimize: boolean;
  743.     procedure SetCapacity(Size: integer);
  744.     procedure Warning(Severity: TGIFSeverity; Message: string); virtual; abstract;
  745.     procedure BuildHistogram(var Histogram: TColormapHistogram); virtual; abstract;
  746.     procedure MapImages(var Map: TColormapReverse); virtual; abstract;
  747.  
  748.   public
  749.     constructor Create;
  750.     destructor Destroy; override;
  751.     class function Color2RGB(Color: TColor): TGIFColor;
  752.     class function RGB2Color(Color: TGIFColor): TColor;
  753.     procedure SaveToStream(Stream: TStream);
  754.     procedure LoadFromStream(Stream: TStream; Count: integer);
  755.     procedure Assign(Source: TPersistent); override;
  756.     function IndexOf(Color: TColor): integer;
  757.     function Add(Color: TColor): integer;
  758.     function AddUnique(Color: TColor): integer;
  759.     procedure Delete(Index: integer);
  760.     procedure Clear;
  761.     function Optimize: boolean; virtual; abstract;
  762.     procedure Changed; virtual; abstract;
  763.     procedure ImportPalette(Palette: HPalette);
  764.     procedure ImportColorTable(Pal: pointer; Count: integer);
  765.     procedure ImportDIBColors(Handle: HDC);
  766.     procedure ImportColorMap(Map: TColorMap; Count: integer);
  767.     function ExportPalette: HPalette;
  768.     property Colors[Index: integer]: TColor read GetColor write SetColor; default;
  769.     property Data: PColorMap read FColorMap;
  770.     property Count: integer read FCount;
  771.     property Optimized: boolean read FOptimized write FOptimized;
  772.     property BitsPerPixel: integer read GetBitsPerPixel;
  773.   end;
  774.  
  775. ////////////////////////////////////////////////////////////////////////////////
  776. //
  777. //          TGIFHeader
  778. //
  779. ////////////////////////////////////////////////////////////////////////////////
  780.   TLogicalScreenDescriptor = packed record
  781.     ScreenWidth: word;              { logical screen width }
  782.     ScreenHeight: word;             { logical screen height }
  783.     PackedFields: byte;             { packed fields }
  784.     BackgroundColorIndex: byte;     { index to global color table }
  785.     AspectRatio: byte;              { actual ratio = (AspectRatio + 15) / 64 }
  786.   end;
  787.  
  788.   TGIFHeader = class(TGIFItem)
  789.   private
  790.     FLogicalScreenDescriptor: TLogicalScreenDescriptor;
  791.     FColorMap       : TGIFColorMap;
  792.     procedure Prepare;
  793.   protected
  794.     function GetVersion: TGIFVersion; override;
  795.     function GetBackgroundColor: TColor;
  796.     procedure SetBackgroundColor(Color: TColor);
  797.     procedure SetBackgroundColorIndex(Index: BYTE);
  798.     function GetBitsPerPixel: integer;
  799.     function GetColorResolution: integer;
  800.   public
  801.     constructor Create(GIFImage: TGIFImage); override;
  802.     destructor Destroy; override;
  803.     procedure Assign(Source: TPersistent); override;
  804.     procedure SaveToStream(Stream: TStream); override;
  805.     procedure LoadFromStream(Stream: TStream); override;
  806.     procedure Clear;
  807.     property Version: TGIFVersion read GetVersion;
  808.     property Width: WORD read FLogicalScreenDescriptor.ScreenWidth
  809.                          write FLogicalScreenDescriptor.ScreenWidth;
  810.     property Height: WORD read FLogicalScreenDescriptor.ScreenHeight
  811.                           write FLogicalScreenDescriptor.Screenheight;
  812.     property BackgroundColorIndex: BYTE read FLogicalScreenDescriptor.BackgroundColorIndex
  813.                                         write SetBackgroundColorIndex;
  814.     property BackgroundColor: TColor read GetBackgroundColor
  815.                                      write SetBackgroundColor;
  816.     property AspectRatio: BYTE read FLogicalScreenDescriptor.AspectRatio
  817.                                write FLogicalScreenDescriptor.AspectRatio;
  818.     property ColorMap: TGIFColorMap read FColorMap;
  819.     property BitsPerPixel: integer read GetBitsPerPixel;
  820.     property ColorResolution: integer read GetColorResolution;
  821.   end;
  822.  
  823. ////////////////////////////////////////////////////////////////////////////////
  824. //
  825. //                      TGIFExtension
  826. //
  827. ////////////////////////////////////////////////////////////////////////////////
  828.   TGIFExtensionType = BYTE;
  829.   TGIFExtension = class;
  830.   TGIFExtensionClass = class of TGIFExtension;
  831.  
  832.   TGIFGraphicControlExtension = class;
  833.  
  834.   TGIFExtension = class(TGIFItem)
  835.   private
  836.     FSubImage: TGIFSubImage;
  837.   protected
  838.     function GetExtensionType: TGIFExtensionType; virtual; abstract;
  839.     function GetVersion: TGIFVersion; override;
  840.     function DoReadFromStream(Stream: TStream): TGIFExtensionType;
  841.     class procedure RegisterExtension(elabel: BYTE; eClass: TGIFExtensionClass);
  842.     class function FindExtension(Stream: TStream): TGIFExtensionClass;
  843.     class function FindSubExtension(Stream: TStream): TGIFExtensionClass; virtual;
  844.   public
  845.      // Ignore compiler warning about hiding base class constructor
  846.     constructor Create(ASubImage: TGIFSubImage); {$IFDEF VER12_PLUS} reintroduce; {$ENDIF} virtual;
  847.     destructor Destroy; override;
  848.     procedure SaveToStream(Stream: TStream); override;
  849.     procedure LoadFromStream(Stream: TStream); override;
  850.     property ExtensionType: TGIFExtensionType read GetExtensionType;
  851.     property SubImage: TGIFSubImage read FSubImage;
  852.   end;
  853.  
  854. ////////////////////////////////////////////////////////////////////////////////
  855. //
  856. //          TGIFSubImage
  857. //
  858. ////////////////////////////////////////////////////////////////////////////////
  859.   TGIFExtensionList = class(TGIFList)
  860.   protected
  861.     function GetExtension(Index: Integer): TGIFExtension;
  862.     procedure SetExtension(Index: Integer; Extension: TGIFExtension);
  863.   public
  864.     procedure LoadFromStream(Stream: TStream; Parent: TObject); override;
  865.     property Extensions[Index: Integer]: TGIFExtension read GetExtension write SetExtension; default;
  866.   end;
  867.  
  868.   TImageDescriptor = packed record
  869.     Separator: byte;    { fixed value of ImageSeparator }
  870.     Left: word;     { Column in pixels in respect to left edge of logical screen }
  871.     Top: word;      { row in pixels in respect to top of logical screen }
  872.     Width: word;    { width of image in pixels }
  873.     Height: word;   { height of image in pixels }
  874.     PackedFields: byte; { Bit fields }
  875.   end;
  876.  
  877.   TGIFSubImage = class(TGIFItem)
  878.   private
  879.     FBitmap     : TBitmap;
  880.     FMask       : HBitmap;
  881.     FNeedMask       : boolean;
  882.     FLocalPalette   : HPalette;
  883.     FData       : PAnsiChar;
  884.     FDataSize       : integer;
  885.     FColorMap       : TGIFColorMap;
  886.     FImageDescriptor    : TImageDescriptor;
  887.     FExtensions     : TGIFExtensionList;
  888.     FTransparent    : boolean;
  889.     FGCE        : TGIFGraphicControlExtension;
  890.     procedure Prepare;
  891.     procedure Compress(Stream: TStream);
  892.     procedure Decompress(Stream: TStream);
  893.   protected
  894.     function GetVersion: TGIFVersion; override;
  895.     function GetInterlaced: boolean;
  896.     procedure SetInterlaced(Value: boolean);
  897.     function GetColorResolution: integer;
  898.     function GetBitsPerPixel: integer;
  899.     procedure AssignTo(Dest: TPersistent); override;
  900.     function DoGetBitmap: TBitmap;
  901.     function DoGetDitherBitmap: TBitmap;
  902.     function GetBitmap: TBitmap;
  903.     procedure SetBitmap(Value: TBitmap);
  904.     procedure FreeMask;
  905.     function GetEmpty: Boolean;
  906.     function GetPalette: HPALETTE;
  907.     procedure SetPalette(Value: HPalette);
  908.     function GetActiveColorMap: TGIFColorMap;
  909.     function GetBoundsRect: TRect;
  910.     procedure SetBoundsRect(const Value: TRect);
  911.     procedure DoSetBounds(ALeft, ATop, AWidth, AHeight: integer);
  912.     function GetClientRect: TRect;
  913.     function GetPixel(x, y: integer): BYTE;
  914. // 2006.10.09 ->
  915.     procedure SetPixel(x, y: integer; Value: BYTE);
  916. // 2006.10.09 <-
  917.     function GetScanline(y: integer): pointer;
  918.     procedure NewBitmap;
  919.     procedure FreeBitmap;
  920.     procedure NewImage;
  921.     procedure FreeImage;
  922.     procedure NeedImage;
  923.     function ScaleRect(DestRect: TRect): TRect;
  924.     function HasMask: boolean;
  925.     function GetBounds(Index: integer): WORD;
  926.     procedure SetBounds(Index: integer; Value: WORD);
  927.     function GetHasBitmap: boolean;
  928.     procedure SetHasBitmap(Value: boolean);
  929.   public
  930.     constructor Create(GIFImage: TGIFImage); override;
  931.     destructor Destroy; override;
  932.     procedure Clear;
  933.     procedure SaveToStream(Stream: TStream); override;
  934.     procedure LoadFromStream(Stream: TStream); override;
  935.     procedure Assign(Source: TPersistent); override;
  936.     procedure Draw(ACanvas: TCanvas; const Rect: TRect;
  937.       DoTransparent, DoTile: boolean);
  938.     procedure StretchDraw(ACanvas: TCanvas; const Rect: TRect;
  939.       DoTransparent, DoTile: boolean);
  940.     procedure Crop;
  941.     procedure Merge(Previous: TGIFSubImage);
  942.     property HasBitmap: boolean read GetHasBitmap write SetHasBitmap;
  943.     property Left: WORD index 1 read GetBounds write SetBounds;
  944.     property Top: WORD index 2 read GetBounds write SetBounds;
  945.     property Width: WORD index 3 read GetBounds write SetBounds;
  946.     property Height: WORD index 4 read GetBounds write SetBounds;
  947.     property BoundsRect: TRect read GetBoundsRect write SetBoundsRect;
  948.     property ClientRect: TRect read GetClientRect;
  949.     property Interlaced: boolean read GetInterlaced write SetInterlaced;
  950.     property ColorMap: TGIFColorMap read FColorMap;
  951.     property ActiveColorMap: TGIFColorMap read GetActiveColorMap;
  952.     property Data: PAnsiChar read FData;
  953.     property DataSize: integer read FDataSize;
  954.     property Extensions: TGIFExtensionList read FExtensions;
  955.     property Version: TGIFVersion read GetVersion;
  956.     property ColorResolution: integer read GetColorResolution;
  957.     property BitsPerPixel: integer read GetBitsPerPixel;
  958.     property Bitmap: TBitmap read GetBitmap write SetBitmap;
  959.     property Mask: HBitmap read FMask;
  960.     property Palette: HPALETTE read GetPalette write SetPalette;
  961.     property Empty: boolean read GetEmpty;
  962.     property Transparent: boolean read FTransparent;
  963.     property GraphicControlExtension: TGIFGraphicControlExtension read FGCE;
  964. // 2006.10.09 ->
  965. //  property Pixels[x, y: integer]: BYTE read GetPixel;
  966.     property Pixels[x, y: integer]: BYTE read GetPixel write SetPixel;
  967. // 2006.10.09 <-
  968.     property Scanline[y: integer]: pointer read GetScanline;
  969.   end;
  970.  
  971. ////////////////////////////////////////////////////////////////////////////////
  972. //
  973. //                      TGIFTrailer
  974. //
  975. ////////////////////////////////////////////////////////////////////////////////
  976.   TGIFTrailer = class(TGIFItem)
  977.     procedure SaveToStream(Stream: TStream); override;
  978.     procedure LoadFromStream(Stream: TStream); override;
  979.   end;
  980.  
  981. ////////////////////////////////////////////////////////////////////////////////
  982. //
  983. //                      TGIFGraphicControlExtension
  984. //
  985. ////////////////////////////////////////////////////////////////////////////////
  986.   // Graphic Control Extension block a.k.a GCE
  987.   TGIFGCERec = packed record
  988.     BlockSize: byte;         { should be 4 }
  989.     PackedFields: Byte;
  990.     DelayTime: Word;         { in centiseconds }
  991.     TransparentColorIndex: Byte;
  992.     Terminator: Byte;
  993.   end;
  994.  
  995.   TDisposalMethod = (dmNone, dmNoDisposal, dmBackground, dmPrevious);
  996.  
  997.   TGIFGraphicControlExtension = class(TGIFExtension)
  998.   private
  999.     FGCExtension: TGIFGCERec;
  1000.   protected
  1001.     function GetExtensionType: TGIFExtensionType; override;
  1002.     function GetTransparent: boolean;
  1003.     procedure SetTransparent(Value: boolean);
  1004.     function GetTransparentColor: TColor;
  1005.     procedure SetTransparentColor(Color: TColor);
  1006.     function GetTransparentColorIndex: BYTE;
  1007.     procedure SetTransparentColorIndex(Value: BYTE);
  1008.     function GetDelay: WORD;
  1009.     procedure SetDelay(Value: WORD);
  1010.     function GetUserInput: boolean;
  1011.     procedure SetUserInput(Value: boolean);
  1012.     function GetDisposal: TDisposalMethod;
  1013.     procedure SetDisposal(Value: TDisposalMethod);
  1014.  
  1015.   public
  1016.     constructor Create(ASubImage: TGIFSubImage); override;
  1017.     destructor Destroy; override;
  1018.     procedure SaveToStream(Stream: TStream); override;
  1019.     procedure LoadFromStream(Stream: TStream); override;
  1020.     property Delay: WORD read GetDelay write SetDelay;
  1021.     property Transparent: boolean read GetTransparent write SetTransparent;
  1022.     property TransparentColorIndex: BYTE read GetTransparentColorIndex
  1023.                                             write SetTransparentColorIndex;
  1024.     property TransparentColor: TColor read GetTransparentColor write SetTransparentColor;
  1025.     property UserInput: boolean read GetUserInput write SetUserInput;
  1026.     property Disposal: TDisposalMethod read GetDisposal write SetDisposal;
  1027.   end;
  1028.  
  1029. ////////////////////////////////////////////////////////////////////////////////
  1030. //
  1031. //                      TGIFTextExtension
  1032. //
  1033. ////////////////////////////////////////////////////////////////////////////////
  1034.   TGIFPlainTextExtensionRec = packed record
  1035.     BlockSize: byte;         { should be 12 }
  1036.     Left, Top, Width, Height: Word;
  1037.     CellWidth, CellHeight: Byte;
  1038.     TextFGColorIndex,
  1039.     TextBGColorIndex: Byte;
  1040.   end;
  1041.  
  1042.   TGIFTextExtension = class(TGIFExtension)
  1043.   private
  1044.     FText       : TStrings;
  1045.     FPlainTextExtension : TGIFPlainTextExtensionRec;
  1046.   protected
  1047.     function GetExtensionType: TGIFExtensionType; override;
  1048.     function GetForegroundColor: TColor;
  1049.     procedure SetForegroundColor(Color: TColor);
  1050.     function GetBackgroundColor: TColor;
  1051.     procedure SetBackgroundColor(Color: TColor);
  1052.     function GetBounds(Index: integer): WORD;
  1053.     procedure SetBounds(Index: integer; Value: WORD);
  1054.     function GetCharWidthHeight(Index: integer): BYTE;
  1055.     procedure SetCharWidthHeight(Index: integer; Value: BYTE);
  1056.     function GetColorIndex(Index: integer): BYTE;
  1057.     procedure SetColorIndex(Index: integer; Value: BYTE);
  1058.   public
  1059.     constructor Create(ASubImage: TGIFSubImage); override;
  1060.     destructor Destroy; override;
  1061.     procedure SaveToStream(Stream: TStream); override;
  1062.     procedure LoadFromStream(Stream: TStream); override;
  1063.     property Left: WORD index 1 read GetBounds write SetBounds;
  1064.     property Top: WORD index 2 read GetBounds write SetBounds;
  1065.     property GridWidth: WORD index 3 read GetBounds write SetBounds;
  1066.     property GridHeight: WORD index 4 read GetBounds write SetBounds;
  1067.     property CharWidth: BYTE index 1 read GetCharWidthHeight write SetCharWidthHeight;
  1068.     property CharHeight: BYTE index 2 read GetCharWidthHeight write SetCharWidthHeight;
  1069.     property ForegroundColorIndex: BYTE index 1 read GetColorIndex write SetColorIndex;
  1070.     property ForegroundColor: TColor read GetForegroundColor;
  1071.     property BackgroundColorIndex: BYTE  index 2 read GetColorIndex write SetColorIndex;
  1072.     property BackgroundColor: TColor read GetBackgroundColor;
  1073.     property Text: TStrings read FText write FText;
  1074.   end;
  1075.  
  1076. ////////////////////////////////////////////////////////////////////////////////
  1077. //
  1078. //                      TGIFCommentExtension
  1079. //
  1080. ////////////////////////////////////////////////////////////////////////////////
  1081.   TGIFCommentExtension = class(TGIFExtension)
  1082.   private
  1083.     FText       : TStrings;
  1084.   protected
  1085.     function GetExtensionType: TGIFExtensionType; override;
  1086.   public
  1087.     constructor Create(ASubImage: TGIFSubImage); override;
  1088.     destructor Destroy; override;
  1089.     procedure SaveToStream(Stream: TStream); override;
  1090.     procedure LoadFromStream(Stream: TStream); override;
  1091.     property Text: TStrings read FText;
  1092.   end;
  1093.  
  1094. ////////////////////////////////////////////////////////////////////////////////
  1095. //
  1096. //                      TGIFApplicationExtension
  1097. //
  1098. ////////////////////////////////////////////////////////////////////////////////
  1099.   TGIFIdentifierCode = array[0..7] of AnsiChar;
  1100.   TGIFAuthenticationCode = array[0..2] of AnsiChar;
  1101.   TGIFApplicationRec = packed record
  1102.     Identifier      : TGIFIdentifierCode;
  1103.     Authentication  : TGIFAuthenticationCode;
  1104.   end;
  1105.  
  1106.   TGIFApplicationExtension = class;
  1107.   TGIFAppExtensionClass = class of TGIFApplicationExtension;
  1108.  
  1109.   TGIFApplicationExtension = class(TGIFExtension)
  1110.   private
  1111.     FIdent      : TGIFApplicationRec;
  1112.     function GetAuthentication: AnsiString;
  1113.     function GetIdentifier: AnsiString;
  1114.   protected
  1115.     function GetExtensionType: TGIFExtensionType; override;
  1116.     procedure SetAuthentication(const Value: AnsiString);
  1117.     procedure SetIdentifier(const Value: AnsiString);
  1118.     procedure SaveData(Stream: TStream); virtual; abstract;
  1119.     procedure LoadData(Stream: TStream); virtual; abstract;
  1120.   public
  1121.     constructor Create(ASubImage: TGIFSubImage); override;
  1122.     destructor Destroy; override;
  1123.     procedure SaveToStream(Stream: TStream); override;
  1124.     procedure LoadFromStream(Stream: TStream); override;
  1125.     class procedure RegisterExtension(eIdent: TGIFApplicationRec; eClass: TGIFAppExtensionClass);
  1126.     class function FindSubExtension(Stream: TStream): TGIFExtensionClass; override;
  1127.     property Identifier: AnsiString read GetIdentifier write SetIdentifier;
  1128.     property Authentication: AnsiString read GetAuthentication write SetAuthentication;
  1129.   end;
  1130.  
  1131. ////////////////////////////////////////////////////////////////////////////////
  1132. //
  1133. //                      TGIFUnknownAppExtension
  1134. //
  1135. ////////////////////////////////////////////////////////////////////////////////
  1136.   TGIFBlock = class(TObject)
  1137.   private
  1138.     FSize       : BYTE;
  1139.     FData       : pointer;
  1140.   public
  1141.     constructor Create(ASize: integer);
  1142.     destructor Destroy; override;
  1143.     procedure SaveToStream(Stream: TStream);
  1144.     procedure LoadFromStream(Stream: TStream);
  1145.     property Size: BYTE read FSize;
  1146.     property Data: pointer read FData;
  1147.   end;
  1148.  
  1149.   TGIFUnknownAppExtension = class(TGIFApplicationExtension)
  1150.   private
  1151.     FBlocks     : TList;
  1152.   protected
  1153.     procedure SaveData(Stream: TStream); override;
  1154.     procedure LoadData(Stream: TStream); override;
  1155.   public
  1156.     constructor Create(ASubImage: TGIFSubImage); override;
  1157.     destructor Destroy; override;
  1158.     property Blocks: TList read FBlocks;
  1159.   end;
  1160.  
  1161. ////////////////////////////////////////////////////////////////////////////////
  1162. //
  1163. //                      TGIFAppExtNSLoop
  1164. //
  1165. ////////////////////////////////////////////////////////////////////////////////
  1166.   TGIFAppExtNSLoop = class(TGIFApplicationExtension)
  1167.   private
  1168.     FLoops      : WORD;
  1169.     FBufferSize     : DWORD;
  1170.   protected
  1171.     procedure SaveData(Stream: TStream); override;
  1172.     procedure LoadData(Stream: TStream); override;
  1173.   public
  1174.     constructor Create(ASubImage: TGIFSubImage); override;
  1175.     property Loops: WORD read FLoops write FLoops;
  1176.     property BufferSize: DWORD read FBufferSize write FBufferSize;
  1177.   end;
  1178.  
  1179. ////////////////////////////////////////////////////////////////////////////////
  1180. //
  1181. //                      TGIFImage
  1182. //
  1183. ////////////////////////////////////////////////////////////////////////////////
  1184.   TGIFImageList = class(TGIFList)
  1185.   protected
  1186.     function GetImage(Index: Integer): TGIFSubImage;
  1187.     procedure SetImage(Index: Integer; SubImage: TGIFSubImage);
  1188.   public
  1189.     procedure LoadFromStream(Stream: TStream; Parent: TObject); override;
  1190.     procedure SaveToStream(Stream: TStream); override;
  1191.     property SubImages[Index: Integer]: TGIFSubImage read GetImage write SetImage; default;
  1192.   end;
  1193.  
  1194.   // Compression algorithms
  1195.   TGIFCompression =
  1196.     (gcLZW,         // Normal LZW compression
  1197.      gcRLE          // GIF compatible RLE compression
  1198.     );
  1199.  
  1200.   // Color reduction methods
  1201.   TColorReduction =
  1202.     (rmNone,            // Do not perform color reduction
  1203.      rmWindows20,       // Reduce to the Windows 20 color system palette
  1204.      rmWindows256,      // Reduce to the Windows 256 color halftone palette (Only works in 256 color display mode)
  1205.      rmWindowsGray,     // Reduce to the Windows 4 grayscale colors
  1206.      rmMonochrome,      // Reduce to a black/white monochrome palette
  1207.      rmGrayScale,       // Reduce to a uniform 256 shade grayscale palette
  1208.      rmNetscape,        // Reduce to the Netscape 216 color palette
  1209.      rmQuantize,        // Reduce to optimal 2^n color palette
  1210.      rmQuantizeWindows,     // Reduce to optimal 256 color windows palette
  1211.      rmPalette          // Reduce to custom palette
  1212.     );
  1213.   TDitherMode =
  1214.     (dmNearest,         // Nearest color matching w/o error correction
  1215.      dmFloydSteinberg,      // Floyd Steinberg Error Diffusion dithering
  1216.      dmStucki,          // Stucki Error Diffusion dithering
  1217.      dmSierra,          // Sierra Error Diffusion dithering
  1218.      dmJaJuNI,          // Jarvis, Judice & Ninke Error Diffusion dithering
  1219.      dmSteveArche,      // Stevenson & Arche Error Diffusion dithering
  1220.      dmBurkes           // Burkes Error Diffusion dithering
  1221.      // dmOrdered,      // Ordered dither
  1222.     );
  1223.  
  1224.   // Optimization options
  1225.   TGIFOptimizeOption =
  1226.     (ooCrop,            // Crop animated GIF frames
  1227.      ooMerge,           // Merge pixels of same color
  1228.      ooCleanup,         // Remove comments and application extensions
  1229.      ooColorMap,        // Sort color map by usage and remove unused entries
  1230.      ooReduceColors     // Reduce color depth ***NOT IMPLEMENTED***
  1231.     );
  1232.   TGIFOptimizeOptions = set of TGIFOptimizeOption;
  1233.  
  1234.   TGIFDrawOption =
  1235.     (goAsync,           // Asyncronous draws (paint in thread)
  1236.      goTransparent,     // Transparent draws
  1237.      goAnimate,         // Animate draws
  1238.      goLoop,            // Loop animations
  1239.      goLoopContinously,     // Ignore loop count and loop forever
  1240.      goValidateCanvas,      // Validate canvas in threaded paint ***NOT IMPLEMENTED***
  1241.      goDirectDraw,      // Draw() directly on canvas
  1242.      goClearOnLoop,     // Clear animation on loop
  1243.      goTile,            // Tiled display
  1244.      goDither,          // Dither to Netscape palette
  1245.      goAutoDither       // Only dither on 256 color systems
  1246.     );
  1247.   TGIFDrawOptions = set of TGIFDrawOption;
  1248.   // Note: if goAsync is not set then goDirectDraw should be set. Otherwise
  1249.   // the image will not be displayed.
  1250.  
  1251.   PGIFPainter = ^TGIFPainter;
  1252.  
  1253.   TGIFPainter = class(TThread)
  1254.   private
  1255.     FImage      : TGIFImage;    // The TGIFImage that owns this painter
  1256.     FCanvas     : TCanvas;  // Destination canvas
  1257.     FRect       : TRect;    // Destination rect
  1258.     FDrawOptions    : TGIFDrawOptions;// Paint options
  1259.     FAnimationSpeed : integer;  // Animation speed %
  1260.     FActiveImage    : integer;  // Current frame
  1261.     Disposal        ,       // Used by synchronized paint
  1262.     OldDisposal     : TDisposalMethod;// Used by synchronized paint
  1263.     BackupBuffer    : TBitmap;  // Used by synchronized paint
  1264.     FrameBuffer     : TBitmap;  // Used by synchronized paint
  1265.     Background      : TBitmap;  // Used by synchronized paint
  1266.     ValidateDC      : HDC;
  1267.     DoRestart       : boolean;  // Flag used to restart animation
  1268.     FStarted        : boolean;  // Flag used to signal start of paint
  1269.     PainterRef      : PGIFPainter;  // Pointer to var referencing painter
  1270.     FEventHandle    : THandle;  // Animation delay event
  1271.     ExceptObject    : Exception;    // Eaten exception
  1272.     ExceptAddress   : pointer;  // Eaten exceptions address
  1273.     FEvent      : TNotifyEvent; // Used by synchronized events
  1274.     FOnStartPaint   : TNotifyEvent;
  1275.     FOnPaint        : TNotifyEvent;
  1276.     FOnAfterPaint   : TNotifyEvent;
  1277.     FOnLoop     : TNotifyEvent;
  1278.     FOnEndPaint     : TNotifyEvent;
  1279.     procedure DoOnTerminate(Sender: TObject);// Sync. shutdown procedure
  1280.     procedure DoSynchronize(Method: TThreadMethod);// Conditional sync stub
  1281. {$ifdef SERIALIZE_RENDER}
  1282.     procedure PrefetchBitmap;       // Sync. bitmap prefetch
  1283. {$endif}
  1284.     procedure DoPaintFrame;     // Sync. buffered paint procedure
  1285.     procedure DoPaint;          // Sync. paint procedure
  1286.     procedure DoEvent;
  1287.     procedure SetActiveImage(const Value: integer);// Sync. event procedure
  1288.   protected
  1289.     procedure Execute; override;
  1290.     procedure SetAnimationSpeed(Value: integer);
  1291.   public
  1292.     constructor Create(AImage: TGIFImage; ACanvas: TCanvas; ARect: TRect;
  1293.       Options: TGIFDrawOptions);
  1294.     constructor CreateRef(Painter: PGIFPainter; AImage: TGIFImage; ACanvas: TCanvas; ARect: TRect;
  1295.       Options: TGIFDrawOptions);
  1296.     destructor Destroy; override;
  1297.     procedure Start;
  1298.     procedure Stop;
  1299.     procedure Restart;
  1300.     property Image: TGIFImage read FImage;
  1301.     property Canvas: TCanvas read FCanvas;
  1302.     property Rect: TRect read FRect write FRect;
  1303.     property DrawOptions: TGIFDrawOptions read FDrawOptions write FDrawOptions;
  1304.     property AnimationSpeed: integer read FAnimationSpeed write SetAnimationSpeed;
  1305.     property Started: boolean read FStarted;
  1306.     property ActiveImage: integer read FActiveImage write SetActiveImage;
  1307.     property OnStartPaint: TNotifyEvent read FOnStartPaint write FOnStartPaint;
  1308.     property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
  1309.     property OnAfterPaint: TNotifyEvent read FOnAfterPaint write FOnAfterPaint;
  1310.     property OnLoop: TNotifyEvent read FOnLoop write FOnLoop;
  1311.     property OnEndPaint : TNotifyEvent read FOnEndPaint  write FOnEndPaint  ;
  1312.     property EventHandle: THandle read FEventHandle;
  1313.   end;
  1314.  
  1315.   TGIFWarning = procedure(Sender: TObject; Severity: TGIFSeverity; Message: string) of object;
  1316.  
  1317.   TGIFImage = class(TGraphic)
  1318.   private
  1319.     IsDrawing       : Boolean;
  1320.     IsInsideGetPalette  : boolean;
  1321.     FImages     : TGIFImageList;
  1322.     FHeader     : TGIFHeader;
  1323.     FGlobalPalette  : HPalette;
  1324.     FPainters       : TThreadList;
  1325.     FDrawOptions    : TGIFDrawOptions;
  1326.     FColorReduction : TColorReduction;
  1327.     FReductionBits  : integer;
  1328.     FDitherMode     : TDitherMode;
  1329.     FCompression    : TGIFCompression;
  1330.     FOnWarning      : TGIFWarning;
  1331.     FBitmap     : TBitmap;
  1332.     FDrawPainter    : TGIFPainter;
  1333.     FThreadPriority : TThreadPriority;
  1334.     FAnimationSpeed : integer;
  1335.     FForceFrame: Integer;  // 2004.03.09
  1336.     FDrawBackgroundColor: TColor;
  1337.     FOnStartPaint   : TNotifyEvent;
  1338.     FOnPaint        : TNotifyEvent;
  1339.     FOnAfterPaint   : TNotifyEvent;
  1340.     FOnLoop     : TNotifyEvent;
  1341.     FOnEndPaint     : TNotifyEvent;
  1342. {$IFDEF VER9x}
  1343.     FPaletteModified    : Boolean;
  1344.     FOnProgress     : TProgressEvent;
  1345. {$ENDIF}
  1346.     function GetAnimate: Boolean;  // 2002.07.07
  1347.     procedure SetAnimate(const Value: Boolean);  // 2002.07.07
  1348.     procedure SetForceFrame(const Value: Integer);  // 2004.03.09
  1349.   protected
  1350.     // Obsolete: procedure Changed(Sender: TObject); {$IFDEF VER9x} virtual; {$ELSE} override; {$ENDIF}
  1351.     function GetHeight: Integer; override;
  1352.     procedure SetHeight(Value: Integer); override;
  1353.     function GetWidth: Integer; override;
  1354.     procedure SetWidth(Value: Integer); override;
  1355.     procedure AssignTo(Dest: TPersistent); override;
  1356.     function InternalPaint(Painter: PGIFPainter; ACanvas: TCanvas; const Rect: TRect; Options: TGIFDrawOptions): TGIFPainter;
  1357.     procedure Draw(ACanvas: TCanvas; const Rect: TRect); override;
  1358.     function Equals(Graphic: TGraphic): Boolean; override;
  1359.     function GetPalette: HPALETTE; {$IFDEF VER9x} virtual; {$ELSE} override; {$ENDIF}
  1360.     procedure SetPalette(Value: HPalette); {$IFDEF VER9x} virtual; {$ELSE} override; {$ENDIF}
  1361.     function GetEmpty: Boolean; override;
  1362.     procedure WriteData(Stream: TStream); override;
  1363.     function GetIsTransparent: Boolean;
  1364.     function GetVersion: TGIFVersion;
  1365.     function GetColorResolution: integer;
  1366.     function GetBitsPerPixel: integer;
  1367.     function GetBackgroundColorIndex: BYTE;
  1368.     procedure SetBackgroundColorIndex(const Value: BYTE);
  1369.     function GetBackgroundColor: TColor;
  1370.     procedure SetBackgroundColor(const Value: TColor);
  1371.     function GetAspectRatio: BYTE;
  1372.     procedure SetAspectRatio(const Value: BYTE);
  1373.     procedure SetDrawOptions(Value: TGIFDrawOptions);
  1374.     procedure SetAnimationSpeed(Value: integer);
  1375.     procedure SetReductionBits(Value: integer);
  1376.     procedure NewImage;
  1377.     function GetBitmap: TBitmap;
  1378.     function NewBitmap: TBitmap;
  1379.     procedure FreeBitmap;
  1380.     function GetColorMap: TGIFColorMap;
  1381.     function GetDoDither: boolean;
  1382.     property DrawPainter: TGIFPainter read FDrawPainter; // Extremely volatile
  1383.     property DoDither: boolean read GetDoDither;
  1384. {$IFDEF VER9x}
  1385.     procedure Progress(Sender: TObject; Stage: TProgressStage;
  1386.       PercentDone: Byte;  RedrawNow: Boolean; const R: TRect; const Msg: string); dynamic;
  1387. {$ENDIF}
  1388. {$IFDEF FIXHEADER_WIDTHHEIGHT_SILENT}
  1389.     procedure FixHeaderWidthHeight;  // 2006.07.09
  1390. {$ENDIF}
  1391.   public
  1392.     constructor Create; override;
  1393.     destructor Destroy; override;
  1394.     procedure SaveToStream(Stream: TStream); override;
  1395.     procedure LoadFromStream(Stream: TStream); override;
  1396.     procedure LoadFromResourceName(Instance: THandle; const ResName: String);  // 2002.07.07
  1397.     function Add(Source: TPersistent): integer;
  1398.     procedure Pack;
  1399.     procedure OptimizeColorMap;
  1400.     procedure Optimize(Options: TGIFOptimizeOptions;
  1401.       ColorReduction: TColorReduction; DitherMode: TDitherMode;
  1402.       ReductionBits: integer);
  1403.     procedure Clear;
  1404.     procedure StopDraw;
  1405.     function Paint(ACanvas: TCanvas; const Rect: TRect; Options: TGIFDrawOptions): TGIFPainter;
  1406.     procedure PaintStart;
  1407.     procedure PaintPause;
  1408.     procedure PaintStop;
  1409.     procedure PaintResume;
  1410.     procedure PaintRestart;
  1411.     procedure Warning(Sender: TObject; Severity: TGIFSeverity; Message: string); virtual;
  1412.     procedure Assign(Source: TPersistent); override;
  1413.     procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle;
  1414.       APalette: HPALETTE); override;
  1415.     procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
  1416.       var APalette: HPALETTE); override;
  1417.     property GlobalColorMap: TGIFColorMap read GetColorMap;
  1418.     property Version: TGIFVersion read GetVersion;
  1419.     property Images: TGIFImageList read FImages;
  1420.     property ColorResolution: integer read GetColorResolution;
  1421.     property BitsPerPixel: integer read GetBitsPerPixel;
  1422.     property BackgroundColorIndex: BYTE read GetBackgroundColorIndex write SetBackgroundColorIndex;
  1423.     property BackgroundColor: TColor read GetBackgroundColor write SetBackgroundColor;
  1424.     property AspectRatio: BYTE read GetAspectRatio write SetAspectRatio;
  1425.     property Header: TGIFHeader read FHeader; // ***OBSOLETE***
  1426.     property IsTransparent: boolean read GetIsTransparent;
  1427.     property DrawOptions: TGIFDrawOptions read FDrawOptions write SetDrawOptions;
  1428.     property DrawBackgroundColor: TColor read FDrawBackgroundColor write FDrawBackgroundColor;
  1429.     property ColorReduction: TColorReduction read FColorReduction write FColorReduction;
  1430.     property ReductionBits: integer read FReductionBits write SetReductionBits;
  1431.     property DitherMode: TDitherMode read FDitherMode write FDitherMode;
  1432.     property Compression: TGIFCompression read FCompression write FCompression;
  1433.     property AnimationSpeed: integer read FAnimationSpeed write SetAnimationSpeed;
  1434.     property Animate: Boolean read GetAnimate write SetAnimate;  // 2002.07.07
  1435.     property ForceFrame: Integer read FForceFrame write SetForceFrame;  // 2004.03.09
  1436.     property Painters: TThreadList read FPainters;
  1437.     property ThreadPriority: TThreadPriority read FThreadPriority write FThreadPriority;
  1438.     property Bitmap: TBitmap read GetBitmap; // Volatile - beware!
  1439.     property OnWarning: TGIFWarning read FOnWarning write FOnWarning;
  1440.     property OnStartPaint: TNotifyEvent read FOnStartPaint write FOnStartPaint;
  1441.     property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
  1442.     property OnAfterPaint: TNotifyEvent read FOnAfterPaint write FOnAfterPaint;
  1443.     property OnLoop: TNotifyEvent read FOnLoop write FOnLoop;
  1444.     property OnEndPaint : TNotifyEvent read FOnEndPaint  write FOnEndPaint  ;
  1445. {$IFDEF VER9x}
  1446.     property Palette: HPALETTE read GetPalette write SetPalette;
  1447.     property PaletteModified: Boolean read FPaletteModified write FPaletteModified;
  1448.     property OnProgress: TProgressEvent read FOnProgress write FOnProgress;
  1449. {$ENDIF}
  1450.   end;
  1451.  
  1452. ////////////////////////////////////////////////////////////////////////////////
  1453. //
  1454. //                      Utility routines
  1455. //
  1456. ////////////////////////////////////////////////////////////////////////////////
  1457.   // WebPalette creates a 216 color uniform palette a.k.a. the Netscape Palette
  1458.   function WebPalette: HPalette;
  1459.  
  1460.   // ReduceColors
  1461.   // Map colors in a bitmap to their nearest representation in a palette using
  1462.   // the methods specified by the ColorReduction and DitherMode parameters.
  1463.   // The ReductionBits parameter specifies the desired number of colors (bits
  1464.   // per pixel) when the reduction method is rmQuantize. The CustomPalette
  1465.   // specifies the palette when the rmPalette reduction method is used.
  1466.   function ReduceColors(Bitmap: TBitmap; ColorReduction: TColorReduction;
  1467.     DitherMode: TDitherMode; ReductionBits: integer; CustomPalette: hPalette): TBitmap;
  1468.  
  1469.   // CreateOptimizedPaletteFromManyBitmaps
  1470.   //: Performs Color Quantization on multiple bitmaps.
  1471.   // The Bitmaps parameter is a list of bitmaps. Returns an optimized palette.
  1472.   function CreateOptimizedPaletteFromManyBitmaps(Bitmaps: TList; Colors, ColorBits: integer;
  1473.     Windows: boolean): hPalette;
  1474.  
  1475. {$IFDEF VER9x}
  1476.   // From Delphi 3 graphics.pas
  1477. type
  1478.   TPixelFormat = (pfDevice, pf1bit, pf4bit, pf8bit, pf15bit, pf16bit, pf24bit, pf32bit, pfCustom);
  1479. {$ENDIF}
  1480.  
  1481.   procedure InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: Integer;
  1482.     var ImageSize: longInt; PixelFormat: TPixelFormat);
  1483.   function InternalGetDIB(Bitmap: HBITMAP; Palette: HPALETTE;
  1484.    var BitmapInfo; var Bits; PixelFormat: TPixelFormat): Boolean;
  1485.  
  1486. ////////////////////////////////////////////////////////////////////////////////
  1487. //
  1488. //                      Global variables
  1489. //
  1490. ////////////////////////////////////////////////////////////////////////////////
  1491. // GIF Clipboard format identifier for use by LoadFromClipboardFormat and
  1492. // SaveToClipboardFormat.
  1493. // Set in Initialization section.
  1494. var
  1495.   CF_GIF: WORD;
  1496.  
  1497. ////////////////////////////////////////////////////////////////////////////////
  1498. //
  1499. //                      Library defaults
  1500. //
  1501. ////////////////////////////////////////////////////////////////////////////////
  1502. var
  1503.   //: Default options for TGIFImage.DrawOptions.
  1504.   GIFImageDefaultDrawOptions : TGIFDrawOptions =
  1505.     [goAsync, goLoop, goTransparent, goAnimate, goDither, goAutoDither
  1506. {$IFDEF STRICT_MOZILLA}
  1507.      ,goClearOnLoop
  1508. {$ENDIF}
  1509. {$IFDEF DEFAULT_GOCLEARLOOP} // 2006.07.10
  1510.      ,goClearOnLoop
  1511. {$ENDIF}
  1512.     ];
  1513.  
  1514.   // WARNING! Do not use goAsync and goDirectDraw unless you have absolute
  1515.   // control of the destination canvas.
  1516.   // TGIFPainter will continue to write on the canvas even after the canvas has
  1517.   // been deleted, unless *you* prevent it.
  1518.   // The goValidateCanvas option will fix this problem if it is ever implemented.
  1519.  
  1520.   //: Default color reduction methods for bitmap import.
  1521.   // These are the fastest settings, but also the ones that gives the
  1522.   // worst result (in most cases).
  1523.   GIFImageDefaultColorReduction: TColorReduction = rmNetscape;
  1524.   GIFImageDefaultColorReductionBits: integer = 8; // Range 3 - 8
  1525.   GIFImageDefaultDitherMode: TDitherMode = dmNearest;
  1526.  
  1527.   //: Default encoder compression method.
  1528.   GIFImageDefaultCompression: TGIFCompression = gcLZW;
  1529.  
  1530.   //: Default painter thread priority
  1531.   GIFImageDefaultThreadPriority: TThreadPriority = tpNormal;
  1532.  
  1533.   //: Default animation speed in % of normal speed (range 0 - 1000)
  1534.   GIFImageDefaultAnimationSpeed: integer = 100;
  1535.  
  1536.   // DoAutoDither is set to True in the initializaion section if the desktop DC
  1537.   // supports 256 colors or less.
  1538.   // It can be modified in your application to disable/enable Auto Dithering
  1539.   DoAutoDither: boolean = False;
  1540.  
  1541.   // Palette is set to True in the initialization section if the desktop DC
  1542.   // supports 256 colors or less.
  1543.   // You should NOT modify it.
  1544.   PaletteDevice: boolean = False;
  1545.  
  1546.   // Set GIFImageRenderOnLoad to True to render (convert to bitmap) the
  1547.   // GIF frames as they are loaded instead of rendering them on-demand.
  1548.   // This might increase resource consumption and will increase load time,
  1549.   // but will cause animated GIFs to display more smoothly.
  1550.   GIFImageRenderOnLoad: boolean = False;
  1551.  
  1552.   // If GIFImageOptimizeOnStream is true, the GIF will be optimized
  1553.   // before it is streamed to the DFM file.
  1554.   // This will not affect TGIFImage.SaveToStream or SaveToFile.
  1555.   GIFImageOptimizeOnStream: boolean = False;
  1556.  
  1557. ////////////////////////////////////////////////////////////////////////////////
  1558. //
  1559. //                      Design Time support
  1560. //
  1561. ////////////////////////////////////////////////////////////////////////////////
  1562. // Dummy component registration for design time support of GIFs in TImage
  1563. procedure Register;
  1564.  
  1565. ////////////////////////////////////////////////////////////////////////////////
  1566. //
  1567. //                      Error messages
  1568. //
  1569. ////////////////////////////////////////////////////////////////////////////////
  1570. {$ifndef VER9x}
  1571. resourcestring
  1572. {$else}
  1573. const
  1574. {$endif}
  1575.   // GIF Error messages
  1576.   sOutOfData        = 'Premature end of data';
  1577.   sTooManyColors    = 'Color table overflow';
  1578.   sBadColorIndex    = 'Invalid color index';
  1579.   sBadVersion       = 'Unsupported GIF version';
  1580.   sBadSignature     = 'Invalid GIF signature';
  1581.   sScreenBadColorSize   = 'Invalid number of colors specified in Screen Descriptor';
  1582.   sImageBadColorSize    = 'Invalid number of colors specified in Image Descriptor';
  1583.   sUnknownExtension = 'Unknown extension type';
  1584.   sBadExtensionLabel    = 'Invalid extension introducer';
  1585.   sOutOfMemDIB      = 'Failed to allocate memory for GIF DIB';
  1586.   sDIBCreate        = 'Failed to create DIB from Bitmap';
  1587.   sDecodeTooFewBits = 'Decoder bit buffer under-run';
  1588.   sDecodeCircular   = 'Circular decoder table entry';
  1589.   sBadTrailer       = 'Invalid Image trailer';
  1590.   sBadExtensionInstance = 'Internal error: Extension Instance does not match Extension Label';
  1591.   sBadBlockSize     = 'Unsupported Application Extension block size';
  1592.   sBadBlock     = 'Unknown GIF block type';
  1593.   sUnsupportedClass = 'Object type not supported for operation';
  1594.   sInvalidData      = 'Invalid GIF data';
  1595.   sBadHeight        = 'Image height too small for contained frames';
  1596.   sBadWidth     = 'Image width too small for contained frames';
  1597. {$IFNDEF REGISTER_TGIFIMAGE}
  1598.   sGIFToClipboard   = 'Clipboard operations not supported for GIF objects';
  1599. {$ELSE}
  1600.   sFailedPaste      = 'Failed to store GIF on clipboard';
  1601. {$IFDEF VER9x}
  1602.   sUnknownClipboardFormat= 'Unsupported clipboard format';
  1603. {$ENDIF}
  1604. {$ENDIF}
  1605.   sScreenSizeExceeded   = 'Image exceeds Logical Screen size';
  1606.   sNoColorTable     = 'No global or local color table defined';
  1607.   sBadPixelCoordinates  = 'Invalid pixel coordinates';
  1608.   sUnsupportedBitmap    = 'Unsupported bitmap format';
  1609.   sInvalidPixelFormat   = 'Unsupported PixelFormat';
  1610.   sBadDimension     = 'Invalid image dimensions';
  1611.   sNoDIB        = 'Image has no DIB';
  1612.   sInvalidStream    = 'Invalid stream operation';
  1613.   sInvalidColor     = 'Color not in color table';
  1614.   sInvalidBitSize   = 'Invalid Bits Per Pixel value';
  1615.   sEmptyColorMap    = 'Color table is empty';
  1616.   sEmptyImage       = 'Image is empty';
  1617.   sInvalidBitmapList    = 'Invalid bitmap list';
  1618.   sInvalidReduction = 'Invalid reduction method';
  1619. {$IFDEF VER9x}
  1620.   // From Delphi 3 consts.pas
  1621.   SOutOfResources   = 'Out of system resources';
  1622.   SInvalidBitmap    = 'Bitmap image is not valid';
  1623.   SScanLine     = 'Scan line index out of range';
  1624. {$ENDIF}
  1625.  
  1626. ////////////////////////////////////////////////////////////////////////////////
  1627. //
  1628. //                      Misc texts
  1629. //
  1630. ////////////////////////////////////////////////////////////////////////////////
  1631.   // File filter name
  1632.   sGIFImageFile     = 'GIF Image';
  1633.  
  1634.   // Progress messages
  1635.   sProgressLoading  = 'Loading...';
  1636.   sProgressSaving   = 'Saving...';
  1637.   sProgressConverting   = 'Converting...';
  1638.   sProgressRendering    = 'Rendering...';
  1639.   sProgressCopying  = 'Copying...';
  1640.   sProgressOptimizing   = 'Optimizing...';
  1641.  
  1642.  
  1643. ////////////////////////////////////////////////////////////////////////////////
  1644. ////////////////////////////////////////////////////////////////////////////////
  1645. //
  1646. //          Implementation
  1647. //
  1648. ////////////////////////////////////////////////////////////////////////////////
  1649. ////////////////////////////////////////////////////////////////////////////////
  1650. implementation
  1651.  
  1652. { This makes me long for the C preprocessor... }
  1653. {$ifdef DEBUG}
  1654.   {$ifdef DEBUG_COMPRESSPERFORMANCE}
  1655.     {$define DEBUG_PERFORMANCE}
  1656.   {$else}
  1657.     {$ifdef DEBUG_DECOMPRESSPERFORMANCE}
  1658.       {$define DEBUG_PERFORMANCE}
  1659.     {$else}
  1660.       {$ifdef DEBUG_DITHERPERFORMANCE}
  1661.         {$define DEBUG_PERFORMANCE}
  1662.       {$else}
  1663.         {$ifdef DEBUG_DITHERPERFORMANCE}
  1664.           {$define DEBUG_PERFORMANCE}
  1665.         {$else}
  1666.           {$ifdef DEBUG_DRAWPERFORMANCE}
  1667.             {$define DEBUG_PERFORMANCE}
  1668.           {$else}
  1669.             {$ifdef DEBUG_RENDERPERFORMANCE}
  1670.               {$define DEBUG_PERFORMANCE}
  1671.             {$endif}
  1672.           {$endif}
  1673.         {$endif}
  1674.       {$endif}
  1675.     {$endif}
  1676.   {$endif}
  1677. {$endif}
  1678.  
  1679. uses
  1680. {$ifdef DEBUG}
  1681.   dialogs,
  1682. {$endif}
  1683.   mmsystem, // timeGetTime()
  1684.   messages,
  1685.   Consts;
  1686.  
  1687. ////////////////////////////////////////////////////////////////////////////////
  1688. //
  1689. //          Misc consts
  1690. //
  1691. ////////////////////////////////////////////////////////////////////////////////
  1692. const
  1693.   { Extension/block label values }
  1694.   bsPlainTextExtension      = $01;
  1695.   bsGraphicControlExtension = $F9;
  1696.   bsCommentExtension        = $FE;
  1697.   bsApplicationExtension    = $FF;
  1698.  
  1699.   bsImageDescriptor     = Ord(',');
  1700.   bsExtensionIntroducer     = Ord('!');
  1701.   bsTrailer         = ord(';');
  1702.  
  1703.   // Thread messages - Used by TThread.Synchronize()
  1704.   CM_DESTROYWINDOW  = $8FFE; // Defined in classes.pas
  1705.   CM_EXECPROC       = $8FFF; // Defined in classes.pas
  1706.  
  1707.  
  1708. ////////////////////////////////////////////////////////////////////////////////
  1709. //
  1710. //                      Design Time support
  1711. //
  1712. ////////////////////////////////////////////////////////////////////////////////
  1713. //: Dummy component registration to add design-time support of GIFs to TImage.
  1714. // Since TGIFImage isn't a component there's nothing to register here, but
  1715. // since Register is only called at design time we can set the design time
  1716. // GIF paint options here (modify as you please):
  1717. procedure Register;
  1718. begin
  1719.   // Don't loop animations at design-time. Animated GIFs will animate once and
  1720.   // then stop thus not using CPU resources and distracting the developer.
  1721.   Exclude(GIFImageDefaultDrawOptions, goLoop);
  1722. end;
  1723.  
  1724. ////////////////////////////////////////////////////////////////////////////////
  1725. //
  1726. //          Utilities
  1727. //
  1728. ////////////////////////////////////////////////////////////////////////////////
  1729. //: Creates a 216 color uniform non-dithering Netscape palette.
  1730. function WebPalette: HPalette;
  1731. type
  1732.   TLogWebPalette    = packed record
  1733.     palVersion      : word;
  1734.     palNumEntries   : word;
  1735.     PalEntries      : array[0..5,0..5,0..5] of TPaletteEntry;
  1736.   end;
  1737. var
  1738.   r, g, b       : byte;
  1739.   LogWebPalette     : TLogWebPalette;
  1740.   LogPalette        : TLogpalette absolute LogWebPalette; // Stupid typecast
  1741. begin
  1742.   with LogWebPalette do
  1743.   begin
  1744.     palVersion:= $0300;
  1745.     palNumEntries:= 216;
  1746.     for r:=0 to 5 do
  1747.       for g:=0 to 5 do
  1748.         for b:=0 to 5 do
  1749.         begin
  1750.           with PalEntries[r,g,b] do
  1751.           begin
  1752.             peRed := 51 * r;
  1753.             peGreen := 51 * g;
  1754.             peBlue := 51 * b;
  1755.             peFlags := 0;
  1756.           end;
  1757.         end;
  1758.   end;
  1759.   Result := CreatePalette(Logpalette);
  1760. end;
  1761.  
  1762. (*
  1763. **  GDI Error handling
  1764. **  Adapted from graphics.pas
  1765. *)
  1766. {$IFOPT R+}
  1767.   {$DEFINE R_PLUS}
  1768.   {$RANGECHECKS OFF}
  1769. {$ENDIF}
  1770. {$ifdef D3_BCB3}
  1771. function GDICheck(Value: Integer): Integer;
  1772. {$else}
  1773. function GDICheck(Value: Cardinal): Cardinal;
  1774. {$endif}
  1775. var
  1776.   ErrorCode     : integer;
  1777. // 2008.10.19 ->
  1778. {$IFDEF VER20_PLUS}
  1779.   Buf           : array [byte] of WideChar;
  1780. {$ELSE}
  1781.   Buf           : array [byte] of AnsiChar;
  1782. {$ENDIF}
  1783. // 2008.10.19 <-
  1784.  
  1785.   function ReturnAddr: Pointer;
  1786.   // From classes.pas
  1787.   asm
  1788.     MOV     EAX,[EBP+4] // sysutils.pas says [EBP-4], but this works !
  1789.   end;
  1790.  
  1791. begin
  1792.   if (Value = 0) then
  1793.   begin
  1794.     ErrorCode := GetLastError;
  1795.     if (ErrorCode <> 0) and (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil,
  1796.       ErrorCode, LOCALE_USER_DEFAULT, Buf, sizeof(Buf), nil) <> 0) then
  1797.       raise EOutOfResources.Create(Buf) at ReturnAddr
  1798.     else
  1799.       raise EOutOfResources.Create(SOutOfResources) at ReturnAddr;
  1800.   end;
  1801.   Result := Value;
  1802. end;
  1803. {$IFDEF R_PLUS}
  1804.   {$RANGECHECKS ON}
  1805.   {$UNDEF R_PLUS}
  1806. {$ENDIF}
  1807.  
  1808. (*
  1809. **  Raise error condition
  1810. *)
  1811. procedure Error(msg: string);
  1812.   function ReturnAddr: Pointer;
  1813.   // From classes.pas
  1814.   asm
  1815.     MOV     EAX,[EBP+4] // sysutils.pas says [EBP-4] !
  1816.   end;
  1817. begin
  1818.   raise GIFException.Create(msg) at ReturnAddr;
  1819. end;
  1820.  
  1821. (*
  1822. **  Return number bytes required to
  1823. **  hold a given number of bits.
  1824. *)
  1825. function ByteAlignBit(Bits: Cardinal): Cardinal;
  1826. begin
  1827.   Result := (Bits+7) SHR 3;
  1828. end;
  1829. // Rounded up to nearest 2
  1830. function WordAlignBit(Bits: Cardinal): Cardinal;
  1831. begin
  1832.   Result := ((Bits+15) SHR 4) SHL 1;
  1833. end;
  1834. // Rounded up to nearest 4
  1835. function DWordAlignBit(Bits: Cardinal): Cardinal;
  1836. begin
  1837.   Result := ((Bits+31) SHR 5) SHL 2;
  1838. end;
  1839. // Round to arbitrary number of bits
  1840. function AlignBit(Bits, BitsPerPixel, Alignment: Cardinal): Cardinal;
  1841. begin
  1842.   Dec(Alignment);
  1843.   Result := ((Bits * BitsPerPixel) + Alignment) and not Alignment;
  1844.   Result := Result SHR 3;
  1845. end;
  1846.  
  1847. (*
  1848. **  Compute Bits per Pixel from Number of Colors
  1849. **  (Return the ceiling log of n)
  1850. *)
  1851. function Colors2bpp(Colors: integer): integer;
  1852. var
  1853.   MaxColor      : integer;
  1854. begin
  1855.   (*
  1856.   ** This might be faster computed by multiple if then else statements
  1857.   *)
  1858.  
  1859.   if (Colors = 0) then
  1860.     Result := 0
  1861.   else
  1862.   begin
  1863.     Result := 1;
  1864.     MaxColor := 2;
  1865.     while (Colors > MaxColor) do
  1866.     begin
  1867.       inc(Result);
  1868.       MaxColor := MaxColor SHL 1;
  1869.     end;
  1870.   end;
  1871. end;
  1872.  
  1873. (*
  1874. **  Write an ordinal byte value to a stream
  1875. *)
  1876. procedure WriteByte(Stream: TStream; b: BYTE);
  1877. begin
  1878.   Stream.Write(b, 1);
  1879. end;
  1880.  
  1881. (*
  1882. **  Read an ordinal byte value from a stream
  1883. *)
  1884. function ReadByte(Stream: TStream): BYTE;
  1885. begin
  1886.   Stream.Read(Result, 1);
  1887. end;
  1888.  
  1889. (*
  1890. **  Read data from stream and raise exception of EOF
  1891. *)
  1892. procedure ReadCheck(Stream: TStream; var Buffer; Size: LongInt);
  1893. var
  1894.   ReadSize      : integer;
  1895. begin
  1896.   ReadSize := Stream.Read(Buffer, Size);
  1897.   if (ReadSize <> Size) then
  1898.     Error(sOutOfData);
  1899. end;
  1900.  
  1901. (*
  1902. **  Write a string list to a stream as multiple blocks
  1903. **  of max 255 characters in each.
  1904. *)
  1905. procedure WriteStrings(Stream: TStream; Text: TStrings);
  1906. var
  1907.   i         : integer;
  1908.   b         : BYTE;
  1909.   size          : integer;
  1910.   s         : AnsiString;
  1911. begin
  1912.   for i := 0 to Text.Count-1 do
  1913.   begin
  1914.     s := AnsiString(Text[i]);
  1915.     size := length(s);
  1916.     if (size > 255) then
  1917.       b := 255
  1918.     else
  1919.       b := size;
  1920.     while (size > 0) do
  1921.     begin
  1922.       dec(size, b);
  1923.       WriteByte(Stream, b);
  1924. // 2008.10.19 ->
  1925. //      Stream.Write(PChar(s)^, b);
  1926.       Stream.Write(PByte(s)^, b);
  1927. // 2008.10.19 <-
  1928.       delete(s, 1, b);
  1929.       if (b > size) then
  1930.         b := size;
  1931.     end;
  1932.   end;
  1933.   // Terminating zero (length = 0)
  1934.   WriteByte(Stream, 0);
  1935. end;
  1936.  
  1937.  
  1938. (*
  1939. **  Read a string list from a stream as multiple blocks
  1940. **  of max 255 characters in each.
  1941. *)
  1942. { TODO -oanme -cImprovement : Replace ReadStrings with TGIFReader. }
  1943. procedure ReadStrings(Stream: TStream; Text: TStrings);
  1944. var
  1945.   size          : BYTE;
  1946.   buf           : array[0..255] of AnsiChar;
  1947. begin
  1948.   Text.Clear;
  1949.   if (Stream.Read(size, 1) <> 1) then
  1950.     exit;
  1951.   while (size > 0) do
  1952.   begin
  1953.     ReadCheck(Stream, buf, size);
  1954.     buf[size] := #0;
  1955. // 2008.10.19 ->
  1956. //    Text.Add(Buf);
  1957.     Text.Add(string(Buf));
  1958. // 2008.10.19 <-
  1959.     if (Stream.Read(size, 1) <> 1) then
  1960.       exit;
  1961.   end;
  1962. end;
  1963.  
  1964.  
  1965. ////////////////////////////////////////////////////////////////////////////////
  1966. //
  1967. //      Delphi 2.x / C++ Builder 1.x support
  1968. //
  1969. ////////////////////////////////////////////////////////////////////////////////
  1970. {$IFDEF VER9x}
  1971. var
  1972.   // From Delphi 3 graphics.pas
  1973.   SystemPalette16: HPalette; // 16 color palette that maps to the system palette
  1974.  
  1975. type
  1976.   TPixelFormats = set of TPixelFormat;
  1977.  
  1978. const
  1979.   // Only pf1bit, pf4bit and pf8bit is supported since they are the only ones
  1980.   // with palettes
  1981.   SupportedPixelformats: TPixelFormats = [pf1bit, pf4bit, pf8bit];
  1982. {$ENDIF}
  1983.  
  1984.  
  1985. // --------------------------
  1986. // InitializeBitmapInfoHeader
  1987. // --------------------------
  1988. // Fills a TBitmapInfoHeader with the values of a bitmap when converted to a
  1989. // DIB of a specified PixelFormat.
  1990. //
  1991. // Parameters:
  1992. // Bitmap   The handle of the source bitmap.
  1993. // Info     The TBitmapInfoHeader buffer that will receive the values.
  1994. // PixelFormat  The pixel format of the destination DIB.
  1995. //
  1996. {$IFDEF BAD_STACK_ALIGNMENT}
  1997.   // Disable optimization to circumvent optimizer bug...
  1998.   {$IFOPT O+}
  1999.     {$DEFINE O_PLUS}
  2000.     {$O-}
  2001.   {$ENDIF}
  2002. {$ENDIF}
  2003. procedure InitializeBitmapInfoHeader(Bitmap: HBITMAP; var Info: TBitmapInfoHeader;
  2004.   PixelFormat: TPixelFormat);
  2005. // From graphics.pas, "optimized" for our use
  2006. var
  2007.   DIB       : TDIBSection;
  2008.   Bytes     : Integer;
  2009. begin
  2010.   DIB.dsbmih.biSize := 0;
  2011.   Bytes := GetObject(Bitmap, SizeOf(DIB), @DIB);
  2012.   if (Bytes = 0) then
  2013.     Error(sInvalidBitmap);
  2014.  
  2015.   if (Bytes >= (sizeof(DIB.dsbm) + sizeof(DIB.dsbmih))) and
  2016.     (DIB.dsbmih.biSize >= sizeof(DIB.dsbmih)) then
  2017.     Info := DIB.dsbmih
  2018.   else
  2019.   begin
  2020.     FillChar(Info, sizeof(Info), 0);
  2021.     with Info, DIB.dsbm do
  2022.     begin
  2023.       biSize := SizeOf(Info);
  2024.       biWidth := bmWidth;
  2025.       biHeight := bmHeight;
  2026.     end;
  2027.   end;
  2028.   case PixelFormat of
  2029.     pf1bit: Info.biBitCount := 1;
  2030.     pf4bit: Info.biBitCount := 4;
  2031.     pf8bit: Info.biBitCount := 8;
  2032.     pf24bit: Info.biBitCount := 24;
  2033.   else
  2034.     Error(sInvalidPixelFormat);
  2035.     // Info.biBitCount := DIB.dsbm.bmBitsPixel * DIB.dsbm.bmPlanes;
  2036.   end;
  2037.   Info.biPlanes := 1;
  2038.   Info.biCompression := BI_RGB; // Always return data in RGB format
  2039.   Info.biSizeImage := AlignBit(Info.biWidth, Info.biBitCount, 32) * Cardinal(abs(Info.biHeight));
  2040. end;
  2041. {$IFDEF O_PLUS}
  2042.   {$O+}
  2043.   {$UNDEF O_PLUS}
  2044. {$ENDIF}
  2045.  
  2046. // -------------------
  2047. // InternalGetDIBSizes
  2048. // -------------------
  2049. // Calculates the buffer sizes nescessary for convertion of a bitmap to a DIB
  2050. // of a specified PixelFormat.
  2051. // See the GetDIBSizes API function for more info.
  2052. //
  2053. // Parameters:
  2054. // Bitmap   The handle of the source bitmap.
  2055. // InfoHeaderSize
  2056. //      The returned size of a buffer that will receive the DIB's
  2057. //      TBitmapInfo structure.
  2058. // ImageSize    The returned size of a buffer that will receive the DIB's
  2059. //      pixel data.
  2060. // PixelFormat  The pixel format of the destination DIB.
  2061. //
  2062. procedure InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: Integer;
  2063.   var ImageSize: longInt; PixelFormat: TPixelFormat);
  2064. // From graphics.pas, "optimized" for our use
  2065. var
  2066.   Info      : TBitmapInfoHeader;
  2067. begin
  2068.   InitializeBitmapInfoHeader(Bitmap, Info, PixelFormat);
  2069.   // Check for palette device format
  2070.   if (Info.biBitCount > 8) then
  2071.   begin
  2072.     // Header but no palette
  2073.     InfoHeaderSize := SizeOf(TBitmapInfoHeader);
  2074.     if ((Info.biCompression and BI_BITFIELDS) <> 0) then
  2075.       Inc(InfoHeaderSize, 12);
  2076.   end else
  2077.     // Header and palette
  2078.     InfoHeaderSize := SizeOf(TBitmapInfoHeader) + SizeOf(TRGBQuad) * (1 shl Info.biBitCount);
  2079.   ImageSize := Info.biSizeImage;
  2080. end;
  2081.  
  2082. // --------------
  2083. // InternalGetDIB
  2084. // --------------
  2085. // Converts a bitmap to a DIB of a specified PixelFormat.
  2086. //
  2087. // Parameters:
  2088. // Bitmap   The handle of the source bitmap.
  2089. // Pal      The handle of the source palette.
  2090. // BitmapInfo   The buffer that will receive the DIB's TBitmapInfo structure.
  2091. //      A buffer of sufficient size must have been allocated prior to
  2092. //      calling this function.
  2093. // Bits     The buffer that will receive the DIB's pixel data.
  2094. //      A buffer of sufficient size must have been allocated prior to
  2095. //      calling this function.
  2096. // PixelFormat  The pixel format of the destination DIB.
  2097. //
  2098. // Returns:
  2099. // True on success, False on failure.
  2100. //
  2101. // Note: The InternalGetDIBSizes function can be used to calculate the
  2102. // nescessary sizes of the BitmapInfo and Bits buffers.
  2103. //
  2104. function InternalGetDIB(Bitmap: HBITMAP; Palette: HPALETTE;
  2105.   var BitmapInfo; var Bits; PixelFormat: TPixelFormat): Boolean;
  2106. // From graphics.pas, "optimized" for our use
  2107. var
  2108.   OldPal    : HPALETTE;
  2109.   DC        : HDC;
  2110. begin
  2111.   InitializeBitmapInfoHeader(Bitmap, TBitmapInfoHeader(BitmapInfo), PixelFormat);
  2112.   OldPal := 0;
  2113.   DC := CreateCompatibleDC(0);
  2114.   try
  2115.     if (Palette <> 0) then
  2116.     begin
  2117.       OldPal := SelectPalette(DC, Palette, False);
  2118.       RealizePalette(DC);
  2119.     end;
  2120.     Result := (GetDIBits(DC, Bitmap, 0, abs(TBitmapInfoHeader(BitmapInfo).biHeight),
  2121.       @Bits, TBitmapInfo(BitmapInfo), DIB_RGB_COLORS) <> 0);
  2122.   finally
  2123.     if (OldPal <> 0) then
  2124.       SelectPalette(DC, OldPal, False);
  2125.     DeleteDC(DC);
  2126.   end;
  2127. end;
  2128.  
  2129. // ----------
  2130. // DIBFromBit
  2131. // ----------
  2132. // Converts a bitmap to a DIB of a specified PixelFormat.
  2133. // The DIB is returned in a TMemoryStream ready for streaming to a BMP file.
  2134. //
  2135. // Note: As opposed to D2's DIBFromBit function, the returned stream also
  2136. // contains a TBitmapFileHeader at offset 0.
  2137. //
  2138. // Parameters:
  2139. // Stream   The TMemoryStream used to store the bitmap data.
  2140. //      The stream must be allocated and freed by the caller prior to
  2141. //      calling this function.
  2142. // Src      The handle of the source bitmap.
  2143. // Pal      The handle of the source palette.
  2144. // PixelFormat  The pixel format of the destination DIB.
  2145. // DIBHeader    A pointer to the DIB's TBitmapInfo (or TBitmapInfoHeader)
  2146. //      structure in the memory stream.
  2147. //      The size of the structure can either be deduced from the
  2148. //      pixel format (i.e. number of colors) or calculated by
  2149. //      subtracting the DIBHeader pointer from the DIBBits pointer.
  2150. // DIBBits  A pointer to the DIB's pixel data in the memory stream.
  2151. //
  2152. procedure DIBFromBit(Stream: TMemoryStream; Src: HBITMAP;
  2153.   Pal: HPALETTE; PixelFormat: TPixelFormat; var DIBHeader, DIBBits: Pointer);
  2154. // (From D2 graphics.pas, "optimized" for our use)
  2155. var
  2156.   HeaderSize        : integer;
  2157.   FileSize      : longInt;
  2158.   ImageSize     : longInt;
  2159.   BitmapFileHeader  : PBitmapFileHeader;
  2160. begin
  2161.   if (Src = 0) then
  2162.     Error(sInvalidBitmap);
  2163.   // Get header- and pixel data size for new pixel format
  2164.   InternalGetDIBSizes(Src, HeaderSize, ImageSize, PixelFormat);
  2165.   // Make room in stream for a TBitmapInfo and pixel data
  2166.   FileSize := sizeof(TBitmapFileHeader) + HeaderSize + ImageSize;
  2167.   Stream.SetSize(FileSize);
  2168.   // Get pointer to TBitmapFileHeader
  2169.   BitmapFileHeader := Stream.Memory;
  2170.   // Get pointer to TBitmapInfo
  2171.   DIBHeader := Pointer(Longint(BitmapFileHeader) + sizeof(TBitmapFileHeader));
  2172.   // Get pointer to pixel data
  2173.   DIBBits := Pointer(Longint(DIBHeader) + HeaderSize);
  2174.   // Initialize file header
  2175.   FillChar(BitmapFileHeader^, sizeof(TBitmapFileHeader), 0);
  2176.   with BitmapFileHeader^ do
  2177.   begin
  2178.     bfType := $4D42; // 'BM' = Windows BMP signature
  2179.     bfSize := FileSize; // File size (not needed)
  2180.     bfOffBits := sizeof(TBitmapFileHeader) + HeaderSize; // Offset of pixel data
  2181.   end;
  2182.   // Get pixel data in new pixel format
  2183.   InternalGetDIB(Src, Pal, DIBHeader^, DIBBits^, PixelFormat);
  2184. end;
  2185.  
  2186. // --------------
  2187. // GetPixelFormat
  2188. // --------------
  2189. // Returns the current pixel format of a bitmap.
  2190. //
  2191. // Replacement for delphi 3 TBitmap.PixelFormat getter.
  2192. //
  2193. // Parameters:
  2194. // Bitmap   The bitmap which pixel format is returned.
  2195. //
  2196. // Returns:
  2197. // The PixelFormat of the bitmap
  2198. //
  2199. function GetPixelFormat(Bitmap: TBitmap): TPixelFormat;
  2200. {$IFDEF VER9x}
  2201. // From graphics.pas, "optimized" for our use
  2202. var
  2203.   DIBSection        : TDIBSection;
  2204.   Bytes         : Integer;
  2205.   Handle        : HBitmap;
  2206. begin
  2207.   Result := pfCustom; // This value is never returned
  2208.   // BAD_STACK_ALIGNMENT
  2209.   // Note: To work around an optimizer bug, we do not use Bitmap.Handle
  2210.   // directly. Instead we store the value and use it indirectly. Unless we do
  2211.   // this, the register containing Bitmap.Handle will be overwritten!
  2212.   Handle := Bitmap.Handle;
  2213.   if (Handle <> 0) then
  2214.   begin
  2215.     Bytes := GetObject(Handle, SizeOf(DIBSection), @DIBSection);
  2216.     if (Bytes = 0) then
  2217.       Error(sInvalidBitmap);
  2218.  
  2219.     with (DIBSection) do
  2220.     begin
  2221.       // Check for NT bitmap
  2222.       if (Bytes < (SizeOf(dsbm) + SizeOf(dsbmih))) or (dsbmih.biSize < SizeOf(dsbmih)) then
  2223.         DIBSection.dsBmih.biBitCount := dsbm.bmBitsPixel * dsbm.bmPlanes;
  2224.  
  2225.       case (dsBmih.biBitCount) of
  2226.         0: Result := pfDevice;
  2227.         1: Result := pf1bit;
  2228.         4: Result := pf4bit;
  2229.         8: Result := pf8bit;
  2230.         16: case (dsBmih.biCompression) of
  2231.               BI_RGB:
  2232.                 Result := pf15Bit;
  2233.               BI_BITFIELDS:
  2234.                 if (dsBitFields[1] = $07E0) then
  2235.                   Result := pf16Bit;
  2236.             end;
  2237.         24: Result := pf24Bit;
  2238.         32: if (dsBmih.biCompression = BI_RGB) then
  2239.               Result := pf32Bit;
  2240.       else
  2241.         Error(sUnsupportedBitmap);
  2242.       end;
  2243.     end;
  2244.   end else
  2245. //    Result := pfDevice;
  2246.     Error(sUnsupportedBitmap);
  2247. end;
  2248. {$ELSE}
  2249. begin
  2250.   Result := Bitmap.PixelFormat;
  2251. end;
  2252. {$ENDIF}
  2253.  
  2254. // --------------
  2255. // SetPixelFormat
  2256. // --------------
  2257. // Changes the pixel format of a TBitmap.
  2258. //
  2259. // Replacement for delphi 3 TBitmap.PixelFormat setter.
  2260. // The returned TBitmap will always be a DIB.
  2261. //
  2262. // Note: Under Delphi 3.x this function will leak a palette handle each time it
  2263. //       converts a TBitmap to pf8bit format!
  2264. //       If possible, use SafeSetPixelFormat instead to avoid this.
  2265. //
  2266. // Parameters:
  2267. // Bitmap   The bitmap to modify.
  2268. // PixelFormat  The pixel format to convert to.
  2269. //
  2270. procedure SetPixelFormat(Bitmap: TBitmap; PixelFormat: TPixelFormat);
  2271. {$IFDEF VER9x}
  2272. var
  2273.   Stream    : TMemoryStream;
  2274.   Header    ,
  2275.   Bits      : Pointer;
  2276. begin
  2277.   // Can't change anything without a handle
  2278.   if (Bitmap.Handle = 0) then
  2279.     Error(sInvalidBitmap);
  2280.  
  2281.   // Only convert to supported formats
  2282.   if not(PixelFormat in SupportedPixelformats) then
  2283.     Error(sInvalidPixelFormat);
  2284.  
  2285.   // No need to convert to same format
  2286.   if (GetPixelFormat(Bitmap) = PixelFormat) then
  2287.     exit;
  2288.  
  2289.   Stream := TMemoryStream.Create;
  2290.   try
  2291.     // Convert to DIB file in memory stream
  2292.     DIBFromBit(Stream, Bitmap.Handle, Bitmap.Palette, PixelFormat, Header, Bits);
  2293.     // Load DIB from stream
  2294.     Stream.Position := 0;
  2295.     Bitmap.LoadFromStream(Stream);
  2296.   finally
  2297.     Stream.Free;
  2298.   end;
  2299. end;
  2300. {$ELSE}
  2301. begin
  2302.   Bitmap.PixelFormat := PixelFormat;
  2303. end;
  2304. {$ENDIF}
  2305.  
  2306. {$IFDEF VER100}
  2307. var
  2308.   pf8BitBitmap: TBitmap = nil;
  2309. {$ENDIF}
  2310.  
  2311. // ------------------
  2312. // SafeSetPixelFormat
  2313. // ------------------
  2314. // Changes the pixel format of a TBitmap but doesn't preserve the contents.
  2315. //
  2316. // Replacement for Delphi 3 TBitmap.PixelFormat setter.
  2317. // The returned TBitmap will always be an empty DIB of the same size as the
  2318. // original bitmap.
  2319. //
  2320. // This function is used to avoid the palette handle leak that Delphi 3's
  2321. // SetPixelFormat and TBitmap.PixelFormat suffers from.
  2322. //
  2323. // Parameters:
  2324. // Bitmap   The bitmap to modify.
  2325. // PixelFormat  The pixel format to convert to.
  2326. //
  2327. procedure SafeSetPixelFormat(Bitmap: TBitmap; PixelFormat: TPixelFormat);
  2328. {$IFDEF VER9x}
  2329. begin
  2330.   SetPixelFormat(Bitmap, PixelFormat);
  2331. end;
  2332. {$ELSE}
  2333. {$IFNDEF VER100}
  2334. var
  2335.   Palette       : hPalette;
  2336. begin
  2337.   Bitmap.PixelFormat := PixelFormat;
  2338.  
  2339.   // Work around a bug in TBitmap:
  2340.   // When converting to pf8bit format, the palette assigned to TBitmap.Palette
  2341.   // will be a half tone palette (which only contains the 20 system colors).
  2342.   // Unfortunately this is not the palette used to render the bitmap and it
  2343.   // is also not the palette saved with the bitmap.
  2344.   if (PixelFormat = pf8bit) then
  2345.   begin
  2346.     // Disassociate the wrong palette from the bitmap (without affecting
  2347.     // the DIB color table)
  2348.     Palette := Bitmap.ReleasePalette;
  2349.     if (Palette <> 0) then
  2350.       DeleteObject(Palette);
  2351.     // Recreate the palette from the DIB color table
  2352.     Bitmap.Palette;
  2353.   end;
  2354. end;
  2355. {$ELSE}
  2356. var
  2357.   Width         ,
  2358.   Height        : integer;
  2359. begin
  2360.   if (PixelFormat = pf8bit) then
  2361.   begin
  2362.     // Partial solution to "TBitmap.PixelFormat := pf8bit" leak
  2363.     // by Greg Chapman <[email protected]>
  2364.     if (pf8BitBitmap = nil) then
  2365.     begin
  2366.       // Create a "template" bitmap
  2367.       // The bitmap is deleted in the finalization section of the unit.
  2368.       pf8BitBitmap:= TBitmap.Create;
  2369.       // Convert template to pf8bit format
  2370.       // This will leak 1 palette handle, but only once
  2371.       pf8BitBitmap.PixelFormat:= pf8Bit;
  2372.     end;
  2373.     // Store the size of the original bitmap
  2374.     Width := Bitmap.Width;
  2375.     Height := Bitmap.Height;
  2376.     // Convert to pf8bit format by copying template
  2377.     Bitmap.Assign(pf8BitBitmap);
  2378.     // Restore the original size
  2379.     Bitmap.Width := Width;
  2380.     Bitmap.Height := Height;
  2381.   end else
  2382.     // This is safe since only pf8bit leaks
  2383.     Bitmap.PixelFormat := PixelFormat;
  2384. end;
  2385. {$ENDIF}
  2386. {$ENDIF}
  2387.  
  2388.  
  2389. {$IFDEF VER9x}
  2390.  
  2391. // -----------
  2392. // CopyPalette
  2393. // -----------
  2394. // Copies a HPALETTE.
  2395. //
  2396. // Copied from D3 graphics.pas.
  2397. // This is declared private in some old versions of Delphi 2 so we have to
  2398. // implement it here to support those old versions.
  2399. //
  2400. // Parameters:
  2401. // Palette  The palette to copy.
  2402. //
  2403. // Returns:
  2404. // The handle to a new palette.
  2405. //
  2406. function CopyPalette(Palette: HPALETTE): HPALETTE;
  2407. var
  2408.   PaletteSize: Integer;
  2409.   LogPal: TMaxLogPalette;
  2410. begin
  2411.   Result := 0;
  2412.   if Palette = 0 then Exit;
  2413.   PaletteSize := 0;
  2414.   if GetObject(Palette, SizeOf(PaletteSize), @PaletteSize) = 0 then Exit;
  2415.   if PaletteSize = 0 then Exit;
  2416.   with LogPal do
  2417.   begin
  2418.     palVersion := $0300;
  2419.     palNumEntries := PaletteSize;
  2420.     GetPaletteEntries(Palette, 0, PaletteSize, palPalEntry);
  2421.   end;
  2422.   Result := CreatePalette(PLogPalette(@LogPal)^);
  2423. end;
  2424.  
  2425.  
  2426. // TThreadList implementation from Delphi 3 classes.pas
  2427. constructor TThreadList.Create;
  2428. begin
  2429.   inherited Create;
  2430.   InitializeCriticalSection(FLock);
  2431.   FList := TList.Create;
  2432. end;
  2433.  
  2434. destructor TThreadList.Destroy;
  2435. begin
  2436.   LockList;    // Make sure nobody else is inside the list.
  2437.   try
  2438.     FList.Free;
  2439.     inherited Destroy;
  2440.   finally
  2441.     UnlockList;
  2442.     DeleteCriticalSection(FLock);
  2443.   end;
  2444. end;
  2445.  
  2446. procedure TThreadList.Add(Item: Pointer);
  2447. begin
  2448.   LockList;
  2449.   try
  2450.     if FList.IndexOf(Item) = -1 then
  2451.       FList.Add(Item);
  2452.   finally
  2453.     UnlockList;
  2454.   end;
  2455. end;
  2456.  
  2457. procedure TThreadList.Clear;
  2458. begin
  2459.   LockList;
  2460.   try
  2461.     FList.Clear;
  2462.   finally
  2463.     UnlockList;
  2464.   end;
  2465. end;
  2466.  
  2467. function  TThreadList.LockList: TList;
  2468. begin
  2469.   EnterCriticalSection(FLock);
  2470.   Result := FList;
  2471. end;
  2472.  
  2473. procedure TThreadList.Remove(Item: Pointer);
  2474. begin
  2475.   LockList;
  2476.   try
  2477.     FList.Remove(Item);
  2478.   finally
  2479.     UnlockList;
  2480.   end;
  2481. end;
  2482.  
  2483. procedure TThreadList.UnlockList;
  2484. begin
  2485.   LeaveCriticalSection(FLock);
  2486. end;
  2487. // End of TThreadList implementation
  2488.  
  2489. // From Delphi 3 sysutils.pas
  2490. { CompareMem performs a binary compare of Length bytes of memory referenced
  2491.   by P1 to that of P2.  CompareMem returns True if the memory referenced by
  2492.   P1 is identical to that of P2. }
  2493. function CompareMem(P1, P2: Pointer; Length: Integer): Boolean; assembler;
  2494. asm
  2495.         PUSH    ESI
  2496.         PUSH    EDI
  2497.         MOV     ESI,P1
  2498.         MOV     EDI,P2
  2499.         MOV     EDX,ECX
  2500.         XOR     EAX,EAX
  2501.         AND     EDX,3
  2502.         SHR     ECX,1
  2503.         SHR     ECX,1
  2504.         REPE    CMPSD
  2505.         JNE     @@2
  2506.         MOV     ECX,EDX
  2507.         REPE    CMPSB
  2508.         JNE     @@2
  2509. @@1:    INC     EAX
  2510. @@2:    POP     EDI
  2511.         POP     ESI
  2512. end;
  2513.  
  2514. // Dummy ASSERT procedure since ASSERT does not exist in Delphi 2.x
  2515. procedure ASSERT(Condition: boolean; Message: string);
  2516. begin
  2517. end;
  2518.  
  2519. {$ENDIF} // Delphi 2.x stuff
  2520.  
  2521. ////////////////////////////////////////////////////////////////////////////////
  2522. //
  2523. //          TDIB Classes
  2524. //
  2525. //  These classes gives read and write access to TBitmap's pixel data
  2526. //  independently of the Delphi version used.
  2527. //
  2528. ////////////////////////////////////////////////////////////////////////////////
  2529. type
  2530.   TDIB = class(TObject)
  2531.   private
  2532.     FBitmap     : TBitmap;
  2533.     FPixelFormat    : TPixelFormat;
  2534.   protected
  2535.     function GetScanline(Row: integer): pointer; virtual; abstract;
  2536.     constructor Create(ABitmap: TBitmap; APixelFormat: TPixelFormat);
  2537.   public
  2538.     property Scanline[Row: integer]: pointer read GetScanline;
  2539.     property Bitmap: TBitmap read FBitmap;
  2540.     property PixelFormat: TPixelFormat read FPixelFormat;
  2541.   end;
  2542.  
  2543.   TDIBReader = class(TDIB)
  2544.   private
  2545. {$ifdef VER9x}
  2546.     FDIB        : TDIBSection;
  2547.     FDC         : HDC;
  2548.     FScanLine       : pointer;
  2549.     FLastRow        : integer;
  2550.     FInfo       : PBitmapInfo;
  2551.     FBytes      : integer;
  2552. {$endif}
  2553.   protected
  2554.     function GetScanline(Row: integer): pointer; override;
  2555.   public
  2556.     constructor Create(ABitmap: TBitmap; APixelFormat: TPixelFormat);
  2557.     destructor Destroy; override;
  2558.   end;
  2559.  
  2560.   TDIBWriter = class(TDIB)
  2561.   private
  2562. {$ifdef PIXELFORMAT_TOO_SLOW}
  2563.     FDIBInfo        : PBitmapInfo;
  2564.     FDIBBits        : pointer;
  2565.     FDIBInfoSize    : integer;
  2566.     FDIBBitsSize    : longInt;
  2567. {$ifndef CREATEDIBSECTION_SLOW}
  2568.     FDIB        : HBITMAP;
  2569. {$endif}
  2570. {$endif}
  2571.     FPalette        : HPalette;
  2572.     FHeight     : integer;
  2573.     FWidth      : integer;
  2574.   protected
  2575.     procedure CreateDIB;
  2576.     procedure FreeDIB;
  2577.     procedure NeedDIB;
  2578.     function GetScanline(Row: integer): pointer; override;
  2579.   public
  2580.     constructor Create(ABitmap: TBitmap; APixelFormat: TPixelFormat;
  2581.       AWidth, AHeight: integer; APalette: HPalette);
  2582.     destructor Destroy; override;
  2583.     procedure UpdateBitmap;
  2584.     property Width: integer read FWidth;
  2585.     property Height: integer read FHeight;
  2586.     property Palette: HPalette read FPalette;
  2587.   end;
  2588.  
  2589. ////////////////////////////////////////////////////////////////////////////////
  2590. constructor TDIB.Create(ABitmap: TBitmap; APixelFormat: TPixelFormat);
  2591. begin
  2592.   inherited Create;
  2593.   FBitmap := ABitmap;
  2594.   FPixelFormat := APixelFormat;
  2595. end;
  2596.  
  2597. ////////////////////////////////////////////////////////////////////////////////
  2598. constructor TDIBReader.Create(ABitmap: TBitmap; APixelFormat: TPixelFormat);
  2599. {$ifdef VER9x}
  2600. var
  2601.   InfoHeaderSize    : integer;
  2602.   ImageSize     : longInt;
  2603. {$endif}
  2604. begin
  2605.   inherited Create(ABitmap, APixelFormat);
  2606. {$ifndef VER9x}
  2607.   SetPixelFormat(FBitmap, FPixelFormat);
  2608. {$else}
  2609.   FDC := CreateCompatibleDC(0);
  2610.   SelectPalette(FDC, FBitmap.Palette, False);
  2611.  
  2612.   // Allocate DIB info structure
  2613.   InternalGetDIBSizes(ABitmap.Handle, InfoHeaderSize, ImageSize, APixelFormat);
  2614.   GetMem(FInfo, InfoHeaderSize);
  2615.   // Get DIB info
  2616.   InitializeBitmapInfoHeader(ABitmap.Handle, FInfo^.bmiHeader, APixelFormat);
  2617.  
  2618.   // Allocate scan line buffer
  2619.   GetMem(FScanLine, ImageSize DIV abs(FInfo^.bmiHeader.biHeight));
  2620.  
  2621.   FLastRow := -1;
  2622. {$endif}
  2623. end;
  2624.  
  2625. destructor TDIBReader.Destroy;
  2626. begin
  2627. {$ifdef VER9x}
  2628.   DeleteDC(FDC);
  2629.   FreeMem(FScanLine);
  2630.   FreeMem(FInfo);
  2631. {$endif}
  2632.   inherited Destroy;
  2633. end;
  2634.  
  2635. function TDIBReader.GetScanline(Row: integer): pointer;
  2636. begin
  2637. {$ifdef VER9x}
  2638.   if (Row < 0) or (Row >= FBitmap.Height) then
  2639.     raise EInvalidGraphicOperation.Create(SScanLine);
  2640.   GDIFlush;
  2641.  
  2642.   Result := FScanLine;
  2643.   if (Row = FLastRow) then
  2644.     exit;
  2645.   FLastRow := Row;
  2646.  
  2647.   if (FInfo^.bmiHeader.biHeight > 0) then  // bottom-up DIB
  2648.     Row := FInfo^.bmiHeader.biHeight - Row - 1;
  2649.   GetDIBits(FDC, FBitmap.Handle, Row, 1, FScanLine, FInfo^, DIB_RGB_COLORS);
  2650.  
  2651. {$else}
  2652.   Result := FBitmap.ScanLine[Row];
  2653. {$endif}
  2654. end;
  2655.  
  2656. ////////////////////////////////////////////////////////////////////////////////
  2657. constructor TDIBWriter.Create(ABitmap: TBitmap; APixelFormat: TPixelFormat;
  2658.   AWidth, AHeight: integer; APalette: HPalette);
  2659. begin
  2660.   inherited Create(ABitmap, APixelFormat);
  2661.  
  2662.   // DIB writer only supports 8 or 24 bit bitmaps
  2663.   if not(APixelFormat in [pf8bit, pf24bit]) then
  2664.     Error(sInvalidPixelFormat);
  2665.   if (AWidth = 0) or (AHeight = 0) then
  2666.     Error(sBadDimension);
  2667.  
  2668.   FHeight := AHeight;
  2669.   FWidth := AWidth;
  2670. {$ifndef PIXELFORMAT_TOO_SLOW}
  2671.   FBitmap.Palette := 0;
  2672.   FBitmap.Height := FHeight;
  2673.   FBitmap.Width := FWidth;
  2674.   SafeSetPixelFormat(FBitmap, FPixelFormat);
  2675.   FPalette := CopyPalette(APalette);
  2676.   FBitmap.Palette := FPalette;
  2677. {$else}
  2678.   FPalette := APalette;
  2679.   FDIBInfo := nil;
  2680.   FDIBBits := nil;
  2681. {$ifndef CREATEDIBSECTION_SLOW}
  2682.   FDIB := 0;
  2683. {$endif}
  2684. {$endif}
  2685. end;
  2686.  
  2687. destructor TDIBWriter.Destroy;
  2688. begin
  2689.   UpdateBitmap;
  2690.   FreeDIB;
  2691.   inherited Destroy;
  2692. end;
  2693.  
  2694. function TDIBWriter.GetScanline(Row: integer): pointer;
  2695. begin
  2696. {$ifdef PIXELFORMAT_TOO_SLOW}
  2697.   NeedDIB;
  2698.  
  2699.   if (FDIBBits = nil) then
  2700.     Error(sNoDIB);
  2701.   with FDIBInfo^.bmiHeader do
  2702.   begin
  2703.     if (Row < 0) or (Row >= Height) then
  2704.       raise EInvalidGraphicOperation.Create(SScanLine);
  2705.     GDIFlush;
  2706.  
  2707.     if biHeight > 0 then  // bottom-up DIB
  2708.       Row := biHeight - Row - 1;
  2709.     Result := PAnsiChar(Cardinal(FDIBBits) + Cardinal(Row) * AlignBit(biWidth, biBitCount, 32));
  2710.   end;
  2711. {$else}
  2712.   Result := FBitmap.ScanLine[Row];
  2713. {$endif}
  2714. end;
  2715.  
  2716. procedure TDIBWriter.CreateDIB;
  2717. {$IFDEF PIXELFORMAT_TOO_SLOW}
  2718. var
  2719.   SrcColors     : WORD;
  2720. //  ScreenDC        : HDC;
  2721.  
  2722.   // From Delphi 3.02 graphics.pas
  2723.   // There is a bug in the ByteSwapColors from Delphi 3.0!
  2724.   procedure ByteSwapColors(var Colors; Count: Integer);
  2725.   var   // convert RGB to BGR and vice-versa.  TRGBQuad <-> TPaletteEntry
  2726.     SysInfo: TSystemInfo;
  2727.   begin
  2728.     GetSystemInfo(SysInfo);
  2729.     asm
  2730.           MOV   EDX, Colors
  2731.           MOV   ECX, Count
  2732.           DEC   ECX
  2733.           JS    @@END
  2734.           LEA   EAX, SysInfo
  2735.           CMP   [EAX].TSystemInfo.wProcessorLevel, 3
  2736.           JE    @@386
  2737.     @@1:  MOV   EAX, [EDX+ECX*4]
  2738.           BSWAP EAX
  2739.           SHR   EAX,8
  2740.           MOV   [EDX+ECX*4],EAX
  2741.           DEC   ECX
  2742.           JNS   @@1
  2743.           JMP   @@END
  2744.     @@386:
  2745.           PUSH  EBX
  2746.     @@2:  XOR   EBX,EBX
  2747.           MOV   EAX, [EDX+ECX*4]
  2748.           MOV   BH, AL
  2749.           MOV   BL, AH
  2750.           SHR   EAX,16
  2751.           SHL   EBX,8
  2752.           MOV   BL, AL
  2753.           MOV   [EDX+ECX*4],EBX
  2754.           DEC   ECX
  2755.           JNS   @@2
  2756.           POP   EBX
  2757.       @@END:
  2758.     end;
  2759.   end;
  2760. {$ENDIF}
  2761. begin
  2762. {$ifdef PIXELFORMAT_TOO_SLOW}
  2763.   FreeDIB;
  2764.  
  2765.   if (PixelFormat = pf8bit) then
  2766.     // 8 bit: Header and palette
  2767.     FDIBInfoSize := SizeOf(TBitmapInfoHeader) + SizeOf(TRGBQuad) * (1 shl 8)
  2768.   else
  2769.     // 24 bit: Header but no palette
  2770.     FDIBInfoSize := SizeOf(TBitmapInfoHeader);
  2771.  
  2772.   // Allocate TBitmapInfo structure
  2773.   GetMem(FDIBInfo, FDIBInfoSize);
  2774.   try
  2775.     FDIBInfo^.bmiHeader.biSize := SizeOf(FDIBInfo^.bmiHeader);
  2776.     FDIBInfo^.bmiHeader.biWidth := Width;
  2777.     FDIBInfo^.bmiHeader.biHeight := Height;
  2778.     FDIBInfo^.bmiHeader.biPlanes := 1;
  2779.     FDIBInfo^.bmiHeader.biSizeImage := 0;
  2780.     FDIBInfo^.bmiHeader.biCompression := BI_RGB;
  2781.  
  2782.     if (PixelFormat = pf8bit) then
  2783.     begin
  2784.       FDIBInfo^.bmiHeader.biBitCount := 8;
  2785.       // Find number of colors defined by palette
  2786.       if (Palette <> 0) and
  2787.         (GetObject(Palette, sizeof(SrcColors), @SrcColors) <> 0) and
  2788.         (SrcColors <> 0) then
  2789.       begin
  2790.         // Copy all colors...
  2791.         GetPaletteEntries(Palette, 0, SrcColors, FDIBInfo^.bmiColors[0]);
  2792.         // ...and convert BGR to RGB
  2793.         ByteSwapColors(FDIBInfo^.bmiColors[0], SrcColors);
  2794.       end else
  2795.         SrcColors := 0;
  2796.  
  2797.       // Finally zero any unused entried
  2798.       if (SrcColors < 256) then
  2799.         FillChar(pointer(LongInt(@FDIBInfo^.bmiColors)+SizeOf(TRGBQuad)*SrcColors)^,
  2800.           256 - SrcColors, 0);
  2801.       FDIBInfo^.bmiHeader.biClrUsed := 256;
  2802.       FDIBInfo^.bmiHeader.biClrImportant := SrcColors;
  2803.     end else
  2804.     begin
  2805.       FDIBInfo^.bmiHeader.biBitCount := 24;
  2806.       FDIBInfo^.bmiHeader.biClrUsed := 0;
  2807.       FDIBInfo^.bmiHeader.biClrImportant := 0;
  2808.     end;
  2809.     FDIBBitsSize := AlignBit(Width, FDIBInfo^.bmiHeader.biBitCount, 32) * Cardinal(abs(Height));
  2810.  
  2811. {$ifdef CREATEDIBSECTION_SLOW}
  2812.     FDIBBits := GlobalAllocPtr(GMEM_MOVEABLE, FDIBBitsSize);
  2813.     if (FDIBBits = nil) then
  2814.       raise EOutOfMemory.Create(sOutOfMemDIB);
  2815. {$else}
  2816. //    ScreenDC := GDICheck(GetDC(0));
  2817.     try
  2818.       // Allocate DIB section
  2819.       // Note: You can ignore warnings about the HDC parameter being 0. The
  2820.       // parameter is not used for 24 bit bitmaps
  2821.       FDIB := GDICheck(CreateDIBSection(0 {ScreenDC}, FDIBInfo^, DIB_RGB_COLORS,
  2822.         FDIBBits,
  2823.         {$IFDEF VER9x} nil, {$ELSE} 0, {$ENDIF}
  2824.         0));
  2825.     finally
  2826. //      ReleaseDC(0, ScreenDC);
  2827.     end;
  2828. {$endif}
  2829.  
  2830.   except
  2831.     FreeDIB;
  2832.     raise;
  2833.   end;
  2834. {$endif}
  2835. end;
  2836.  
  2837. procedure TDIBWriter.FreeDIB;
  2838. begin
  2839. {$ifdef PIXELFORMAT_TOO_SLOW}
  2840.   if (FDIBInfo <> nil) then
  2841.     FreeMem(FDIBInfo);
  2842. {$ifdef CREATEDIBSECTION_SLOW}
  2843.   if (FDIBBits <> nil) then
  2844.     GlobalFreePtr(FDIBBits);
  2845. {$else}
  2846.   if (FDIB <> 0) then
  2847.     DeleteObject(FDIB);
  2848.   FDIB := 0;
  2849. {$endif}
  2850.   FDIBInfo := nil;
  2851.   FDIBBits := nil;
  2852. {$endif}
  2853. end;
  2854.  
  2855. procedure TDIBWriter.NeedDIB;
  2856. begin
  2857. {$ifdef PIXELFORMAT_TOO_SLOW}
  2858. {$ifdef CREATEDIBSECTION_SLOW}
  2859.   if (FDIBBits = nil) then
  2860. {$else}
  2861.   if (FDIB = 0) then
  2862. {$endif}
  2863.     CreateDIB;
  2864. {$endif}
  2865. end;
  2866.  
  2867. // Convert the DIB created by CreateDIB back to a TBitmap
  2868. procedure TDIBWriter.UpdateBitmap;
  2869. {$ifdef PIXELFORMAT_TOO_SLOW}
  2870. var
  2871.   Stream        : TMemoryStream;
  2872.   FileSize      : longInt;
  2873.   BitmapFileHeader  : TBitmapFileHeader;
  2874. {$endif}
  2875. begin
  2876. {$ifdef PIXELFORMAT_TOO_SLOW}
  2877.  
  2878. {$ifdef CREATEDIBSECTION_SLOW}
  2879.   if (FDIBBits = nil) then
  2880. {$else}
  2881.   if (FDIB = 0) then
  2882. {$endif}
  2883.     exit;
  2884.  
  2885.   // Win95 and NT differs in what solution performs best
  2886. {$ifndef CREATEDIBSECTION_SLOW}
  2887. {$ifdef VER10_PLUS}
  2888.   if (Win32Platform = VER_PLATFORM_WIN32_NT) then
  2889.   begin
  2890.     // Assign DIB to bitmap
  2891.     FBitmap.Handle := FDIB;
  2892.     FDIB := 0;
  2893.     FBitmap.Palette := CopyPalette(Palette);
  2894.   end else
  2895. {$endif}
  2896. {$endif}
  2897.   begin
  2898.     // Write DIB to a stream in the BMP file format
  2899.     Stream := TMemoryStream.Create;
  2900.     try
  2901.       // Make room in stream for a TBitmapInfo and pixel data
  2902.       FileSize := sizeof(TBitmapFileHeader) + FDIBInfoSize + FDIBBitsSize;
  2903.       Stream.SetSize(FileSize);
  2904.       // Initialize file header
  2905.       FillChar(BitmapFileHeader, sizeof(TBitmapFileHeader), 0);
  2906.       with BitmapFileHeader do
  2907.       begin
  2908.         bfType := $4D42; // 'BM' = Windows BMP signature
  2909.         bfSize := FileSize; // File size (not needed)
  2910.         bfOffBits := sizeof(TBitmapFileHeader) + FDIBInfoSize; // Offset of pixel data
  2911.       end;
  2912.       // Save file header
  2913.       Stream.Write(BitmapFileHeader, sizeof(TBitmapFileHeader));
  2914.       // Save TBitmapInfo structure
  2915.       Stream.Write(FDIBInfo^, FDIBInfoSize);
  2916.       // Save pixel data
  2917.       Stream.Write(FDIBBits^, FDIBBitsSize);
  2918.  
  2919.       // Rewind and load bitmap from stream
  2920.       Stream.Position := 0;
  2921.       FBitmap.LoadFromStream(Stream);
  2922.     finally
  2923.       Stream.Free;
  2924.     end;
  2925.   end;
  2926. {$endif}
  2927. end;
  2928.  
  2929. ////////////////////////////////////////////////////////////////////////////////
  2930. //
  2931. //          Color Mapping
  2932. //
  2933. ////////////////////////////////////////////////////////////////////////////////
  2934. type
  2935.   TColorLookup = class(TObject)
  2936.   private
  2937.     FColors     : integer;
  2938.   public
  2939.     constructor Create(Palette: hPalette); virtual;
  2940.     function Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; virtual; abstract;
  2941.     property Colors: integer read FColors;
  2942.   end;
  2943.  
  2944.   PRGBQuadArray = ^TRGBQuadArray;       // From Delphi 3 graphics.pas
  2945.   TRGBQuadArray = array[Byte] of TRGBQuad;  // From Delphi 3 graphics.pas
  2946.  
  2947.   BGRArray = array[0..0] of TRGBTriple;
  2948.   PBGRArray = ^BGRArray;
  2949.  
  2950.   PalArray =  array[byte] of TPaletteEntry;
  2951.   PPalArray = ^PalArray;
  2952.  
  2953.   // TFastColorLookup implements a simple but reasonably fast generic color
  2954.   // mapper. It trades precision for speed by reducing the size of the color
  2955.   // space.
  2956.   // Using a class instead of inline code results in a speed penalty of
  2957.   // approx. 15% but reduces the complexity of the color reduction routines that
  2958.   // uses it. If bitmap to GIF conversion speed is really important to you, the
  2959.   // implementation can easily be inlined again.
  2960.   TInverseLookup = array[0..1 SHL 15-1] of SmallInt;
  2961.   PInverseLookup = ^TInverseLookup;
  2962.  
  2963.   TFastColorLookup = class(TColorLookup)
  2964.   private
  2965.     FPaletteEntries : PPalArray;
  2966.     FInverseLookup  : PInverseLookup;
  2967.   public
  2968.     constructor Create(Palette: hPalette); override;
  2969.     destructor Destroy; override;
  2970.     function Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  2971.   end;
  2972.  
  2973.   // TSlowColorLookup implements a precise but very slow generic color mapper.
  2974.   // It uses the GetNearestPaletteIndex GDI function.
  2975.   // Note: Tests has shown TFastColorLookup to be more precise than
  2976.   // TSlowColorLookup in many cases. I can't explain why...
  2977.   TSlowColorLookup = class(TColorLookup)
  2978.   private
  2979.     FPaletteEntries : PPalArray;
  2980.     FPalette        : hPalette;
  2981.   public
  2982.     constructor Create(Palette: hPalette); override;
  2983.     destructor Destroy; override;
  2984.     function Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  2985.   end;
  2986.  
  2987.   // TNetscapeColorLookup maps colors to the netscape 6*6*6 color cube.
  2988.   TNetscapeColorLookup = class(TColorLookup)
  2989.   public
  2990.     constructor Create(Palette: hPalette); override;
  2991.     function Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  2992.   end;
  2993.  
  2994.   // TGrayWindowsLookup maps colors to 4 shade palette.
  2995.   TGrayWindowsLookup = class(TSlowColorLookup)
  2996.   public
  2997.     constructor Create(Palette: hPalette); override;
  2998.     function Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  2999.   end;
  3000.  
  3001.   // TGrayScaleLookup maps colors to a uniform 256 shade palette.
  3002.   TGrayScaleLookup = class(TColorLookup)
  3003.   public
  3004.     constructor Create(Palette: hPalette); override;
  3005.     function Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  3006.   end;
  3007.  
  3008.   // TMonochromeLookup maps colors to a black/white palette.
  3009.   TMonochromeLookup = class(TColorLookup)
  3010.   public
  3011.     constructor Create(Palette: hPalette); override;
  3012.     function Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  3013.   end;
  3014.  
  3015. constructor TColorLookup.Create(Palette: hPalette);
  3016. begin
  3017.   inherited Create;
  3018. end;
  3019.  
  3020. constructor TFastColorLookup.Create(Palette: hPalette);
  3021. var
  3022.   i         : integer;
  3023.   InverseIndex      : integer;
  3024. begin
  3025.   inherited Create(Palette);
  3026.  
  3027.   GetMem(FPaletteEntries, sizeof(TPaletteEntry) * 256);
  3028.   FColors := GetPaletteEntries(Palette, 0, 256, FPaletteEntries^);
  3029.  
  3030.   New(FInverseLookup);
  3031.   for i := low(TInverseLookup) to high(TInverseLookup) do
  3032.     FInverseLookup^[i] := -1;
  3033.  
  3034.   // Premap palette colors
  3035.   if (FColors > 0) then
  3036.     for i := 0 to FColors-1 do
  3037.       with FPaletteEntries^[i] do
  3038.       begin
  3039.         InverseIndex := (peRed SHR 3) OR ((peGreen AND $F8) SHL 2) OR ((peBlue AND $F8) SHL 7);
  3040.         if (FInverseLookup^[InverseIndex] = -1) then
  3041.           FInverseLookup^[InverseIndex] := i;
  3042.       end;
  3043. end;
  3044.  
  3045. destructor TFastColorLookup.Destroy;
  3046. begin
  3047.   if (FPaletteEntries <> nil) then
  3048.     FreeMem(FPaletteEntries);
  3049.   if (FInverseLookup <> nil) then
  3050.     Dispose(FInverseLookup);
  3051.  
  3052.   inherited Destroy;
  3053. end;
  3054.  
  3055. // Map color to arbitrary palette
  3056. function TFastColorLookup.Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3057. var
  3058.   i         : integer;
  3059.   InverseIndex      : integer;
  3060.   Delta         ,
  3061.   MinDelta      ,
  3062.   MinColor      : integer;
  3063. begin
  3064.   // Reduce color space with 3 bits in each dimension
  3065.   InverseIndex := (Red SHR 3) OR ((Green AND $F8) SHL 2) OR ((Blue AND $F8) SHL 7);
  3066.  
  3067.   if (FInverseLookup^[InverseIndex] <> -1) then
  3068.     Result := AnsiChar(FInverseLookup^[InverseIndex])
  3069.   else
  3070.   begin
  3071.     // Sequential scan for nearest color to minimize euclidian distance
  3072.     MinDelta := 3 * (256 * 256);
  3073.     MinColor := 0;
  3074.     for i := 0 to FColors-1 do
  3075.       with FPaletteEntries[i] do
  3076.       begin
  3077.         Delta := ABS(peRed - Red) + ABS(peGreen - Green) + ABS(peBlue - Blue);
  3078.         if (Delta < MinDelta) then
  3079.         begin
  3080.           MinDelta := Delta;
  3081.           MinColor := i;
  3082.         end;
  3083.       end;
  3084.     Result := AnsiChar(MinColor);
  3085.     FInverseLookup^[InverseIndex] := MinColor;
  3086.   end;
  3087.  
  3088.   with FPaletteEntries^[ord(Result)] do
  3089.   begin
  3090.     R := peRed;
  3091.     G := peGreen;
  3092.     B := peBlue;
  3093.   end;
  3094. end;
  3095.  
  3096. constructor TSlowColorLookup.Create(Palette: hPalette);
  3097. begin
  3098.   inherited Create(Palette);
  3099.   FPalette := Palette;
  3100.   FColors := GetPaletteEntries(Palette, 0, 256, nil^);
  3101.   if (FColors > 0) then
  3102.   begin
  3103.     GetMem(FPaletteEntries, sizeof(TPaletteEntry) * FColors);
  3104.     FColors := GetPaletteEntries(Palette, 0, 256, FPaletteEntries^);
  3105.   end;
  3106. end;
  3107.  
  3108. destructor TSlowColorLookup.Destroy;
  3109. begin
  3110.   if (FPaletteEntries <> nil) then
  3111.     FreeMem(FPaletteEntries);
  3112.  
  3113.   inherited Destroy;
  3114. end;
  3115.  
  3116. // Map color to arbitrary palette
  3117. function TSlowColorLookup.Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3118. begin
  3119.   Result := AnsiChar(GetNearestPaletteIndex(FPalette, Red OR (Green SHL 8) OR (Blue SHL 16)));
  3120.   if (FPaletteEntries <> nil) then
  3121.     with FPaletteEntries^[ord(Result)] do
  3122.     begin
  3123.       R := peRed;
  3124.       G := peGreen;
  3125.       B := peBlue;
  3126.     end;
  3127. end;
  3128.  
  3129. constructor TNetscapeColorLookup.Create(Palette: hPalette);
  3130. begin
  3131.   inherited Create(Palette);
  3132.   FColors := 6*6*6; // This better be true or something is wrong
  3133. end;
  3134.  
  3135. // Map color to netscape 6*6*6 color cube
  3136. function TNetscapeColorLookup.Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3137. begin
  3138.   R := (Red+3) DIV 51;
  3139.   G := (Green+3) DIV 51;
  3140.   B := (Blue+3) DIV 51;
  3141.   Result := AnsiChar(B + 6*G + 36*R);
  3142.   R := R * 51;
  3143.   G := G * 51;
  3144.   B := B * 51;
  3145. end;
  3146.  
  3147. constructor TGrayWindowsLookup.Create(Palette: hPalette);
  3148. begin
  3149.   inherited Create(Palette);
  3150.   FColors := 4;
  3151. end;
  3152.  
  3153. // Convert color to windows grays
  3154. function TGrayWindowsLookup.Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3155. begin
  3156.   Result := inherited Lookup(MulDiv(Red, 77, 256),
  3157.     MulDiv(Green, 150, 256), MulDiv(Blue, 29, 256), R, G, B);
  3158. end;
  3159.  
  3160. constructor TGrayScaleLookup.Create(Palette: hPalette);
  3161. begin
  3162.   inherited Create(Palette);
  3163.   FColors := 256;
  3164. end;
  3165.  
  3166. // Convert color to grayscale
  3167. function TGrayScaleLookup.Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3168. begin
  3169.   Result := AnsiChar((Blue*29 + Green*150 + Red*77) DIV 256);
  3170.   R := ord(Result);
  3171.   G := ord(Result);
  3172.   B := ord(Result);
  3173. end;
  3174.  
  3175. constructor TMonochromeLookup.Create(Palette: hPalette);
  3176. begin
  3177.   inherited Create(Palette);
  3178.   FColors := 2;
  3179. end;
  3180.  
  3181. // Convert color to black/white
  3182. function TMonochromeLookup.Lookup(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3183. begin
  3184.   if ((Blue*29 + Green*150 + Red*77) > 32512) then
  3185.   begin
  3186.     Result := #1;
  3187.     R := 255;
  3188.     G := 255;
  3189.     B := 255;
  3190.   end else
  3191.   begin
  3192.     Result := #0;
  3193.     R := 0;
  3194.     G := 0;
  3195.     B := 0;
  3196.   end;
  3197. end;
  3198.  
  3199. ////////////////////////////////////////////////////////////////////////////////
  3200. //
  3201. //          Dithering engine
  3202. //
  3203. ////////////////////////////////////////////////////////////////////////////////
  3204. type
  3205.   TDitherEngine = class
  3206.   private
  3207.   protected
  3208.     FDirection      : integer;
  3209.     FColumn     : integer;
  3210.     FLookup     : TColorLookup;
  3211.     Width       : integer;
  3212.   public
  3213.     constructor Create(AWidth: integer; Lookup: TColorLookup); virtual;
  3214.     function Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; virtual;
  3215.     procedure NextLine; virtual;
  3216.     procedure NextColumn;
  3217.  
  3218.     property Direction: integer read FDirection;
  3219.     property Column: integer read FColumn;
  3220.   end;
  3221.  
  3222.   // Note: TErrorTerm does only *need* to be 16 bits wide, but since
  3223.   // it is *much* faster to use native machine words (32 bit), we sacrifice
  3224.   // some bytes (a lot actually) to improve performance.
  3225.   TErrorTerm        = Integer;
  3226.   TErrors       = array[0..0] of TErrorTerm;
  3227.   PErrors       = ^TErrors;
  3228.  
  3229.   TFloydSteinbergDitherer = class(TDitherEngine)
  3230.   private
  3231.     ErrorsR     ,
  3232.     ErrorsG     ,
  3233.     ErrorsB     : PErrors;
  3234.     ErrorR      ,
  3235.     ErrorG      ,
  3236.     ErrorB      : PErrors;
  3237.     CurrentErrorR   ,       // Current error or pixel value
  3238.     CurrentErrorG   ,
  3239.     CurrentErrorB   ,
  3240.     BelowErrorR     ,       // Error for pixel below current
  3241.     BelowErrorG     ,
  3242.     BelowErrorB     ,
  3243.     BelowPrevErrorR ,       // Error for pixel below previous pixel
  3244.     BelowPrevErrorG ,
  3245.     BelowPrevErrorB : TErrorTerm;
  3246.   public
  3247.     constructor Create(AWidth: integer; Lookup: TColorLookup); override;
  3248.     destructor Destroy; override;
  3249.     function Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  3250.     procedure NextLine; override;
  3251.   end;
  3252.  
  3253.   T5by3Ditherer = class(TDitherEngine)
  3254.   private
  3255.     ErrorsR0        ,
  3256.     ErrorsG0        ,
  3257.     ErrorsB0        ,
  3258.     ErrorsR1        ,
  3259.     ErrorsG1        ,
  3260.     ErrorsB1        ,
  3261.     ErrorsR2        ,
  3262.     ErrorsG2        ,
  3263.     ErrorsB2        : PErrors;
  3264.     ErrorR0     ,
  3265.     ErrorG0     ,
  3266.     ErrorB0     ,
  3267.     ErrorR1     ,
  3268.     ErrorG1     ,
  3269.     ErrorB1     ,
  3270.     ErrorR2     ,
  3271.     ErrorG2     ,
  3272.     ErrorB2     : PErrors;
  3273.     FDirection2     : integer;
  3274.   protected
  3275.     FDivisor        : integer;
  3276.     procedure Propagate(Errors0, Errors1, Errors2: PErrors; Error: integer); virtual; abstract;
  3277.   public
  3278.     constructor Create(AWidth: integer; Lookup: TColorLookup); override;
  3279.     destructor Destroy; override;
  3280.     function Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  3281.     procedure NextLine; override;
  3282.   end;
  3283.  
  3284.   TStuckiDitherer = class(T5by3Ditherer)
  3285.   protected
  3286.     procedure Propagate(Errors0, Errors1, Errors2: PErrors; Error: integer); override;
  3287.   public
  3288.     constructor Create(AWidth: integer; Lookup: TColorLookup); override;
  3289.   end;
  3290.  
  3291.   TSierraDitherer = class(T5by3Ditherer)
  3292.   protected
  3293.     procedure Propagate(Errors0, Errors1, Errors2: PErrors; Error: integer); override;
  3294.   public
  3295.     constructor Create(AWidth: integer; Lookup: TColorLookup); override;
  3296.   end;
  3297.  
  3298.   TJaJuNiDitherer = class(T5by3Ditherer)
  3299.   protected
  3300.     procedure Propagate(Errors0, Errors1, Errors2: PErrors; Error: integer); override;
  3301.   public
  3302.     constructor Create(AWidth: integer; Lookup: TColorLookup); override;
  3303.   end;
  3304.  
  3305.   TSteveArcheDitherer = class(TDitherEngine)
  3306.   private
  3307.     ErrorsR0        ,
  3308.     ErrorsG0        ,
  3309.     ErrorsB0        ,
  3310.     ErrorsR1        ,
  3311.     ErrorsG1        ,
  3312.     ErrorsB1        ,
  3313.     ErrorsR2        ,
  3314.     ErrorsG2        ,
  3315.     ErrorsB2        ,
  3316.     ErrorsR3        ,
  3317.     ErrorsG3        ,
  3318.     ErrorsB3        : PErrors;
  3319.     ErrorR0     ,
  3320.     ErrorG0     ,
  3321.     ErrorB0     ,
  3322.     ErrorR1     ,
  3323.     ErrorG1     ,
  3324.     ErrorB1     ,
  3325.     ErrorR2     ,
  3326.     ErrorG2     ,
  3327.     ErrorB2     ,
  3328.     ErrorR3     ,
  3329.     ErrorG3     ,
  3330.     ErrorB3     : PErrors;
  3331.     FDirection2     ,
  3332.     FDirection3     : integer;
  3333.   public
  3334.     constructor Create(AWidth: integer; Lookup: TColorLookup); override;
  3335.     destructor Destroy; override;
  3336.     function Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  3337.     procedure NextLine; override;
  3338.   end;
  3339.  
  3340.   TBurkesDitherer = class(TDitherEngine)
  3341.   private
  3342.     ErrorsR0        ,
  3343.     ErrorsG0        ,
  3344.     ErrorsB0        ,
  3345.     ErrorsR1        ,
  3346.     ErrorsG1        ,
  3347.     ErrorsB1        : PErrors;
  3348.     ErrorR0     ,
  3349.     ErrorG0     ,
  3350.     ErrorB0     ,
  3351.     ErrorR1     ,
  3352.     ErrorG1     ,
  3353.     ErrorB1     : PErrors;
  3354.     FDirection2     : integer;
  3355.   public
  3356.     constructor Create(AWidth: integer; Lookup: TColorLookup); override;
  3357.     destructor Destroy; override;
  3358.     function Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar; override;
  3359.     procedure NextLine; override;
  3360.   end;
  3361.  
  3362. ////////////////////////////////////////////////////////////////////////////////
  3363. //  TDitherEngine
  3364. constructor TDitherEngine.Create(AWidth: integer; Lookup: TColorLookup);
  3365. begin
  3366.   inherited Create;
  3367.  
  3368.   FLookup := Lookup;
  3369.   Width := AWidth;
  3370.  
  3371.   FDirection := 1;
  3372.   FColumn := 0;
  3373. end;
  3374.  
  3375. function TDitherEngine.Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3376. begin
  3377.   // Map color to palette
  3378.   Result := FLookup.Lookup(Red, Green, Blue, R, G, B);
  3379.   NextColumn;
  3380. end;
  3381.  
  3382. procedure TDitherEngine.NextLine;
  3383. begin
  3384.   FDirection := -FDirection;
  3385.   if (FDirection = 1) then
  3386.     FColumn := 0
  3387.   else
  3388.     FColumn := Width-1;
  3389. end;
  3390.  
  3391. procedure TDitherEngine.NextColumn;
  3392. begin
  3393.   inc(FColumn, FDirection);
  3394. end;
  3395.  
  3396. ////////////////////////////////////////////////////////////////////////////////
  3397. //  TFloydSteinbergDitherer
  3398. constructor TFloydSteinbergDitherer.Create(AWidth: integer; Lookup: TColorLookup);
  3399. begin
  3400.   inherited Create(AWidth, Lookup);
  3401.  
  3402.   // The Error arrays has (columns + 2) entries; the extra entry at
  3403.   // each end saves us from special-casing the first and last pixels.
  3404.   // We can get away with a single array (holding one row's worth of errors)
  3405.   // by using it to store the current row's errors at pixel columns not yet
  3406.   // processed, but the next row's errors at columns already processed.  We
  3407.   // need only a few extra variables to hold the errors immediately around the
  3408.   // current column.  (If we are lucky, those variables are in registers, but
  3409.   // even if not, they're probably cheaper to access than array elements are.)
  3410.   GetMem(ErrorsR, sizeof(TErrorTerm)*(Width+2));
  3411.   GetMem(ErrorsG, sizeof(TErrorTerm)*(Width+2));
  3412.   GetMem(ErrorsB, sizeof(TErrorTerm)*(Width+2));
  3413.   FillChar(ErrorsR^, sizeof(TErrorTerm)*(Width+2), 0);
  3414.   FillChar(ErrorsG^, sizeof(TErrorTerm)*(Width+2), 0);
  3415.   FillChar(ErrorsB^, sizeof(TErrorTerm)*(Width+2), 0);
  3416.   ErrorR := ErrorsR;
  3417.   ErrorG := ErrorsG;
  3418.   ErrorB := ErrorsB;
  3419.   CurrentErrorR := 0;
  3420.   CurrentErrorG := CurrentErrorR;
  3421.   CurrentErrorB := CurrentErrorR;
  3422.   BelowErrorR := CurrentErrorR;
  3423.   BelowErrorG := CurrentErrorR;
  3424.   BelowErrorB := CurrentErrorR;
  3425.   BelowPrevErrorR := CurrentErrorR;
  3426.   BelowPrevErrorG := CurrentErrorR;
  3427.   BelowPrevErrorB := CurrentErrorR;
  3428. end;
  3429.  
  3430. destructor TFloydSteinbergDitherer.Destroy;
  3431. begin
  3432.   FreeMem(ErrorsR);
  3433.   FreeMem(ErrorsG);
  3434.   FreeMem(ErrorsB);
  3435.   inherited Destroy;
  3436. end;
  3437.  
  3438. {$IFOPT R+}
  3439.   {$DEFINE R_PLUS}
  3440.   {$RANGECHECKS OFF}
  3441. {$ENDIF}
  3442. function TFloydSteinbergDitherer.Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3443. var
  3444.   BelowNextError    : TErrorTerm;
  3445.   Delta         : TErrorTerm;
  3446. begin
  3447.   CurrentErrorR := Red + (CurrentErrorR + ErrorR[0] + 8) DIV 16;
  3448. //  CurrentErrorR := Red + (CurrentErrorR + ErrorR[Direction] + 8) DIV 16;
  3449.   if (CurrentErrorR < 0) then
  3450.     CurrentErrorR := 0
  3451.   else if (CurrentErrorR > 255) then
  3452.     CurrentErrorR := 255;
  3453.  
  3454.   CurrentErrorG := Green + (CurrentErrorG + ErrorG[0] + 8) DIV 16;
  3455. //  CurrentErrorG := Green + (CurrentErrorG + ErrorG[Direction] + 8) DIV 16;
  3456.   if (CurrentErrorG < 0) then
  3457.     CurrentErrorG := 0
  3458.   else if (CurrentErrorG > 255) then
  3459.     CurrentErrorG := 255;
  3460.  
  3461.   CurrentErrorB := Blue + (CurrentErrorB + ErrorB[0] + 8) DIV 16;
  3462. //  CurrentErrorB := Blue + (CurrentErrorB + ErrorB[Direction] + 8) DIV 16;
  3463.   if (CurrentErrorB < 0) then
  3464.     CurrentErrorB := 0
  3465.   else if (CurrentErrorB > 255) then
  3466.     CurrentErrorB := 255;
  3467.  
  3468.   // Map color to palette
  3469.   Result := inherited Dither(CurrentErrorR, CurrentErrorG, CurrentErrorB, R, G, B);
  3470.  
  3471.   // Propagate Floyd-Steinberg error terms.
  3472.   // Errors are accumulated into the error arrays, at a resolution of
  3473.   // 1/16th of a pixel count.  The error at a given pixel is propagated
  3474.   // to its not-yet-processed neighbors using the standard F-S fractions,
  3475.   //        ... (here)  7/16
  3476.   //        3/16    5/16    1/16
  3477.   // We work left-to-right on even rows, right-to-left on odd rows.
  3478.  
  3479.   // Red component
  3480.   CurrentErrorR := CurrentErrorR - R;
  3481.   if (CurrentErrorR <> 0) then
  3482.   begin
  3483.     BelowNextError := CurrentErrorR;            // Error * 1
  3484.  
  3485.     Delta := CurrentErrorR * 2;
  3486.     inc(CurrentErrorR, Delta);
  3487.     ErrorR[0] := BelowPrevErrorR + CurrentErrorR;   // Error * 3
  3488.  
  3489.     inc(CurrentErrorR, Delta);
  3490.     BelowPrevErrorR := BelowErrorR + CurrentErrorR; // Error * 5
  3491.  
  3492.     BelowErrorR := BelowNextError;          // Error * 1
  3493.  
  3494.     inc(CurrentErrorR, Delta);              // Error * 7
  3495.   end;
  3496.  
  3497.   // Green component
  3498.   CurrentErrorG := CurrentErrorG - G;
  3499.   if (CurrentErrorG <> 0) then
  3500.   begin
  3501.     BelowNextError := CurrentErrorG;            // Error * 1
  3502.  
  3503.     Delta := CurrentErrorG * 2;
  3504.     inc(CurrentErrorG, Delta);
  3505.     ErrorG[0] := BelowPrevErrorG + CurrentErrorG;   // Error * 3
  3506.  
  3507.     inc(CurrentErrorG, Delta);
  3508.     BelowPrevErrorG := BelowErrorG + CurrentErrorG; // Error * 5
  3509.  
  3510.     BelowErrorG := BelowNextError;          // Error * 1
  3511.  
  3512.     inc(CurrentErrorG, Delta);              // Error * 7
  3513.   end;
  3514.  
  3515.   // Blue component
  3516.   CurrentErrorB := CurrentErrorB - B;
  3517.   if (CurrentErrorB <> 0) then
  3518.   begin
  3519.     BelowNextError := CurrentErrorB;            // Error * 1
  3520.  
  3521.     Delta := CurrentErrorB * 2;
  3522.     inc(CurrentErrorB, Delta);
  3523.     ErrorB[0] := BelowPrevErrorB + CurrentErrorB;   // Error * 3
  3524.  
  3525.     inc(CurrentErrorB, Delta);
  3526.     BelowPrevErrorB := BelowErrorB + CurrentErrorB; // Error * 5
  3527.  
  3528.     BelowErrorB := BelowNextError;          // Error * 1
  3529.  
  3530.     inc(CurrentErrorB, Delta);              // Error * 7
  3531.   end;
  3532.  
  3533.   // Move on to next column
  3534.   if (Direction = 1) then
  3535.   begin
  3536.     inc(longInt(ErrorR), sizeof(TErrorTerm));
  3537.     inc(longInt(ErrorG), sizeof(TErrorTerm));
  3538.     inc(longInt(ErrorB), sizeof(TErrorTerm));
  3539.   end else
  3540.   begin
  3541.     dec(longInt(ErrorR), sizeof(TErrorTerm));
  3542.     dec(longInt(ErrorG), sizeof(TErrorTerm));
  3543.     dec(longInt(ErrorB), sizeof(TErrorTerm));
  3544.   end;
  3545. end;
  3546. {$IFDEF R_PLUS}
  3547.   {$RANGECHECKS ON}
  3548.   {$UNDEF R_PLUS}
  3549. {$ENDIF}
  3550.  
  3551. {$IFOPT R+}
  3552.   {$DEFINE R_PLUS}
  3553.   {$RANGECHECKS OFF}
  3554. {$ENDIF}
  3555. procedure TFloydSteinbergDitherer.NextLine;
  3556. begin
  3557.   ErrorR[0] := BelowPrevErrorR;
  3558.   ErrorG[0] := BelowPrevErrorG;
  3559.   ErrorB[0] := BelowPrevErrorB;
  3560.  
  3561.   // Note: The optimizer produces better code for this construct:
  3562.   //   a := 0; b := a; c := a;
  3563.   // compared to this construct:
  3564.   //   a := 0; b := 0; c := 0;
  3565.   CurrentErrorR := 0;
  3566.   CurrentErrorG := CurrentErrorR;
  3567.   CurrentErrorB := CurrentErrorG;
  3568.   BelowErrorR := CurrentErrorG;
  3569.   BelowErrorG := CurrentErrorG;
  3570.   BelowErrorB := CurrentErrorG;
  3571.   BelowPrevErrorR := CurrentErrorG;
  3572.   BelowPrevErrorG := CurrentErrorG;
  3573.   BelowPrevErrorB := CurrentErrorG;
  3574.  
  3575.   inherited NextLine;
  3576.  
  3577.   if (Direction = 1) then
  3578.   begin
  3579.     ErrorR := ErrorsR;
  3580.     ErrorG := ErrorsG;
  3581.     ErrorB := ErrorsB;
  3582.   end else
  3583.   begin
  3584.     ErrorR := @ErrorsR[Width+1];
  3585.     ErrorG := @ErrorsG[Width+1];
  3586.     ErrorB := @ErrorsB[Width+1];
  3587.   end;
  3588. end;
  3589. {$IFDEF R_PLUS}
  3590.   {$RANGECHECKS ON}
  3591.   {$UNDEF R_PLUS}
  3592. {$ENDIF}
  3593.  
  3594. ////////////////////////////////////////////////////////////////////////////////
  3595. //  T5by3Ditherer
  3596. constructor T5by3Ditherer.Create(AWidth: integer; Lookup: TColorLookup);
  3597. begin
  3598.   inherited Create(AWidth, Lookup);
  3599.  
  3600.   GetMem(ErrorsR0, sizeof(TErrorTerm)*(Width+4));
  3601.   GetMem(ErrorsG0, sizeof(TErrorTerm)*(Width+4));
  3602.   GetMem(ErrorsB0, sizeof(TErrorTerm)*(Width+4));
  3603.   GetMem(ErrorsR1, sizeof(TErrorTerm)*(Width+4));
  3604.   GetMem(ErrorsG1, sizeof(TErrorTerm)*(Width+4));
  3605.   GetMem(ErrorsB1, sizeof(TErrorTerm)*(Width+4));
  3606.   GetMem(ErrorsR2, sizeof(TErrorTerm)*(Width+4));
  3607.   GetMem(ErrorsG2, sizeof(TErrorTerm)*(Width+4));
  3608.   GetMem(ErrorsB2, sizeof(TErrorTerm)*(Width+4));
  3609.   FillChar(ErrorsR0^, sizeof(TErrorTerm)*(Width+4), 0);
  3610.   FillChar(ErrorsG0^, sizeof(TErrorTerm)*(Width+4), 0);
  3611.   FillChar(ErrorsB0^, sizeof(TErrorTerm)*(Width+4), 0);
  3612.   FillChar(ErrorsR1^, sizeof(TErrorTerm)*(Width+4), 0);
  3613.   FillChar(ErrorsG1^, sizeof(TErrorTerm)*(Width+4), 0);
  3614.   FillChar(ErrorsB1^, sizeof(TErrorTerm)*(Width+4), 0);
  3615.   FillChar(ErrorsR2^, sizeof(TErrorTerm)*(Width+4), 0);
  3616.   FillChar(ErrorsG2^, sizeof(TErrorTerm)*(Width+4), 0);
  3617.   FillChar(ErrorsB2^, sizeof(TErrorTerm)*(Width+4), 0);
  3618.  
  3619.   FDivisor := 1;
  3620.   FDirection2 := 2 * Direction;
  3621.   ErrorR0 := PErrors(longInt(ErrorsR0)+2*sizeof(TErrorTerm));
  3622.   ErrorG0 := PErrors(longInt(ErrorsG0)+2*sizeof(TErrorTerm));
  3623.   ErrorB0 := PErrors(longInt(ErrorsB0)+2*sizeof(TErrorTerm));
  3624.   ErrorR1 := PErrors(longInt(ErrorsR1)+2*sizeof(TErrorTerm));
  3625.   ErrorG1 := PErrors(longInt(ErrorsG1)+2*sizeof(TErrorTerm));
  3626.   ErrorB1 := PErrors(longInt(ErrorsB1)+2*sizeof(TErrorTerm));
  3627.   ErrorR2 := PErrors(longInt(ErrorsR2)+2*sizeof(TErrorTerm));
  3628.   ErrorG2 := PErrors(longInt(ErrorsG2)+2*sizeof(TErrorTerm));
  3629.   ErrorB2 := PErrors(longInt(ErrorsB2)+2*sizeof(TErrorTerm));
  3630. end;
  3631.  
  3632. destructor T5by3Ditherer.Destroy;
  3633. begin
  3634.   FreeMem(ErrorsR0);
  3635.   FreeMem(ErrorsG0);
  3636.   FreeMem(ErrorsB0);
  3637.   FreeMem(ErrorsR1);
  3638.   FreeMem(ErrorsG1);
  3639.   FreeMem(ErrorsB1);
  3640.   FreeMem(ErrorsR2);
  3641.   FreeMem(ErrorsG2);
  3642.   FreeMem(ErrorsB2);
  3643.   inherited Destroy;
  3644. end;
  3645.  
  3646. {$IFOPT R+}
  3647.   {$DEFINE R_PLUS}
  3648.   {$RANGECHECKS OFF}
  3649. {$ENDIF}
  3650. function T5by3Ditherer.Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3651. var
  3652.   ColorR        ,
  3653.   ColorG        ,
  3654.   ColorB        : integer; // Error for current pixel
  3655. begin
  3656.   // Apply red component error correction
  3657.   ColorR := Red + (ErrorR0[0] + FDivisor DIV 2) DIV FDivisor;
  3658.   if (ColorR < 0) then
  3659.     ColorR := 0
  3660.   else if (ColorR > 255) then
  3661.     ColorR := 255;
  3662.  
  3663.   // Apply green component error correction
  3664.   ColorG := Green + (ErrorG0[0] + FDivisor DIV 2) DIV FDivisor;
  3665.   if (ColorG < 0) then
  3666.     ColorG := 0
  3667.   else if (ColorG > 255) then
  3668.     ColorG := 255;
  3669.  
  3670.   // Apply blue component error correction
  3671.   ColorB := Blue + (ErrorB0[0] + FDivisor DIV 2) DIV FDivisor;
  3672.   if (ColorB < 0) then
  3673.     ColorB := 0
  3674.   else if (ColorB > 255) then
  3675.     ColorB := 255;
  3676.  
  3677.   // Map color to palette
  3678.   Result := inherited Dither(ColorR, ColorG, ColorB, R, G, B);
  3679.  
  3680.   // Propagate red component error
  3681.   Propagate(ErrorR0, ErrorR1, ErrorR2, ColorR - R);
  3682.   // Propagate green component error
  3683.   Propagate(ErrorG0, ErrorG1, ErrorG2, ColorG - G);
  3684.   // Propagate blue component error
  3685.   Propagate(ErrorB0, ErrorB1, ErrorB2, ColorB - B);
  3686.  
  3687.   // Move on to next column
  3688.   if (Direction = 1) then
  3689.   begin
  3690.     inc(longInt(ErrorR0), sizeof(TErrorTerm));
  3691.     inc(longInt(ErrorG0), sizeof(TErrorTerm));
  3692.     inc(longInt(ErrorB0), sizeof(TErrorTerm));
  3693.     inc(longInt(ErrorR1), sizeof(TErrorTerm));
  3694.     inc(longInt(ErrorG1), sizeof(TErrorTerm));
  3695.     inc(longInt(ErrorB1), sizeof(TErrorTerm));
  3696.     inc(longInt(ErrorR2), sizeof(TErrorTerm));
  3697.     inc(longInt(ErrorG2), sizeof(TErrorTerm));
  3698.     inc(longInt(ErrorB2), sizeof(TErrorTerm));
  3699.   end else
  3700.   begin
  3701.     dec(longInt(ErrorR0), sizeof(TErrorTerm));
  3702.     dec(longInt(ErrorG0), sizeof(TErrorTerm));
  3703.     dec(longInt(ErrorB0), sizeof(TErrorTerm));
  3704.     dec(longInt(ErrorR1), sizeof(TErrorTerm));
  3705.     dec(longInt(ErrorG1), sizeof(TErrorTerm));
  3706.     dec(longInt(ErrorB1), sizeof(TErrorTerm));
  3707.     dec(longInt(ErrorR2), sizeof(TErrorTerm));
  3708.     dec(longInt(ErrorG2), sizeof(TErrorTerm));
  3709.     dec(longInt(ErrorB2), sizeof(TErrorTerm));
  3710.   end;
  3711. end;
  3712. {$IFDEF R_PLUS}
  3713.   {$RANGECHECKS ON}
  3714.   {$UNDEF R_PLUS}
  3715. {$ENDIF}
  3716.  
  3717. {$IFOPT R+}
  3718.   {$DEFINE R_PLUS}
  3719.   {$RANGECHECKS OFF}
  3720. {$ENDIF}
  3721. procedure T5by3Ditherer.NextLine;
  3722. var
  3723.   TempErrors        : PErrors;
  3724. begin
  3725.   FillChar(ErrorsR0^, sizeof(TErrorTerm)*(Width+4), 0);
  3726.   FillChar(ErrorsG0^, sizeof(TErrorTerm)*(Width+4), 0);
  3727.   FillChar(ErrorsB0^, sizeof(TErrorTerm)*(Width+4), 0);
  3728.  
  3729.   // Swap lines
  3730.   TempErrors := ErrorsR0;
  3731.   ErrorsR0 := ErrorsR1;
  3732.   ErrorsR1 := ErrorsR2;
  3733.   ErrorsR2 := TempErrors;
  3734.  
  3735.   TempErrors := ErrorsG0;
  3736.   ErrorsG0 := ErrorsG1;
  3737.   ErrorsG1 := ErrorsG2;
  3738.   ErrorsG2 := TempErrors;
  3739.  
  3740.   TempErrors := ErrorsB0;
  3741.   ErrorsB0 := ErrorsB1;
  3742.   ErrorsB1 := ErrorsB2;
  3743.   ErrorsB2 := TempErrors;
  3744.  
  3745.   inherited NextLine;
  3746.  
  3747.   FDirection2 := 2 * Direction;
  3748.   if (Direction = 1) then
  3749.   begin
  3750.     // ErrorsR0[1] gives compiler error, so we
  3751.     // use PErrors(longInt(ErrorsR0)+sizeof(TErrorTerm)) instead...
  3752.     ErrorR0 := PErrors(longInt(ErrorsR0)+2*sizeof(TErrorTerm));
  3753.     ErrorG0 := PErrors(longInt(ErrorsG0)+2*sizeof(TErrorTerm));
  3754.     ErrorB0 := PErrors(longInt(ErrorsB0)+2*sizeof(TErrorTerm));
  3755.     ErrorR1 := PErrors(longInt(ErrorsR1)+2*sizeof(TErrorTerm));
  3756.     ErrorG1 := PErrors(longInt(ErrorsG1)+2*sizeof(TErrorTerm));
  3757.     ErrorB1 := PErrors(longInt(ErrorsB1)+2*sizeof(TErrorTerm));
  3758.     ErrorR2 := PErrors(longInt(ErrorsR2)+2*sizeof(TErrorTerm));
  3759.     ErrorG2 := PErrors(longInt(ErrorsG2)+2*sizeof(TErrorTerm));
  3760.     ErrorB2 := PErrors(longInt(ErrorsB2)+2*sizeof(TErrorTerm));
  3761.   end else
  3762.   begin
  3763.     ErrorR0 := @ErrorsR0[Width+1];
  3764.     ErrorG0 := @ErrorsG0[Width+1];
  3765.     ErrorB0 := @ErrorsB0[Width+1];
  3766.     ErrorR1 := @ErrorsR1[Width+1];
  3767.     ErrorG1 := @ErrorsG1[Width+1];
  3768.     ErrorB1 := @ErrorsB1[Width+1];
  3769.     ErrorR2 := @ErrorsR2[Width+1];
  3770.     ErrorG2 := @ErrorsG2[Width+1];
  3771.     ErrorB2 := @ErrorsB2[Width+1];
  3772.   end;
  3773. end;
  3774. {$IFDEF R_PLUS}
  3775.   {$RANGECHECKS ON}
  3776.   {$UNDEF R_PLUS}
  3777. {$ENDIF}
  3778.  
  3779. ////////////////////////////////////////////////////////////////////////////////
  3780. //  TStuckiDitherer
  3781. constructor TStuckiDitherer.Create(AWidth: integer; Lookup: TColorLookup);
  3782. begin
  3783.   inherited Create(AWidth, Lookup);
  3784.   FDivisor := 42;
  3785. end;
  3786.  
  3787. {$IFOPT R+}
  3788.   {$DEFINE R_PLUS}
  3789.   {$RANGECHECKS OFF}
  3790. {$ENDIF}
  3791. procedure TStuckiDitherer.Propagate(Errors0, Errors1, Errors2: PErrors; Error: integer);
  3792. begin
  3793.   if (Error = 0) then
  3794.     exit;
  3795.   // Propagate Stucki error terms:
  3796.   //    ... ... (here)  8/42    4/42
  3797.   //    2/42    4/42    8/42    4/42    2/42
  3798.   //    1/42    2/42    4/42    2/42    1/42
  3799.   inc(Errors2[FDirection2], Error); // Error * 1
  3800.   inc(Errors2[-FDirection2], Error);    // Error * 1
  3801.  
  3802.   Error := Error + Error;
  3803.   inc(Errors1[FDirection2], Error); // Error * 2
  3804.   inc(Errors1[-FDirection2], Error);    // Error * 2
  3805.   inc(Errors2[Direction], Error);   // Error * 2
  3806.   inc(Errors2[-Direction], Error);  // Error * 2
  3807.  
  3808.   Error := Error + Error;
  3809.   inc(Errors0[FDirection2], Error); // Error * 4
  3810.   inc(Errors1[-Direction], Error);  // Error * 4
  3811.   inc(Errors1[Direction], Error);   // Error * 4
  3812.   inc(Errors2[0], Error);       // Error * 4
  3813.  
  3814.   Error := Error + Error;
  3815.   inc(Errors0[Direction], Error);   // Error * 8
  3816.   inc(Errors1[0], Error);       // Error * 8
  3817. end;
  3818. {$IFDEF R_PLUS}
  3819.   {$RANGECHECKS ON}
  3820.   {$UNDEF R_PLUS}
  3821. {$ENDIF}
  3822.  
  3823. ////////////////////////////////////////////////////////////////////////////////
  3824. //  TSierraDitherer
  3825. constructor TSierraDitherer.Create(AWidth: integer; Lookup: TColorLookup);
  3826. begin
  3827.   inherited Create(AWidth, Lookup);
  3828.   FDivisor := 32;
  3829. end;
  3830.  
  3831. {$IFOPT R+}
  3832.   {$DEFINE R_PLUS}
  3833.   {$RANGECHECKS OFF}
  3834. {$ENDIF}
  3835. procedure TSierraDitherer.Propagate(Errors0, Errors1, Errors2: PErrors; Error: integer);
  3836. var
  3837.   TempError     : integer;
  3838. begin
  3839.   if (Error = 0) then
  3840.     exit;
  3841.   // Propagate Sierra error terms:
  3842.   //    ... ... (here)  5/32    3/32
  3843.   //    2/32    4/32    5/32    4/32    2/32
  3844.   //    ... 2/32    3/32    2/32    ...
  3845.   TempError := Error + Error;
  3846.   inc(Errors1[FDirection2], TempError); // Error * 2
  3847.   inc(Errors1[-FDirection2], TempError);// Error * 2
  3848.   inc(Errors2[Direction], TempError);   // Error * 2
  3849.   inc(Errors2[-Direction], TempError);  // Error * 2
  3850.  
  3851.   inc(TempError, Error);
  3852.   inc(Errors0[FDirection2], TempError); // Error * 3
  3853.   inc(Errors2[0], TempError);       // Error * 3
  3854.  
  3855.   inc(TempError, Error);
  3856.   inc(Errors1[-Direction], TempError);  // Error * 4
  3857.   inc(Errors1[Direction], TempError);   // Error * 4
  3858.  
  3859.   inc(TempError, Error);
  3860.   inc(Errors0[Direction], TempError);   // Error * 5
  3861.   inc(Errors1[0], TempError);       // Error * 5
  3862. end;
  3863. {$IFDEF R_PLUS}
  3864.   {$RANGECHECKS ON}
  3865.   {$UNDEF R_PLUS}
  3866. {$ENDIF}
  3867.  
  3868. ////////////////////////////////////////////////////////////////////////////////
  3869. //  TJaJuNiDitherer
  3870. constructor TJaJuNiDitherer.Create(AWidth: integer; Lookup: TColorLookup);
  3871. begin
  3872.   inherited Create(AWidth, Lookup);
  3873.   FDivisor := 38;
  3874. end;
  3875.  
  3876. {$IFOPT R+}
  3877.   {$DEFINE R_PLUS}
  3878.   {$RANGECHECKS OFF}
  3879. {$ENDIF}
  3880. procedure TJaJuNiDitherer.Propagate(Errors0, Errors1, Errors2: PErrors; Error: integer);
  3881. var
  3882.   TempError     : integer;
  3883. begin
  3884.   if (Error = 0) then
  3885.     exit;
  3886.   // Propagate Jarvis, Judice and Ninke error terms:
  3887.   //    ... ... (here)  8/38    4/38
  3888.   //    2/38    4/38    8/38    4/38    2/38
  3889.   //    1/38    2/38    4/38    2/38    1/38
  3890.   inc(Errors2[FDirection2], Error); // Error * 1
  3891.   inc(Errors2[-FDirection2], Error);    // Error * 1
  3892.  
  3893.   TempError := Error + Error;
  3894.   inc(Error, TempError);
  3895.   inc(Errors1[FDirection2], Error); // Error * 3
  3896.   inc(Errors1[-FDirection2], Error);    // Error * 3
  3897.   inc(Errors2[Direction], Error);   // Error * 3
  3898.   inc(Errors2[-Direction], Error);  // Error * 3
  3899.  
  3900.   inc(Error, TempError);
  3901.   inc(Errors0[FDirection2], Error); // Error * 5
  3902.   inc(Errors1[-Direction], Error);  // Error * 5
  3903.   inc(Errors1[Direction], Error);   // Error * 5
  3904.   inc(Errors2[0], Error);       // Error * 5
  3905.  
  3906.   inc(Error, TempError);
  3907.   inc(Errors0[Direction], Error);   // Error * 7
  3908.   inc(Errors1[0], Error);       // Error * 7
  3909. end;
  3910. {$IFDEF R_PLUS}
  3911.   {$RANGECHECKS ON}
  3912.   {$UNDEF R_PLUS}
  3913. {$ENDIF}
  3914.  
  3915. ////////////////////////////////////////////////////////////////////////////////
  3916. //  TSteveArcheDitherer
  3917. constructor TSteveArcheDitherer.Create(AWidth: integer; Lookup: TColorLookup);
  3918. begin
  3919.   inherited Create(AWidth, Lookup);
  3920.  
  3921.   GetMem(ErrorsR0, sizeof(TErrorTerm)*(Width+6));
  3922.   GetMem(ErrorsG0, sizeof(TErrorTerm)*(Width+6));
  3923.   GetMem(ErrorsB0, sizeof(TErrorTerm)*(Width+6));
  3924.   GetMem(ErrorsR1, sizeof(TErrorTerm)*(Width+6));
  3925.   GetMem(ErrorsG1, sizeof(TErrorTerm)*(Width+6));
  3926.   GetMem(ErrorsB1, sizeof(TErrorTerm)*(Width+6));
  3927.   GetMem(ErrorsR2, sizeof(TErrorTerm)*(Width+6));
  3928.   GetMem(ErrorsG2, sizeof(TErrorTerm)*(Width+6));
  3929.   GetMem(ErrorsB2, sizeof(TErrorTerm)*(Width+6));
  3930.   GetMem(ErrorsR3, sizeof(TErrorTerm)*(Width+6));
  3931.   GetMem(ErrorsG3, sizeof(TErrorTerm)*(Width+6));
  3932.   GetMem(ErrorsB3, sizeof(TErrorTerm)*(Width+6));
  3933.   FillChar(ErrorsR0^, sizeof(TErrorTerm)*(Width+6), 0);
  3934.   FillChar(ErrorsG0^, sizeof(TErrorTerm)*(Width+6), 0);
  3935.   FillChar(ErrorsB0^, sizeof(TErrorTerm)*(Width+6), 0);
  3936.   FillChar(ErrorsR1^, sizeof(TErrorTerm)*(Width+6), 0);
  3937.   FillChar(ErrorsG1^, sizeof(TErrorTerm)*(Width+6), 0);
  3938.   FillChar(ErrorsB1^, sizeof(TErrorTerm)*(Width+6), 0);
  3939.   FillChar(ErrorsR2^, sizeof(TErrorTerm)*(Width+6), 0);
  3940.   FillChar(ErrorsG2^, sizeof(TErrorTerm)*(Width+6), 0);
  3941.   FillChar(ErrorsB2^, sizeof(TErrorTerm)*(Width+6), 0);
  3942.   FillChar(ErrorsR3^, sizeof(TErrorTerm)*(Width+6), 0);
  3943.   FillChar(ErrorsG3^, sizeof(TErrorTerm)*(Width+6), 0);
  3944.   FillChar(ErrorsB3^, sizeof(TErrorTerm)*(Width+6), 0);
  3945.  
  3946.   FDirection2 := 2 * Direction;
  3947.   FDirection3 := 3 * Direction;
  3948.  
  3949.   ErrorR0 := PErrors(longInt(ErrorsR0)+3*sizeof(TErrorTerm));
  3950.   ErrorG0 := PErrors(longInt(ErrorsG0)+3*sizeof(TErrorTerm));
  3951.   ErrorB0 := PErrors(longInt(ErrorsB0)+3*sizeof(TErrorTerm));
  3952.   ErrorR1 := PErrors(longInt(ErrorsR1)+3*sizeof(TErrorTerm));
  3953.   ErrorG1 := PErrors(longInt(ErrorsG1)+3*sizeof(TErrorTerm));
  3954.   ErrorB1 := PErrors(longInt(ErrorsB1)+3*sizeof(TErrorTerm));
  3955.   ErrorR2 := PErrors(longInt(ErrorsR2)+3*sizeof(TErrorTerm));
  3956.   ErrorG2 := PErrors(longInt(ErrorsG2)+3*sizeof(TErrorTerm));
  3957.   ErrorB2 := PErrors(longInt(ErrorsB2)+3*sizeof(TErrorTerm));
  3958.   ErrorR3 := PErrors(longInt(ErrorsR3)+3*sizeof(TErrorTerm));
  3959.   ErrorG3 := PErrors(longInt(ErrorsG3)+3*sizeof(TErrorTerm));
  3960.   ErrorB3 := PErrors(longInt(ErrorsB3)+3*sizeof(TErrorTerm));
  3961. end;
  3962.  
  3963. destructor TSteveArcheDitherer.Destroy;
  3964. begin
  3965.   FreeMem(ErrorsR0);
  3966.   FreeMem(ErrorsG0);
  3967.   FreeMem(ErrorsB0);
  3968.   FreeMem(ErrorsR1);
  3969.   FreeMem(ErrorsG1);
  3970.   FreeMem(ErrorsB1);
  3971.   FreeMem(ErrorsR2);
  3972.   FreeMem(ErrorsG2);
  3973.   FreeMem(ErrorsB2);
  3974.   FreeMem(ErrorsR3);
  3975.   FreeMem(ErrorsG3);
  3976.   FreeMem(ErrorsB3);
  3977.   inherited Destroy;
  3978. end;
  3979.  
  3980. {$IFOPT R+}
  3981.   {$DEFINE R_PLUS}
  3982.   {$RANGECHECKS OFF}
  3983. {$ENDIF}
  3984. function TSteveArcheDitherer.Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  3985. var
  3986.   ColorR        ,
  3987.   ColorG        ,
  3988.   ColorB        : integer; // Error for current pixel
  3989.  
  3990.   // Propagate Stevenson & Arche error terms:
  3991.   //    ... ... ... (here)  ... 32/200  ...
  3992.   //    12/200  ... 26/200  ... 30/200  ... 16/200
  3993.   //    ... 12/200  ... 26/200  ... 12/200  ...
  3994.   //    5/200   ... 12/200  ... 12/200  ... 5/200
  3995.   procedure Propagate(Errors0, Errors1, Errors2, Errors3: PErrors; Error: integer);
  3996.   var
  3997.     TempError       : integer;
  3998.   begin
  3999.     if (Error = 0) then
  4000.       exit;
  4001.     TempError := 5 * Error;
  4002.     inc(Errors3[FDirection3], TempError);   // Error * 5
  4003.     inc(Errors3[-FDirection3], TempError);  // Error * 5
  4004.  
  4005.     TempError := 12 * Error;
  4006.     inc(Errors1[-FDirection3], TempError);  // Error * 12
  4007.     inc(Errors2[-FDirection2], TempError);  // Error * 12
  4008.     inc(Errors2[FDirection2], TempError);   // Error * 12
  4009.     inc(Errors3[-Direction], TempError);    // Error * 12
  4010.     inc(Errors3[Direction], TempError);     // Error * 12
  4011.  
  4012.     inc(Errors1[FDirection3], 16 * TempError);  // Error * 16
  4013.  
  4014.     TempError := 26 * Error;
  4015.     inc(Errors1[-Direction], TempError);    // Error * 26
  4016.     inc(Errors2[0], TempError);         // Error * 26
  4017.  
  4018.     inc(Errors1[Direction], 30 * Error);    // Error * 30
  4019.  
  4020.     inc(Errors0[FDirection2], 32 * Error);  // Error * 32
  4021.   end;
  4022.  
  4023. begin
  4024.   // Apply red component error correction
  4025.   ColorR := Red + (ErrorR0[0] + 100) DIV 200;
  4026.   if (ColorR < 0) then
  4027.     ColorR := 0
  4028.   else if (ColorR > 255) then
  4029.     ColorR := 255;
  4030.  
  4031.   // Apply green component error correction
  4032.   ColorG := Green + (ErrorG0[0] + 100) DIV 200;
  4033.   if (ColorG < 0) then
  4034.     ColorG := 0
  4035.   else if (ColorG > 255) then
  4036.     ColorG := 255;
  4037.  
  4038.   // Apply blue component error correction
  4039.   ColorB := Blue + (ErrorB0[0] + 100) DIV 200;
  4040.   if (ColorB < 0) then
  4041.     ColorB := 0
  4042.   else if (ColorB > 255) then
  4043.     ColorB := 255;
  4044.  
  4045.   // Map color to palette
  4046.   Result := inherited Dither(ColorR, ColorG, ColorB, R, G, B);
  4047.  
  4048.   // Propagate red component error
  4049.   Propagate(ErrorR0, ErrorR1, ErrorR2, ErrorR3, ColorR - R);
  4050.   // Propagate green component error
  4051.   Propagate(ErrorG0, ErrorG1, ErrorG2, ErrorG3, ColorG - G);
  4052.   // Propagate blue component error
  4053.   Propagate(ErrorB0, ErrorB1, ErrorB2, ErrorB3, ColorB - B);
  4054.  
  4055.   // Move on to next column
  4056.   if (Direction = 1) then
  4057.   begin
  4058.     inc(longInt(ErrorR0), sizeof(TErrorTerm));
  4059.     inc(longInt(ErrorG0), sizeof(TErrorTerm));
  4060.     inc(longInt(ErrorB0), sizeof(TErrorTerm));
  4061.     inc(longInt(ErrorR1), sizeof(TErrorTerm));
  4062.     inc(longInt(ErrorG1), sizeof(TErrorTerm));
  4063.     inc(longInt(ErrorB1), sizeof(TErrorTerm));
  4064.     inc(longInt(ErrorR2), sizeof(TErrorTerm));
  4065.     inc(longInt(ErrorG2), sizeof(TErrorTerm));
  4066.     inc(longInt(ErrorB2), sizeof(TErrorTerm));
  4067.     inc(longInt(ErrorR3), sizeof(TErrorTerm));
  4068.     inc(longInt(ErrorG3), sizeof(TErrorTerm));
  4069.     inc(longInt(ErrorB3), sizeof(TErrorTerm));
  4070.   end else
  4071.   begin
  4072.     dec(longInt(ErrorR0), sizeof(TErrorTerm));
  4073.     dec(longInt(ErrorG0), sizeof(TErrorTerm));
  4074.     dec(longInt(ErrorB0), sizeof(TErrorTerm));
  4075.     dec(longInt(ErrorR1), sizeof(TErrorTerm));
  4076.     dec(longInt(ErrorG1), sizeof(TErrorTerm));
  4077.     dec(longInt(ErrorB1), sizeof(TErrorTerm));
  4078.     dec(longInt(ErrorR2), sizeof(TErrorTerm));
  4079.     dec(longInt(ErrorG2), sizeof(TErrorTerm));
  4080.     dec(longInt(ErrorB2), sizeof(TErrorTerm));
  4081.     dec(longInt(ErrorR3), sizeof(TErrorTerm));
  4082.     dec(longInt(ErrorG3), sizeof(TErrorTerm));
  4083.     dec(longInt(ErrorB3), sizeof(TErrorTerm));
  4084.   end;
  4085. end;
  4086. {$IFDEF R_PLUS}
  4087.   {$RANGECHECKS ON}
  4088.   {$UNDEF R_PLUS}
  4089. {$ENDIF}
  4090.  
  4091. {$IFOPT R+}
  4092.   {$DEFINE R_PLUS}
  4093.   {$RANGECHECKS OFF}
  4094. {$ENDIF}
  4095. procedure TSteveArcheDitherer.NextLine;
  4096. var
  4097.   TempErrors        : PErrors;
  4098. begin
  4099.   FillChar(ErrorsR0^, sizeof(TErrorTerm)*(Width+6), 0);
  4100.   FillChar(ErrorsG0^, sizeof(TErrorTerm)*(Width+6), 0);
  4101.   FillChar(ErrorsB0^, sizeof(TErrorTerm)*(Width+6), 0);
  4102.  
  4103.   // Swap lines
  4104.   TempErrors := ErrorsR0;
  4105.   ErrorsR0 := ErrorsR1;
  4106.   ErrorsR1 := ErrorsR2;
  4107.   ErrorsR2 := ErrorsR3;
  4108.   ErrorsR3 := TempErrors;
  4109.  
  4110.   TempErrors := ErrorsG0;
  4111.   ErrorsG0 := ErrorsG1;
  4112.   ErrorsG1 := ErrorsG2;
  4113.   ErrorsG2 := ErrorsG3;
  4114.   ErrorsG3 := TempErrors;
  4115.  
  4116.   TempErrors := ErrorsB0;
  4117.   ErrorsB0 := ErrorsB1;
  4118.   ErrorsB1 := ErrorsB2;
  4119.   ErrorsB2 := ErrorsB3;
  4120.   ErrorsB3 := TempErrors;
  4121.  
  4122.   inherited NextLine;
  4123.  
  4124.   FDirection2 := 2 * Direction;
  4125.   FDirection3 := 3 * Direction;
  4126.  
  4127.   if (Direction = 1) then
  4128.   begin
  4129.     // ErrorsR0[1] gives compiler error, so we
  4130.     // use PErrors(longInt(ErrorsR0)+sizeof(TErrorTerm)) instead...
  4131.     ErrorR0 := PErrors(longInt(ErrorsR0)+3*sizeof(TErrorTerm));
  4132.     ErrorG0 := PErrors(longInt(ErrorsG0)+3*sizeof(TErrorTerm));
  4133.     ErrorB0 := PErrors(longInt(ErrorsB0)+3*sizeof(TErrorTerm));
  4134.     ErrorR1 := PErrors(longInt(ErrorsR1)+3*sizeof(TErrorTerm));
  4135.     ErrorG1 := PErrors(longInt(ErrorsG1)+3*sizeof(TErrorTerm));
  4136.     ErrorB1 := PErrors(longInt(ErrorsB1)+3*sizeof(TErrorTerm));
  4137.     ErrorR2 := PErrors(longInt(ErrorsR2)+3*sizeof(TErrorTerm));
  4138.     ErrorG2 := PErrors(longInt(ErrorsG2)+3*sizeof(TErrorTerm));
  4139.     ErrorB2 := PErrors(longInt(ErrorsB2)+3*sizeof(TErrorTerm));
  4140.     ErrorR3 := PErrors(longInt(ErrorsR3)+3*sizeof(TErrorTerm));
  4141.     ErrorG3 := PErrors(longInt(ErrorsG3)+3*sizeof(TErrorTerm));
  4142.     ErrorB3 := PErrors(longInt(ErrorsB3)+3*sizeof(TErrorTerm));
  4143.   end else
  4144.   begin
  4145.     ErrorR0 := @ErrorsR0[Width+2];
  4146.     ErrorG0 := @ErrorsG0[Width+2];
  4147.     ErrorB0 := @ErrorsB0[Width+2];
  4148.     ErrorR1 := @ErrorsR1[Width+2];
  4149.     ErrorG1 := @ErrorsG1[Width+2];
  4150.     ErrorB1 := @ErrorsB1[Width+2];
  4151.     ErrorR2 := @ErrorsR2[Width+2];
  4152.     ErrorG2 := @ErrorsG2[Width+2];
  4153.     ErrorB2 := @ErrorsB2[Width+2];
  4154.     ErrorR3 := @ErrorsR2[Width+2];
  4155.     ErrorG3 := @ErrorsG2[Width+2];
  4156.     ErrorB3 := @ErrorsB2[Width+2];
  4157.   end;
  4158. end;
  4159. {$IFDEF R_PLUS}
  4160.   {$RANGECHECKS ON}
  4161.   {$UNDEF R_PLUS}
  4162. {$ENDIF}
  4163.  
  4164. ////////////////////////////////////////////////////////////////////////////////
  4165. //  TBurkesDitherer
  4166. constructor TBurkesDitherer.Create(AWidth: integer; Lookup: TColorLookup);
  4167. begin
  4168.   inherited Create(AWidth, Lookup);
  4169.  
  4170.   GetMem(ErrorsR0, sizeof(TErrorTerm)*(Width+4));
  4171.   GetMem(ErrorsG0, sizeof(TErrorTerm)*(Width+4));
  4172.   GetMem(ErrorsB0, sizeof(TErrorTerm)*(Width+4));
  4173.   GetMem(ErrorsR1, sizeof(TErrorTerm)*(Width+4));
  4174.   GetMem(ErrorsG1, sizeof(TErrorTerm)*(Width+4));
  4175.   GetMem(ErrorsB1, sizeof(TErrorTerm)*(Width+4));
  4176.   FillChar(ErrorsR0^, sizeof(TErrorTerm)*(Width+4), 0);
  4177.   FillChar(ErrorsG0^, sizeof(TErrorTerm)*(Width+4), 0);
  4178.   FillChar(ErrorsB0^, sizeof(TErrorTerm)*(Width+4), 0);
  4179.   FillChar(ErrorsR1^, sizeof(TErrorTerm)*(Width+4), 0);
  4180.   FillChar(ErrorsG1^, sizeof(TErrorTerm)*(Width+4), 0);
  4181.   FillChar(ErrorsB1^, sizeof(TErrorTerm)*(Width+4), 0);
  4182.  
  4183.   FDirection2 := 2 * Direction;
  4184.   ErrorR0 := PErrors(longInt(ErrorsR0)+2*sizeof(TErrorTerm));
  4185.   ErrorG0 := PErrors(longInt(ErrorsG0)+2*sizeof(TErrorTerm));
  4186.   ErrorB0 := PErrors(longInt(ErrorsB0)+2*sizeof(TErrorTerm));
  4187.   ErrorR1 := PErrors(longInt(ErrorsR1)+2*sizeof(TErrorTerm));
  4188.   ErrorG1 := PErrors(longInt(ErrorsG1)+2*sizeof(TErrorTerm));
  4189.   ErrorB1 := PErrors(longInt(ErrorsB1)+2*sizeof(TErrorTerm));
  4190. end;
  4191.  
  4192. destructor TBurkesDitherer.Destroy;
  4193. begin
  4194.   FreeMem(ErrorsR0);
  4195.   FreeMem(ErrorsG0);
  4196.   FreeMem(ErrorsB0);
  4197.   FreeMem(ErrorsR1);
  4198.   FreeMem(ErrorsG1);
  4199.   FreeMem(ErrorsB1);
  4200.   inherited Destroy;
  4201. end;
  4202.  
  4203. {$IFOPT R+}
  4204.   {$DEFINE R_PLUS}
  4205.   {$RANGECHECKS OFF}
  4206. {$ENDIF}
  4207. function TBurkesDitherer.Dither(Red, Green, Blue: BYTE; var R, G, B: BYTE): AnsiChar;
  4208. var
  4209.   ErrorR        ,
  4210.   ErrorG        ,
  4211.   ErrorB        : integer; // Error for current pixel
  4212.  
  4213.   // Propagate Burkes error terms:
  4214.   //    ... ... (here)  8/32    4/32
  4215.   //    2/32    4/32    8/32    4/32    2/32
  4216.   procedure Propagate(Errors0, Errors1: PErrors; Error: integer);
  4217.   begin
  4218.     if (Error = 0) then
  4219.       exit;
  4220.     inc(Error, Error);
  4221.     inc(Errors1[FDirection2], Error);   // Error * 2
  4222.     inc(Errors1[-FDirection2], Error);  // Error * 2
  4223.  
  4224.     inc(Error, Error);
  4225.     inc(Errors0[FDirection2], Error);   // Error * 4
  4226.     inc(Errors1[-Direction], Error);    // Error * 4
  4227.     inc(Errors1[Direction], Error); // Error * 4
  4228.  
  4229.     inc(Error, Error);
  4230.     inc(Errors0[Direction], Error); // Error * 8
  4231.     inc(Errors1[0], Error);     // Error * 8
  4232.   end;
  4233.  
  4234. begin
  4235.   // Apply red component error correction
  4236.   ErrorR := Red + (ErrorR0[0] + 16) DIV 32;
  4237.   if (ErrorR < 0) then
  4238.     ErrorR := 0
  4239.   else if (ErrorR > 255) then
  4240.     ErrorR := 255;
  4241.  
  4242.   // Apply green component error correction
  4243.   ErrorG := Green + (ErrorG0[0] + 16) DIV 32;
  4244.   if (ErrorG < 0) then
  4245.     ErrorG := 0
  4246.   else if (ErrorG > 255) then
  4247.     ErrorG := 255;
  4248.  
  4249.   // Apply blue component error correction
  4250.   ErrorB := Blue + (ErrorB0[0] + 16) DIV 32;
  4251.   if (ErrorB < 0) then
  4252.     ErrorB := 0
  4253.   else if (ErrorB > 255) then
  4254.     ErrorB := 255;
  4255.  
  4256.   // Map color to palette
  4257.   Result := inherited Dither(ErrorR, ErrorG, ErrorB, R, G, B);
  4258.  
  4259.   // Propagate red component error
  4260.   Propagate(ErrorR0, ErrorR1, ErrorR - R);
  4261.   // Propagate green component error
  4262.   Propagate(ErrorG0, ErrorG1, ErrorG - G);
  4263.   // Propagate blue component error
  4264.   Propagate(ErrorB0, ErrorB1, ErrorB - B);
  4265.  
  4266.   // Move on to next column
  4267.   if (Direction = 1) then
  4268.   begin
  4269.     inc(longInt(ErrorR0), sizeof(TErrorTerm));
  4270.     inc(longInt(ErrorG0), sizeof(TErrorTerm));
  4271.     inc(longInt(ErrorB0), sizeof(TErrorTerm));
  4272.     inc(longInt(ErrorR1), sizeof(TErrorTerm));
  4273.     inc(longInt(ErrorG1), sizeof(TErrorTerm));
  4274.     inc(longInt(ErrorB1), sizeof(TErrorTerm));
  4275.   end else
  4276.   begin
  4277.     dec(longInt(ErrorR0), sizeof(TErrorTerm));
  4278.     dec(longInt(ErrorG0), sizeof(TErrorTerm));
  4279.     dec(longInt(ErrorB0), sizeof(TErrorTerm));
  4280.     dec(longInt(ErrorR1), sizeof(TErrorTerm));
  4281.     dec(longInt(ErrorG1), sizeof(TErrorTerm));
  4282.     dec(longInt(ErrorB1), sizeof(TErrorTerm));
  4283.   end;
  4284. end;
  4285. {$IFDEF R_PLUS}
  4286.   {$RANGECHECKS ON}
  4287.   {$UNDEF R_PLUS}
  4288. {$ENDIF}
  4289.  
  4290. {$IFOPT R+}
  4291.   {$DEFINE R_PLUS}
  4292.   {$RANGECHECKS OFF}
  4293. {$ENDIF}
  4294. procedure TBurkesDitherer.NextLine;
  4295. var
  4296.   TempErrors        : PErrors;
  4297. begin
  4298.   FillChar(ErrorsR0^, sizeof(TErrorTerm)*(Width+4), 0);
  4299.   FillChar(ErrorsG0^, sizeof(TErrorTerm)*(Width+4), 0);
  4300.   FillChar(ErrorsB0^, sizeof(TErrorTerm)*(Width+4), 0);
  4301.  
  4302.   // Swap lines
  4303.   TempErrors := ErrorsR0;
  4304.   ErrorsR0 := ErrorsR1;
  4305.   ErrorsR1 := TempErrors;
  4306.  
  4307.   TempErrors := ErrorsG0;
  4308.   ErrorsG0 := ErrorsG1;
  4309.   ErrorsG1 := TempErrors;
  4310.  
  4311.   TempErrors := ErrorsB0;
  4312.   ErrorsB0 := ErrorsB1;
  4313.   ErrorsB1 := TempErrors;
  4314.  
  4315.   inherited NextLine;
  4316.  
  4317.   FDirection2 := 2 * Direction;
  4318.   if (Direction = 1) then
  4319.   begin
  4320.     // ErrorsR0[1] gives compiler error, so we
  4321.     // use PErrors(longInt(ErrorsR0)+sizeof(TErrorTerm)) instead...
  4322.     ErrorR0 := PErrors(longInt(ErrorsR0)+2*sizeof(TErrorTerm));
  4323.     ErrorG0 := PErrors(longInt(ErrorsG0)+2*sizeof(TErrorTerm));
  4324.     ErrorB0 := PErrors(longInt(ErrorsB0)+2*sizeof(TErrorTerm));
  4325.     ErrorR1 := PErrors(longInt(ErrorsR1)+2*sizeof(TErrorTerm));
  4326.     ErrorG1 := PErrors(longInt(ErrorsG1)+2*sizeof(TErrorTerm));
  4327.     ErrorB1 := PErrors(longInt(ErrorsB1)+2*sizeof(TErrorTerm));
  4328.   end else
  4329.   begin
  4330.     ErrorR0 := @ErrorsR0[Width+1];
  4331.     ErrorG0 := @ErrorsG0[Width+1];
  4332.     ErrorB0 := @ErrorsB0[Width+1];
  4333.     ErrorR1 := @ErrorsR1[Width+1];
  4334.     ErrorG1 := @ErrorsG1[Width+1];
  4335.     ErrorB1 := @ErrorsB1[Width+1];
  4336.   end;
  4337. end;
  4338. {$IFDEF R_PLUS}
  4339.   {$RANGECHECKS ON}
  4340.   {$UNDEF R_PLUS}
  4341. {$ENDIF}
  4342.  
  4343. ////////////////////////////////////////////////////////////////////////////////
  4344. //
  4345. //          Octree Color Quantization Engine
  4346. //
  4347. ////////////////////////////////////////////////////////////////////////////////
  4348. //  Adapted from Earl F. Glynn's ColorQuantizationLibrary, March 1998
  4349. ////////////////////////////////////////////////////////////////////////////////
  4350. type
  4351.   TOctreeNode = class;  // Forward definition so TReducibleNodes can be declared
  4352.  
  4353.   TReducibleNodes = array[0..7] of TOctreeNode;
  4354.  
  4355.   TOctreeNode = Class(TObject)
  4356.   public
  4357.     IsLeaf      : Boolean;
  4358.     PixelCount      : integer;
  4359.     RedSum      : integer;
  4360.     GreenSum        : integer;
  4361.     BlueSum     : integer;
  4362.     Next        : TOctreeNode;
  4363.     Child       : TReducibleNodes;
  4364.  
  4365.     constructor Create(Level: integer; ColorBits: integer; var LeafCount: integer;
  4366.       var ReducibleNodes: TReducibleNodes);
  4367.     destructor Destroy; override;
  4368.   end;
  4369.  
  4370.   TColorQuantizer = class(TObject)
  4371.   private
  4372.     FTree       : TOctreeNode;
  4373.     FLeafCount      : integer;
  4374.     FReducibleNodes : TReducibleNodes;
  4375.     FMaxColors      : integer;
  4376.     FColorBits      : integer;
  4377.  
  4378.   protected
  4379.     procedure AddColor(var Node: TOctreeNode; r, g, b: byte; ColorBits: integer;
  4380.       Level: integer; var LeafCount: integer; var ReducibleNodes: TReducibleNodes);
  4381.     procedure DeleteTree(var Node: TOctreeNode);
  4382.     procedure GetPaletteColors(const Node: TOctreeNode;
  4383.       var RGBQuadArray: TRGBQuadArray; var Index: integer);
  4384.     procedure ReduceTree(ColorBits: integer; var LeafCount: integer;
  4385.       var ReducibleNodes: TReducibleNodes);
  4386.  
  4387.   public
  4388.     constructor Create(MaxColors: integer; ColorBits: integer);
  4389.     destructor Destroy; override;
  4390.  
  4391.     procedure GetColorTable(var RGBQuadArray: TRGBQuadArray);
  4392.     function ProcessImage(const DIB: TDIBReader): boolean;
  4393.  
  4394.     property ColorCount: integer read FLeafCount;
  4395.   end;
  4396.  
  4397. constructor TOctreeNode.Create(Level: integer; ColorBits: integer;
  4398.   var LeafCount: integer; var ReducibleNodes: TReducibleNodes);
  4399. var
  4400.   i         : integer;
  4401. begin
  4402.   PixelCount := 0;
  4403.   RedSum := 0;
  4404.   GreenSum := 0;
  4405.   BlueSum := 0;
  4406.   for i := Low(Child) to High(Child) do
  4407.     Child[i] := nil;
  4408.  
  4409.   IsLeaf := (Level = ColorBits);
  4410.   if (IsLeaf) then
  4411.   begin
  4412.     Next := nil;
  4413.     inc(LeafCount);
  4414.   end else
  4415.   begin
  4416.     Next := ReducibleNodes[Level];
  4417.     ReducibleNodes[Level] := self;
  4418.   end;
  4419. end;
  4420.  
  4421. destructor TOctreeNode.Destroy;
  4422. var
  4423.   i         : integer;
  4424. begin
  4425.   for i := High(Child) downto Low(Child) do
  4426.     Child[i].Free;
  4427. end;
  4428.  
  4429. constructor TColorQuantizer.Create(MaxColors: integer; ColorBits: integer);
  4430. var
  4431.   i         : integer;
  4432. begin
  4433.   ASSERT(ColorBits <= 8, 'ColorBits must be 8 or less');
  4434.  
  4435.   FTree := nil;
  4436.   FLeafCount := 0;
  4437.  
  4438.   // Initialize all nodes even though only ColorBits+1 of them are needed
  4439.   for i := Low(FReducibleNodes) to High(FReducibleNodes) do
  4440.     FReducibleNodes[i] := nil;
  4441.  
  4442.   FMaxColors := MaxColors;
  4443.   FColorBits := ColorBits;
  4444. end;
  4445.  
  4446. destructor TColorQuantizer.Destroy;
  4447. begin
  4448.   if (FTree <> nil) then
  4449.     DeleteTree(FTree);
  4450. end;
  4451.  
  4452. procedure TColorQuantizer.GetColorTable(var RGBQuadArray: TRGBQuadArray);
  4453. var
  4454.   Index         : integer;
  4455. begin
  4456.   Index := 0;
  4457.   GetPaletteColors(FTree, RGBQuadArray, Index);
  4458. end;
  4459.  
  4460. // Handles passed to ProcessImage should refer to DIB sections, not DDBs.
  4461. // In certain cases, specifically when it's called upon to process 1, 4, or
  4462. // 8-bit per pixel images on systems with palettized display adapters,
  4463. // ProcessImage can produce incorrect results if it's passed a handle to a
  4464. // DDB.
  4465. function TColorQuantizer.ProcessImage(const DIB: TDIBReader): boolean;
  4466. var
  4467.   i         ,
  4468.   j         : integer;
  4469.   ScanLine      : pointer;
  4470.   Pixel         : PRGBTriple;
  4471. begin
  4472.   Result := True;
  4473.  
  4474.   for j := 0 to DIB.Bitmap.Height-1 do
  4475.   begin
  4476.     Scanline := DIB.Scanline[j];
  4477.     Pixel := ScanLine;
  4478.     for i := 0 to DIB.Bitmap.Width-1 do
  4479.     begin
  4480.       with Pixel^ do
  4481.         AddColor(FTree, rgbtRed, rgbtGreen, rgbtBlue,
  4482.                  FColorBits, 0, FLeafCount, FReducibleNodes);
  4483.  
  4484.       while FLeafCount > FMaxColors do
  4485.         ReduceTree(FColorbits, FLeafCount, FReducibleNodes);
  4486.       inc(Pixel);
  4487.     end;
  4488.   end;
  4489. end;
  4490.  
  4491. procedure TColorQuantizer.AddColor(var Node: TOctreeNode; r,g,b: byte;
  4492.   ColorBits: integer; Level: integer; var LeafCount: integer;
  4493.   var ReducibleNodes: TReducibleNodes);
  4494. const
  4495.   Mask:  array[0..7] of BYTE = ($80, $40, $20, $10, $08, $04, $02, $01);
  4496. var
  4497.   Index         : integer;
  4498.   Shift         : integer;
  4499. begin
  4500.   // If the node doesn't exist, create it.
  4501.   if (Node = nil) then
  4502.     Node := TOctreeNode.Create(Level, ColorBits, LeafCount, ReducibleNodes);
  4503.  
  4504.   if (Node.IsLeaf) then
  4505.   begin
  4506.     inc(Node.PixelCount);
  4507.     inc(Node.RedSum, r);
  4508.     inc(Node.GreenSum, g);
  4509.     inc(Node.BlueSum, b);
  4510.   end else
  4511.   begin
  4512.     // Recurse a level deeper if the node is not a leaf.
  4513.     Shift := 7 - Level;
  4514.  
  4515.     Index := (((r and mask[Level]) SHR Shift) SHL 2)  or
  4516.              (((g and mask[Level]) SHR Shift) SHL 1)  or
  4517.               ((b and mask[Level]) SHR Shift);
  4518.     AddColor(Node.Child[Index], r, g, b, ColorBits, Level+1, LeafCount, ReducibleNodes);
  4519.   end;
  4520. end;
  4521.  
  4522. procedure TColorQuantizer.DeleteTree(var Node: TOctreeNode);
  4523. var
  4524.   i         : integer;
  4525. begin
  4526.   for i := High(TReducibleNodes) downto Low(TReducibleNodes) do
  4527.     if (Node.Child[i] <> nil) then
  4528.       DeleteTree(Node.Child[i]);
  4529.  
  4530.   Node.Free;
  4531.   Node := nil;
  4532. end;
  4533.  
  4534. procedure TColorQuantizer.GetPaletteColors(const Node: TOctreeNode;
  4535.   var RGBQuadArray: TRGBQuadArray; var Index: integer);
  4536. var
  4537.   i         : integer;
  4538. begin
  4539.   if (Node.IsLeaf) then
  4540.   begin
  4541.     with RGBQuadArray[Index] do
  4542.     begin
  4543.       if (Node.PixelCount <> 0) then
  4544.       begin
  4545.         rgbRed   := BYTE(Node.RedSum   DIV Node.PixelCount);
  4546.         rgbGreen := BYTE(Node.GreenSum DIV Node.PixelCount);
  4547.         rgbBlue  := BYTE(Node.BlueSum  DIV Node.PixelCount);
  4548.       end else
  4549.       begin
  4550.         rgbRed := 0;
  4551.         rgbGreen := 0;
  4552.         rgbBlue := 0;
  4553.       end;
  4554.       rgbReserved := 0;
  4555.     end;
  4556.     inc(Index);
  4557.   end else
  4558.   begin
  4559.     for i := Low(Node.Child) to High(Node.Child) do
  4560.       if (Node.Child[i] <> nil) then
  4561.         GetPaletteColors(Node.Child[i], RGBQuadArray, Index);
  4562.   end;
  4563. end;
  4564.  
  4565. procedure TColorQuantizer.ReduceTree(ColorBits: integer; var LeafCount: integer;
  4566.   var ReducibleNodes: TReducibleNodes);
  4567. var
  4568.   RedSum        ,
  4569.   GreenSum      ,
  4570.   BlueSum       : integer;
  4571.   Children      : integer;
  4572.   i         : integer;
  4573.   Node          : TOctreeNode;
  4574. begin
  4575.   // Find the deepest level containing at least one reducible node
  4576.   i := Colorbits - 1;
  4577.   while (i > 0) and (ReducibleNodes[i] = nil) do
  4578.     dec(i);
  4579.  
  4580.   // Reduce the node most recently added to the list at level i.
  4581.   Node := ReducibleNodes[i];
  4582.   ReducibleNodes[i] := Node.Next;
  4583.  
  4584.   RedSum   := 0;
  4585.   GreenSum := 0;
  4586.   BlueSum  := 0;
  4587.   Children := 0;
  4588.  
  4589.   for i := Low(ReducibleNodes) to High(ReducibleNodes) do
  4590.     if (Node.Child[i] <> nil) then
  4591.     begin
  4592.       inc(RedSum, Node.Child[i].RedSum);
  4593.       inc(GreenSum, Node.Child[i].GreenSum);
  4594.       inc(BlueSum, Node.Child[i].BlueSum);
  4595.       inc(Node.PixelCount, Node.Child[i].PixelCount);
  4596.       Node.Child[i].Free;
  4597.       Node.Child[i] := nil;
  4598.       inc(Children);
  4599.     end;
  4600.  
  4601.   Node.IsLeaf := TRUE;
  4602.   Node.RedSum := RedSum;
  4603.   Node.GreenSum := GreenSum;
  4604.   Node.BlueSum := BlueSum;
  4605.   dec(LeafCount, Children-1);
  4606. end;
  4607.  
  4608. ////////////////////////////////////////////////////////////////////////////////
  4609. //
  4610. //          Octree Color Quantization Wrapper
  4611. //
  4612. ////////////////////////////////////////////////////////////////////////////////
  4613. //  Adapted from Earl F. Glynn's PaletteLibrary, March 1998
  4614. ////////////////////////////////////////////////////////////////////////////////
  4615.  
  4616. // Wrapper for internal use - uses TDIBReader for bitmap access
  4617. function doCreateOptimizedPaletteFromSingleBitmap(const DIB: TDIBReader;
  4618.   Colors, ColorBits: integer; Windows: boolean): hPalette;
  4619. var
  4620.   SystemPalette     : HPalette;
  4621.   ColorQuantizer    : TColorQuantizer;
  4622.   i         : integer;
  4623.   LogicalPalette    : TMaxLogPalette;
  4624.   RGBQuadArray      : TRGBQuadArray;
  4625.   Offset        : integer;
  4626. begin
  4627.   LogicalPalette.palVersion := $0300;
  4628.   LogicalPalette.palNumEntries := Colors;
  4629. // 2003.03.06 ->
  4630.   {reset palette to black}
  4631.   FillChar(LogicalPalette.palPalEntry, SizeOf(LogicalPalette.palPalEntry), 0);
  4632.   for i := 0 to 255 do
  4633.     LogicalPalette.palPalEntry[i].peFlags := PC_NOCOLLAPSE;
  4634. // 2003.03.06 <-
  4635.  
  4636.   if (Windows) then
  4637.   begin
  4638.     // Get the windows 20 color system palette
  4639.     SystemPalette := GetStockObject(DEFAULT_PALETTE);
  4640.     GetPaletteEntries(SystemPalette, 0, 10, LogicalPalette.palPalEntry[0]);
  4641.     //GetPaletteEntries(SystemPalette, 10, 10, LogicalPalette.palPalEntry[245]);  // wrong offset
  4642.     GetPaletteEntries(SystemPalette, 10, 10, LogicalPalette.palPalEntry[246]);  // 2003.03.06
  4643.     Colors := 236;
  4644.     Offset := 10;
  4645.     LogicalPalette.palNumEntries := 256;
  4646. { Test code
  4647. // 2003.03.06 ->
  4648.     // Get the windows 20 color system palette
  4649.     SystemPalette := GetStockObject(DEFAULT_PALETTE);
  4650.     GetPaletteEntries(SystemPalette, 0, 10, LogicalPalette.palPalEntry[0]);
  4651.     GetPaletteEntries(SystemPalette, 10, 10, LogicalPalette.palPalEntry[10]);
  4652.     Colors := 236;
  4653.     Offset := 20;
  4654.     LogicalPalette.palNumEntries := 256;
  4655. // 2003.03.06 <-
  4656. }
  4657.   end else
  4658.     Offset := 0;
  4659.  
  4660.   // Normally for 24-bit images, use ColorBits of 5 or 6.  For 8-bit images
  4661.   // use ColorBits = 8.
  4662.   ColorQuantizer := TColorQuantizer.Create(Colors, ColorBits);
  4663.   try
  4664.     ColorQuantizer.ProcessImage(DIB);
  4665.     ColorQuantizer.GetColorTable(RGBQuadArray);
  4666.   finally
  4667.     ColorQuantizer.Free;
  4668.   end;
  4669.  
  4670.   for i := 0 to Colors-1 do
  4671.     with LogicalPalette.palPalEntry[i+Offset] do
  4672.     begin
  4673.       peRed   := RGBQuadArray[i].rgbRed;
  4674.       peGreen := RGBQuadArray[i].rgbGreen;
  4675.       peBlue  := RGBQuadArray[i].rgbBlue;
  4676.       peFlags := RGBQuadArray[i].rgbReserved;
  4677.     end;
  4678.   Result := CreatePalette(pLogPalette(@LogicalPalette)^);
  4679. end;
  4680.  
  4681. function CreateOptimizedPaletteFromSingleBitmap(const Bitmap: TBitmap;
  4682.   Colors, ColorBits: integer; Windows: boolean): hPalette;
  4683. var
  4684.   DIB           : TDIBReader;
  4685. begin
  4686.   DIB := TDIBReader.Create(Bitmap, pf24bit);
  4687.   try
  4688.     Result := doCreateOptimizedPaletteFromSingleBitmap(DIB, Colors, ColorBits, Windows);
  4689.   finally
  4690.     DIB.Free;
  4691.   end;
  4692. end;
  4693.  
  4694. function CreateOptimizedPaletteFromManyBitmaps(Bitmaps: TList; Colors, ColorBits: integer;
  4695.   Windows: boolean): hPalette;
  4696. var
  4697.   SystemPalette     : HPalette;
  4698.   ColorQuantizer    : TColorQuantizer;
  4699.   i         : integer;
  4700.   LogicalPalette    : TMaxLogPalette;
  4701.   RGBQuadArray      : TRGBQuadArray;
  4702.   Offset        : integer;
  4703.   DIB           : TDIBReader;
  4704. begin
  4705.   if (Bitmaps = nil) or (Bitmaps.Count = 0) then
  4706.     Error(sInvalidBitmapList);
  4707.  
  4708.   LogicalPalette.palVersion := $0300;
  4709.   LogicalPalette.palNumEntries := Colors;
  4710. // 2003.03.06 ->
  4711.   {reset palette to black}
  4712.   FillChar(LogicalPalette.palPalEntry, SizeOf(LogicalPalette.palPalEntry), 0);
  4713.   for i := 0 to 255 do
  4714.     LogicalPalette.palPalEntry[i].peFlags := PC_NOCOLLAPSE;
  4715. // 2003.03.06 <-
  4716.  
  4717.   if (Windows) then
  4718.   begin
  4719.     // Get the windows 20 color system palette
  4720.     SystemPalette := GetStockObject(DEFAULT_PALETTE);
  4721.     GetPaletteEntries(SystemPalette, 0, 10, LogicalPalette.palPalEntry[0]);
  4722.     //GetPaletteEntries(SystemPalette, 10, 10, LogicalPalette.palPalEntry[245]);  // wrong offset
  4723.     GetPaletteEntries(SystemPalette, 10, 10, LogicalPalette.palPalEntry[246]);  // 2003.03.06
  4724.     Colors := 236;
  4725.     Offset := 10;
  4726.     LogicalPalette.palNumEntries := 256;
  4727. { Test code
  4728. // 2003.03.06 ->
  4729.     // Get the windows 20 color system palette
  4730.     SystemPalette := GetStockObject(DEFAULT_PALETTE);
  4731.     GetPaletteEntries(SystemPalette, 0, 10, LogicalPalette.palPalEntry[0]);
  4732.     GetPaletteEntries(SystemPalette, 10, 10, LogicalPalette.palPalEntry[10]);
  4733.     Colors := 236;
  4734.     Offset := 20;
  4735.     LogicalPalette.palNumEntries := 256;
  4736. // 2003.03.06 <-
  4737. }
  4738.   end else
  4739.     Offset := 0;
  4740.  
  4741.   // Normally for 24-bit images, use ColorBits of 5 or 6.  For 8-bit images
  4742.   // use ColorBits = 8.
  4743.   ColorQuantizer := TColorQuantizer.Create(Colors, ColorBits);
  4744.   try
  4745.     for i := 0 to Bitmaps.Count-1 do
  4746.     begin
  4747.       DIB := TDIBReader.Create(TBitmap(Bitmaps[i]), pf24bit);
  4748.       try
  4749.         ColorQuantizer.ProcessImage(DIB);
  4750.       finally
  4751.         DIB.Free;
  4752.       end;
  4753.     end;
  4754.     ColorQuantizer.GetColorTable(RGBQuadArray);
  4755.   finally
  4756.     ColorQuantizer.Free;
  4757.   end;
  4758.  
  4759.   for i := 0 to Colors-1 do
  4760.     with LogicalPalette.palPalEntry[i+Offset] do
  4761.     begin
  4762.       peRed   := RGBQuadArray[i].rgbRed;
  4763.       peGreen := RGBQuadArray[i].rgbGreen;
  4764.       peBlue  := RGBQuadArray[i].rgbBlue;
  4765.       peFlags := RGBQuadArray[i].rgbReserved;
  4766.     end;
  4767.   Result := CreatePalette(pLogPalette(@LogicalPalette)^);
  4768. end;
  4769.  
  4770. ////////////////////////////////////////////////////////////////////////////////
  4771. //
  4772. //          Color reduction
  4773. //
  4774. ////////////////////////////////////////////////////////////////////////////////
  4775. {$IFOPT R+}
  4776.   {$DEFINE R_PLUS}
  4777.   {$RANGECHECKS OFF}
  4778. {$ENDIF}
  4779. //: Reduces the color depth of a bitmap using color quantization and dithering.
  4780. function ReduceColors(Bitmap: TBitmap; ColorReduction: TColorReduction;
  4781.   DitherMode: TDitherMode; ReductionBits: integer; CustomPalette: hPalette): TBitmap;
  4782. var
  4783.   Palette       : hPalette;
  4784.   ColorLookup       : TColorLookup;
  4785.   Ditherer      : TDitherEngine;
  4786.   Row           : Integer;
  4787.   DIBResult     : TDIBWriter;
  4788.   DIBSource     : TDIBReader;
  4789.   SrcScanLine       ,
  4790.   Src           : PRGBTriple;
  4791.   DstScanLine       ,
  4792.   Dst           : PAnsiChar;
  4793.   BGR           : TRGBTriple;
  4794. {$ifdef DEBUG_DITHERPERFORMANCE}
  4795.   TimeStart     ,
  4796.   TimeStop      : DWORD;
  4797. {$endif}
  4798.  
  4799.   function GrayScalePalette: hPalette;
  4800.   var
  4801.     i           : integer;
  4802.     Pal         : TMaxLogPalette;
  4803.   begin
  4804.     Pal.palVersion := $0300;
  4805.     Pal.palNumEntries := 256;
  4806.     for i := 0 to 255 do
  4807.     begin
  4808.       // 2009.10.10 ->
  4809.       //with (Pal.palPalEntry[i]) do
  4810.       with Pal.palPalEntry[i] do
  4811.       // 2009.10.10 <-
  4812.       begin
  4813.         peRed := i;
  4814.         peGreen := i;
  4815.         peBlue  := i;
  4816.         peFlags := PC_NOCOLLAPSE;
  4817.       end;
  4818.     end;
  4819.     Result := CreatePalette(pLogPalette(@Pal)^);
  4820.   end;
  4821.  
  4822.   function MonochromePalette: hPalette;
  4823.   var
  4824.     i           : integer;
  4825.     Pal         : TMaxLogPalette;
  4826.   const
  4827.     Values      : array[0..1] of byte
  4828.                 = (0, 255);
  4829.   begin
  4830.     Pal.palVersion := $0300;
  4831.     Pal.palNumEntries := 2;
  4832.     for i := 0 to 1 do
  4833.     begin
  4834.       // 2009.10.10 ->
  4835.       //with (Pal.palPalEntry[i]) do
  4836.       with Pal.palPalEntry[i] do
  4837.       // 2009.10.10 <-
  4838.       begin
  4839.         peRed := Values[i];
  4840.         peGreen := Values[i];
  4841.         peBlue  := Values[i];
  4842.         peFlags := PC_NOCOLLAPSE;
  4843.       end;
  4844.     end;
  4845.     Result := CreatePalette(pLogPalette(@Pal)^);
  4846.   end;
  4847.  
  4848.   function WindowsGrayScalePalette: hPalette;
  4849.   var
  4850.     i           : integer;
  4851.     Pal         : TMaxLogPalette;
  4852.   const
  4853.     Values      : array[0..3] of byte
  4854.                 = (0, 128, 192, 255);
  4855.   begin
  4856.     Pal.palVersion := $0300;
  4857.     Pal.palNumEntries := 4;
  4858.     for i := 0 to 3 do
  4859.     begin
  4860.       // 2009.10.10 ->
  4861.       //with (Pal.palPalEntry[i]) do
  4862.       with Pal.palPalEntry[i] do
  4863.       // 2009.10.10 <-
  4864.       begin
  4865.         peRed := Values[i];
  4866.         peGreen := Values[i];
  4867.         peBlue  := Values[i];
  4868.         peFlags := PC_NOCOLLAPSE;
  4869.       end;
  4870.     end;
  4871.     Result := CreatePalette(pLogPalette(@Pal)^);
  4872.   end;
  4873.  
  4874.   function WindowsHalftonePalette: hPalette;
  4875.   var
  4876.     DC          : HDC;
  4877.   begin
  4878.     DC := GDICheck(GetDC(0));
  4879.     try
  4880.       Result := CreateHalfTonePalette(DC);
  4881.     finally
  4882.       ReleaseDC(0, DC);
  4883.     end;
  4884.   end;
  4885.  
  4886. begin
  4887. {$ifdef DEBUG_DITHERPERFORMANCE}
  4888.   timeBeginPeriod(5);
  4889.   TimeStart := timeGetTime;
  4890. {$endif}
  4891.  
  4892.   Result := TBitmap.Create;
  4893.   try
  4894.  
  4895.     if (ColorReduction = rmNone) then
  4896.     begin
  4897.       Result.Assign(Bitmap);
  4898. {$ifndef VER9x}
  4899.       SetPixelFormat(Result, pf24bit);
  4900. {$endif}
  4901.       exit;
  4902.     end;
  4903.  
  4904. {$IFNDEF VER9x}
  4905.     if (Bitmap.Width*Bitmap.Height > BitmapAllocationThreshold) then
  4906.       SetPixelFormat(Result, pf1bit); // To reduce resource consumption of resize
  4907. {$ENDIF}
  4908.  
  4909.     ColorLookup := nil;
  4910.     Ditherer := nil;
  4911.     DIBResult := nil;
  4912.     DIBSource := nil;
  4913.     Palette := 0;
  4914.     try // Protect above resources
  4915.  
  4916.       // Dithering and color mapper only supports 24 bit bitmaps,
  4917.       // so we have convert the source bitmap to the appropiate format.
  4918.       DIBSource := TDIBReader.Create(Bitmap, pf24bit);
  4919.  
  4920.       // Create a palette based on current options
  4921.       case (ColorReduction) of
  4922.         rmQuantize:
  4923.           Palette := doCreateOptimizedPaletteFromSingleBitmap(DIBSource, 1 SHL ReductionBits, 8, False);
  4924.         rmQuantizeWindows:
  4925.           Palette := CreateOptimizedPaletteFromSingleBitmap(Bitmap, 256, 8, True);
  4926.         rmNetscape:
  4927.           Palette := WebPalette;
  4928.         rmGrayScale:
  4929.           Palette := GrayScalePalette;
  4930.         rmMonochrome:
  4931.           Palette := MonochromePalette;
  4932.         rmWindowsGray:
  4933.           Palette := WindowsGrayScalePalette;
  4934.         rmWindows20:
  4935.           Palette := GetStockObject(DEFAULT_PALETTE);
  4936.         rmWindows256:
  4937.           Palette := WindowsHalftonePalette;
  4938.         rmPalette:
  4939.           Palette := CopyPalette(CustomPalette);
  4940.       else
  4941.         exit;
  4942.       end;
  4943.  
  4944.       { TODO -oanme -cImprovement : Gray scale conversion should be done prior to dithering/mapping. Otherwise corrected values will be converted multiple times. }
  4945.  
  4946.       // Create a color mapper based on current options
  4947.       case (ColorReduction) of
  4948.         // For some strange reason my fast and dirty color lookup
  4949.         // is more precise that Windows GetNearestPaletteIndex...
  4950.         // rmWindows20:
  4951.         //  ColorLookup := TSlowColorLookup.Create(Palette);
  4952.         // rmWindowsGray:
  4953.         //  ColorLookup := TGrayWindowsLookup.Create(Palette);
  4954.         rmQuantize:
  4955. // 2007.01.18 ->  // switch back to TFastColorLookup
  4956.           ColorLookup := TFastColorLookup.Create(Palette);
  4957. //          ColorLookup := TSlowColorLookup.Create(Palette);  // 2003-03-06
  4958. // 2007.01.18 <-
  4959.         rmNetscape:
  4960.           ColorLookup := TNetscapeColorLookup.Create(Palette);
  4961.         rmGrayScale:
  4962.           ColorLookup := TGrayScaleLookup.Create(Palette);
  4963.         rmMonochrome:
  4964.           ColorLookup := TMonochromeLookup.Create(Palette);
  4965.       else
  4966. //        ColorLookup := TFastColorLookup.Create(Palette);
  4967.         ColorLookup := TSlowColorLookup.Create(Palette);  // 2003-03-06
  4968.       end;
  4969.  
  4970.       // Nothing to do if palette doesn't contain any colors
  4971.       if (ColorLookup.Colors = 0) then
  4972.         exit;
  4973.  
  4974.       // Create a ditherer based on current options
  4975.       case (DitherMode) of
  4976.         dmNearest:
  4977.           Ditherer := TDitherEngine.Create(Bitmap.Width, ColorLookup);
  4978.         dmFloydSteinberg:
  4979.           Ditherer := TFloydSteinbergDitherer.Create(Bitmap.Width, ColorLookup);
  4980.         dmStucki:
  4981.           Ditherer := TStuckiDitherer.Create(Bitmap.Width, ColorLookup);
  4982.         dmSierra:
  4983.           Ditherer := TSierraDitherer.Create(Bitmap.Width, ColorLookup);
  4984.         dmJaJuNI:
  4985.           Ditherer := TJaJuNIDitherer.Create(Bitmap.Width, ColorLookup);
  4986.         dmSteveArche:
  4987.           Ditherer := TSteveArcheDitherer.Create(Bitmap.Width, ColorLookup);
  4988.         dmBurkes:
  4989.           Ditherer := TBurkesDitherer.Create(Bitmap.Width, ColorLookup);
  4990.       else
  4991.         exit;
  4992.       end;
  4993.  
  4994.       // The processed bitmap is returned in pf8bit format
  4995.       DIBResult := TDIBWriter.Create(Result, pf8bit, Bitmap.Width, Bitmap.Height,
  4996.         Palette);
  4997.  
  4998.       // Process the image
  4999.       Row := 0;
  5000.       while (Row < Bitmap.Height) do
  5001.       begin
  5002.         SrcScanline := DIBSource.ScanLine[Row];
  5003.         DstScanline := DIBResult.ScanLine[Row];
  5004.         Src := pointer(longInt(SrcScanLine) + Ditherer.Column*sizeof(TRGBTriple));
  5005.         Dst := pointer(longInt(DstScanLine) + Ditherer.Column);
  5006.  
  5007.         while (Ditherer.Column < Ditherer.Width) and (Ditherer.Column >= 0) do
  5008.         begin
  5009.           BGR := Src^;
  5010.           // Dither and map a single pixel
  5011.           Dst^ := Ditherer.Dither(BGR.rgbtRed, BGR.rgbtGreen, BGR.rgbtBlue,
  5012.             BGR.rgbtRed, BGR.rgbtGreen, BGR.rgbtBlue);
  5013.  
  5014.           inc(Src, Ditherer.Direction);
  5015.           inc(Dst, Ditherer.Direction);
  5016.         end;
  5017.  
  5018.         Inc(Row);
  5019.         Ditherer.NextLine;
  5020.       end;
  5021.     finally
  5022.       if (ColorLookup <> nil) then
  5023.         ColorLookup.Free;
  5024.       if (Ditherer <> nil) then
  5025.         Ditherer.Free;
  5026.       if (DIBResult <> nil) then
  5027.         DIBResult.Free;
  5028.       if (DIBSource <> nil) then
  5029.         DIBSource.Free;
  5030.       // Must delete palette after TDIBWriter since TDIBWriter uses palette
  5031.       if (Palette <> 0) then
  5032.         DeleteObject(Palette);
  5033.     end;
  5034.   except
  5035.     Result.Free;
  5036.     raise;
  5037.   end;
  5038.  
  5039. {$ifdef DEBUG_DITHERPERFORMANCE}
  5040.   TimeStop := timeGetTime;
  5041.   ShowMessage(format('Dithered %d pixels in %d mS, Rate %d pixels/mS (%d pixels/S)',
  5042.     [Bitmap.Height*Bitmap.Width, TimeStop-TimeStart,
  5043.     MulDiv(Bitmap.Height, Bitmap.Width, TimeStop-TimeStart+1),
  5044.     MulDiv(Bitmap.Height, Bitmap.Width * 1000, TimeStop-TimeStart+1)]));
  5045.   timeEndPeriod(5);
  5046. {$endif}
  5047. end;
  5048. {$IFDEF R_PLUS}
  5049.   {$RANGECHECKS ON}
  5050.   {$UNDEF R_PLUS}
  5051. {$ENDIF}
  5052.  
  5053. ////////////////////////////////////////////////////////////////////////////////
  5054. //
  5055. //          TGIFColorMap
  5056. //
  5057. ////////////////////////////////////////////////////////////////////////////////
  5058. const
  5059.   InitColorMapSize = 16;
  5060.   DeltaColorMapSize = 32;
  5061.  
  5062. //: Creates an instance of a TGIFColorMap object.
  5063. constructor TGIFColorMap.Create;
  5064. begin
  5065.   inherited Create;
  5066.   FColorMap := nil;
  5067.   FCapacity := 0;
  5068.   FCount := 0;
  5069.   FOptimized := False;
  5070. end;
  5071.  
  5072. //: Destroys an instance of a TGIFColorMap object.
  5073. destructor TGIFColorMap.Destroy;
  5074. begin
  5075.   Clear;
  5076.   Changed;
  5077.   inherited Destroy;
  5078. end;
  5079.  
  5080. //: Empties the color map.
  5081. procedure TGIFColorMap.Clear;
  5082. begin
  5083.   if (FColorMap <> nil) then
  5084.     FreeMem(FColorMap);
  5085.   FColorMap := nil;
  5086.   FCapacity := 0;
  5087.   FCount := 0;
  5088.   FOptimized := False;
  5089. end;
  5090.  
  5091. //: Converts a Windows color value to a RGB value.
  5092. class function TGIFColorMap.Color2RGB(Color: TColor): TGIFColor;
  5093. begin
  5094.   Result.Blue := (Color shr 16) and $FF;
  5095.   Result.Green := (Color shr 8) and $FF;
  5096.   Result.Red  := Color and $FF;
  5097. end;
  5098.  
  5099. //: Converts a RGB value to a Windows color value.
  5100. class function TGIFColorMap.RGB2Color(Color: TGIFColor): TColor;
  5101. begin
  5102.   Result := (Color.Blue SHL 16) OR (Color.Green SHL 8) OR Color.Red;
  5103. end;
  5104.  
  5105. //: Saves the color map to a stream.
  5106. procedure TGIFColorMap.SaveToStream(Stream: TStream);
  5107. var
  5108.   Dummies       : integer;
  5109.   Dummy         : TGIFColor;
  5110. begin
  5111.   if (FCount = 0) then
  5112.     exit;
  5113.   Stream.WriteBuffer(FColorMap^, FCount*sizeof(TGIFColor));
  5114.   Dummies := (1 SHL BitsPerPixel)-FCount;
  5115.   Dummy.Red := 0;
  5116.   Dummy.Green := 0;
  5117.   Dummy.Blue := 0;
  5118.   while (Dummies > 0) do
  5119.   begin
  5120.     Stream.WriteBuffer(Dummy, sizeof(TGIFColor));
  5121.     dec(Dummies);
  5122.   end;
  5123. end;
  5124.  
  5125. //: Loads the color map from a stream.
  5126. procedure TGIFColorMap.LoadFromStream(Stream: TStream; Count: integer);
  5127. begin
  5128.   Clear;
  5129.   SetCapacity(Count);
  5130.   ReadCheck(Stream, FColorMap^, Count*sizeof(TGIFColor));
  5131.   FCount := Count;
  5132. end;
  5133.  
  5134. //: Returns the position of a color in the color map.
  5135. function TGIFColorMap.IndexOf(Color: TColor): integer;
  5136. var
  5137.   RGB           : TGIFColor;
  5138. begin
  5139.   RGB := Color2RGB(Color);
  5140.   if (FOptimized) then
  5141.   begin
  5142.     // Optimized palette has most frequently occuring entries first
  5143.     Result := 0;
  5144.     // Reverse search to (hopefully) check latest colors first
  5145.     while (Result < FCount) do
  5146.       with (FColorMap^[Result]) do
  5147.       begin
  5148.         if (RGB.Red = Red) and (RGB.Green = Green) and (RGB.Blue = Blue) then
  5149.           exit;
  5150.         Inc(Result);
  5151.       end;
  5152.     Result := -1;
  5153.   end else
  5154.   begin
  5155.     Result := FCount-1;
  5156.     // Reverse search to (hopefully) check latest colors first
  5157.     while (Result >= 0) do
  5158.       with (FColorMap^[Result]) do
  5159.       begin
  5160.         if (RGB.Red = Red) and (RGB.Green = Green) and (RGB.Blue = Blue) then
  5161.           exit;
  5162.         Dec(Result);
  5163.       end;
  5164.   end;
  5165. end;
  5166.  
  5167. procedure TGIFColorMap.SetCapacity(Size: integer);
  5168. begin
  5169.   if (Size >= FCapacity) then
  5170.   begin
  5171.     if (Size <= InitColorMapSize) then
  5172.       FCapacity := InitColorMapSize
  5173.     else
  5174.       FCapacity := (Size + DeltaColorMapSize - 1) DIV DeltaColorMapSize * DeltaColorMapSize;
  5175.     if (FCapacity > GIFMaxColors) then
  5176.       FCapacity := GIFMaxColors;
  5177.     ReallocMem(FColorMap, FCapacity * sizeof(TGIFColor));
  5178.   end;
  5179. end;
  5180.  
  5181. //: Imports a Windows palette into the color map.
  5182. procedure TGIFColorMap.ImportPalette(Palette: HPalette);
  5183. type
  5184.   PalArray =  array[byte] of TPaletteEntry;
  5185. var
  5186.   Pal           : PalArray;
  5187.   NewCount      : integer;
  5188.   i         : integer;
  5189. begin
  5190.   Clear;
  5191.   NewCount := GetPaletteEntries(Palette, 0, 256, pal);
  5192.   if (NewCount = 0) then
  5193.     exit;
  5194.   SetCapacity(NewCount);
  5195.   for i := 0 to NewCount-1 do
  5196.     with FColorMap[i], Pal[i] do
  5197.     begin
  5198.       Red := peRed;
  5199.       Green := peGreen;
  5200.       Blue := peBlue;
  5201.     end;
  5202.   FCount := NewCount;
  5203.   Changed;
  5204. end;
  5205.  
  5206. //: Imports a color map structure into the color map.
  5207. procedure TGIFColorMap.ImportColorMap(Map: TColorMap; Count: integer);
  5208. begin
  5209.   Clear;
  5210.   if (Count = 0) then
  5211.     exit;
  5212.   SetCapacity(Count);
  5213.   FCount := Count;
  5214.  
  5215.   System.Move(Map, FColorMap^, FCount * sizeof(TGIFColor));
  5216.  
  5217.   Changed;
  5218. end;
  5219.  
  5220. //: Imports a Windows palette structure into the color map.
  5221. procedure TGIFColorMap.ImportColorTable(Pal: pointer; Count: integer);
  5222. var
  5223.   i         : integer;
  5224. begin
  5225.   Clear;
  5226.   if (Count = 0) then
  5227.     exit;
  5228.   SetCapacity(Count);
  5229.   for i := 0 to Count-1 do
  5230.     with FColorMap[i], PRGBQuadArray(Pal)[i] do
  5231.     begin
  5232.       Red := rgbRed;
  5233.       Green := rgbGreen;
  5234.       Blue := rgbBlue;
  5235.     end;
  5236.   FCount := Count;
  5237.   Changed;
  5238. end;
  5239.  
  5240. //: Imports the color table of a DIB into the color map.
  5241. procedure TGIFColorMap.ImportDIBColors(Handle: HDC);
  5242. var
  5243.   Pal           : Pointer;
  5244.   NewCount      : integer;
  5245. begin
  5246.   Clear;
  5247.   GetMem(Pal, sizeof(TRGBQuad) * 256);
  5248.   try
  5249.     NewCount := GetDIBColorTable(Handle, 0, 256, Pal^);
  5250.     ImportColorTable(Pal, NewCount);
  5251.   finally
  5252.     FreeMem(Pal);
  5253.   end;
  5254.   Changed;
  5255. end;
  5256.  
  5257. //: Creates a Windows palette from the color map.
  5258. function TGIFColorMap.ExportPalette: HPalette;
  5259. var
  5260.   Pal           : TMaxLogPalette;
  5261.   i         : Integer;
  5262. begin
  5263.   if (Count = 0) then
  5264.   begin
  5265.     Result := 0;
  5266.     exit;
  5267.   end;
  5268.   Pal.palVersion := $300;
  5269.   Pal.palNumEntries := Count;
  5270.   for i := 0 to Count-1 do
  5271.     with FColorMap[i], Pal.palPalEntry[i] do
  5272.     begin
  5273.       peRed := Red;
  5274.       peGreen := Green;
  5275.       peBlue := Blue;
  5276.       peFlags := PC_NOCOLLAPSE; { TODO -oanme -cImprovement : Verify that PC_NOCOLLAPSE is the correct value to use. }
  5277.     end;
  5278.   Result := CreatePalette(PLogPalette(@Pal)^);
  5279. end;
  5280.  
  5281. //: Adds a color to the color map.
  5282. function TGIFColorMap.Add(Color: TColor): integer;
  5283. begin
  5284.   if (FCount >= GIFMaxColors) then
  5285.     // Color map full
  5286.     Error(sTooManyColors);
  5287.  
  5288.   Result := FCount;
  5289.   if (Result >= FCapacity) then
  5290.     SetCapacity(FCount+1);
  5291.   FColorMap^[FCount] := Color2RGB(Color);
  5292.   inc(FCount);
  5293.   FOptimized := False;
  5294.   Changed;
  5295. end;
  5296.  
  5297. function TGIFColorMap.AddUnique(Color: TColor): integer;
  5298. begin
  5299.   // Look up color before add (same as IndexOf)
  5300.   Result := IndexOf(Color);
  5301.   if (Result >= 0) then
  5302.     // Color already in map
  5303.     exit;
  5304.  
  5305.   Result := Add(Color);
  5306. end;
  5307.  
  5308. //: Removes a color from the color map.
  5309. procedure TGIFColorMap.Delete(Index: integer);
  5310. begin
  5311.   if (Index < 0) or (Index >= FCount) then
  5312.     // Color index out of range
  5313.     Error(sBadColorIndex);
  5314.   dec(FCount);
  5315.   if (Index < FCount) then
  5316.     System.Move(FColorMap^[Index + 1], FColorMap^[Index], (FCount - Index)* sizeof(TGIFColor));
  5317.   FOptimized := False;
  5318.   Changed;
  5319. end;
  5320.  
  5321. function TGIFColorMap.GetColor(Index: integer): TColor;
  5322. begin
  5323.   if (Index < 0) or (Index >= FCount) then
  5324.   begin
  5325.     // Color index out of range
  5326.     Warning(gsWarning, sBadColorIndex);
  5327.     // Raise an exception if the color map is empty
  5328.     if (FCount = 0) then
  5329.       Error(sEmptyColorMap);
  5330.     // Default to color index 0
  5331.     Index := 0;
  5332.   end;
  5333.   Result := RGB2Color(FColorMap^[Index]);
  5334. end;
  5335.  
  5336. procedure TGIFColorMap.SetColor(Index: integer; Value: TColor);
  5337. begin
  5338.   if (Index < 0) or (Index >= FCount) then
  5339.     // Color index out of range
  5340.     Error(sBadColorIndex);
  5341.   FColorMap^[Index] := Color2RGB(Value);
  5342.   Changed;
  5343. end;
  5344.  
  5345. function TGIFColorMap.DoOptimize: boolean;
  5346. var
  5347.   Usage         : TColormapHistogram;
  5348.   TempMap       : array[0..255] of TGIFColor;
  5349.   ReverseMap        : TColormapReverse;
  5350.   i         : integer;
  5351.   LastFound     : boolean;
  5352.   NewCount      : integer;
  5353.   T         : TUsageCount;
  5354.   Pivot         : integer;
  5355.  
  5356.   procedure QuickSort(iLo, iHi: Integer);
  5357.   var
  5358.     Lo, Hi: Integer;
  5359.   begin
  5360.     repeat
  5361.       Lo := iLo;
  5362.       Hi := iHi;
  5363.       Pivot := Usage[(iLo + iHi) SHR 1].Count;
  5364.       repeat
  5365.         while (Usage[Lo].Count - Pivot > 0) do inc(Lo);
  5366.         while (Usage[Hi].Count - Pivot < 0) do dec(Hi);
  5367.         if (Lo <= Hi) then
  5368.         begin
  5369.           T := Usage[Lo];
  5370.           Usage[Lo] := Usage[Hi];
  5371.           Usage[Hi] := T;
  5372.           inc(Lo);
  5373.           dec(Hi);
  5374.         end;
  5375.       until (Lo > Hi);
  5376.       if (iLo < Hi) then
  5377.         QuickSort(iLo, Hi);
  5378.       iLo := Lo;
  5379.     until (Lo >= iHi);
  5380.   end;
  5381.  
  5382. begin
  5383.   if (FCount <= 1) then
  5384.   begin
  5385.     Result := False;
  5386.     exit;
  5387.   end;
  5388.  
  5389.   FOptimized := True;
  5390.   Result := True;
  5391.  
  5392.   BuildHistogram(Usage);
  5393.  
  5394.   (*
  5395.   **  Sort according to usage count
  5396.   *)
  5397.   QuickSort(0, FCount-1);
  5398.  
  5399.   (*
  5400.   ** Test for table already sorted
  5401.   *)
  5402.   for i := 0 to FCount-1 do
  5403.     if (Usage[i].Index <> i) then
  5404.       break;
  5405.   if (i = FCount) then
  5406.     exit;
  5407.  
  5408.   (*
  5409.   ** Build old to new map
  5410.   *)
  5411.   for i := 0 to FCount-1 do
  5412.     ReverseMap[Usage[i].Index] := i;
  5413.  
  5414.  
  5415.   MapImages(ReverseMap);
  5416.  
  5417.   (*
  5418.   **  Reorder colormap
  5419.   *)
  5420.   LastFound := False;
  5421.   NewCount := FCount;
  5422.   Move(FColorMap^, TempMap, FCount * sizeof(TGIFColor));
  5423.   for i := 0 to FCount-1 do
  5424.   begin
  5425.     FColorMap^[ReverseMap[i]] := TempMap[i];
  5426.     // Find last used color index
  5427.     if (Usage[i].Count = 0) and not(LastFound) then
  5428.     begin
  5429.       LastFound := True;
  5430.       NewCount := i;
  5431.     end;
  5432.   end;
  5433.  
  5434.   FCount := NewCount;
  5435.  
  5436.   Changed;
  5437. end;
  5438.  
  5439. function TGIFColorMap.GetBitsPerPixel: integer;
  5440. begin
  5441.   Result := Colors2bpp(FCount);
  5442. end;
  5443.  
  5444. //: Copies one color map to another.
  5445. procedure TGIFColorMap.Assign(Source: TPersistent);
  5446. begin
  5447.   if (Source is TGIFColorMap) then
  5448.   begin
  5449.     Clear;
  5450.     FCapacity := TGIFColorMap(Source).FCapacity;
  5451.     FCount := TGIFColorMap(Source).FCount;
  5452.     FOptimized := TGIFColorMap(Source).FOptimized;
  5453.     FColorMap := AllocMem(FCapacity * sizeof(TGIFColor));
  5454.     System.Move(TGIFColorMap(Source).FColorMap^, FColorMap^, FCount * sizeof(TGIFColor));
  5455.     Changed;
  5456.   end else
  5457.     inherited Assign(Source);
  5458. end;
  5459.  
  5460. ////////////////////////////////////////////////////////////////////////////////
  5461. //
  5462. //          TGIFItem
  5463. //
  5464. ////////////////////////////////////////////////////////////////////////////////
  5465. constructor TGIFItem.Create(GIFImage: TGIFImage);
  5466. begin
  5467.   inherited Create;
  5468.  
  5469.   FGIFImage := GIFImage;
  5470. end;
  5471.  
  5472. procedure TGIFItem.Warning(Severity: TGIFSeverity; Message: string);
  5473. begin
  5474.   FGIFImage.Warning(self, Severity, Message);
  5475. end;
  5476.  
  5477. function TGIFItem.GetVersion: TGIFVersion;
  5478. begin
  5479.   Result := gv87a;
  5480. end;
  5481.  
  5482. procedure TGIFItem.LoadFromFile(const Filename: string);
  5483. var
  5484.   Stream: TStream;
  5485. begin
  5486.   Stream := TFileStream.Create(Filename, fmOpenRead OR fmShareDenyWrite);
  5487.   try
  5488.     LoadFromStream(Stream);
  5489.   finally
  5490.     Stream.Free;
  5491.   end;
  5492. end;
  5493.  
  5494. procedure TGIFItem.SaveToFile(const Filename: string);
  5495. var
  5496.   Stream: TStream;
  5497. begin
  5498.   Stream := TFileStream.Create(Filename, fmCreate);
  5499.   try
  5500.     SaveToStream(Stream);
  5501.   finally
  5502.     Stream.Free;
  5503.   end;
  5504. end;
  5505.  
  5506. ////////////////////////////////////////////////////////////////////////////////
  5507. //
  5508. //          TGIFList
  5509. //
  5510. ////////////////////////////////////////////////////////////////////////////////
  5511. constructor TGIFList.Create(Image: TGIFImage);
  5512. begin
  5513.   inherited Create;
  5514.   FImage := Image;
  5515.   FItems := TList.Create;
  5516. end;
  5517.  
  5518. destructor TGIFList.Destroy;
  5519. begin
  5520.   Clear;
  5521.   FItems.Free;
  5522.   inherited Destroy;
  5523. end;
  5524.  
  5525. function TGIFList.GetItem(Index: Integer): TGIFItem;
  5526. begin
  5527.   Result := TGIFItem(FItems[Index]);
  5528. end;
  5529.  
  5530. procedure TGIFList.SetItem(Index: Integer; Item: TGIFItem);
  5531. begin
  5532.   FItems[Index] := Item;
  5533. end;
  5534.  
  5535. function TGIFList.GetCount: Integer;
  5536. begin
  5537.   Result := FItems.Count;
  5538. end;
  5539.  
  5540. function TGIFList.Add(Item: TGIFItem): Integer;
  5541. begin
  5542.   Result := FItems.Add(Item);
  5543. end;
  5544.  
  5545. procedure TGIFList.Clear;
  5546. begin
  5547.   while (FItems.Count > 0) do
  5548.     Delete(0);
  5549. end;
  5550.  
  5551. procedure TGIFList.Delete(Index: Integer);
  5552. var
  5553.   Item          : TGIFItem;
  5554. begin
  5555.   Item := TGIFItem(FItems[Index]);
  5556.   // Delete before item is destroyed to avoid recursion
  5557.   FItems.Delete(Index);
  5558.   Item.Free;
  5559. end;
  5560.  
  5561. procedure TGIFList.Exchange(Index1, Index2: Integer);
  5562. begin
  5563.   FItems.Exchange(Index1, Index2);
  5564. end;
  5565.  
  5566. function TGIFList.First: TGIFItem;
  5567. begin
  5568.   Result := TGIFItem(FItems.First);
  5569. end;
  5570.  
  5571. function TGIFList.IndexOf(Item: TGIFItem): Integer;
  5572. begin
  5573.   Result := FItems.IndexOf(Item);
  5574. end;
  5575.  
  5576. procedure TGIFList.Insert(Index: Integer; Item: TGIFItem);
  5577. begin
  5578.   FItems.Insert(Index, Item);
  5579. end;
  5580.  
  5581. function TGIFList.Last: TGIFItem;
  5582. begin
  5583.   Result := TGIFItem(FItems.Last);
  5584. end;
  5585.  
  5586. procedure TGIFList.Move(CurIndex, NewIndex: Integer);
  5587. begin
  5588.   FItems.Move(CurIndex, NewIndex);
  5589. end;
  5590.  
  5591. function TGIFList.Remove(Item: TGIFItem): Integer;
  5592. begin
  5593.   // Note: TGIFList.Remove must not destroy item
  5594.   Result := FItems.Remove(Item);
  5595. end;
  5596.  
  5597. procedure TGIFList.SaveToStream(Stream: TStream);
  5598. var
  5599.   i         : integer;
  5600. begin
  5601.   for i := 0 to FItems.Count-1 do
  5602.     TGIFItem(FItems[i]).SaveToStream(Stream);
  5603. end;
  5604.  
  5605. procedure TGIFList.Warning(Severity: TGIFSeverity; Message: string);
  5606. begin
  5607.   Image.Warning(self, Severity, Message);
  5608. end;
  5609.  
  5610. ////////////////////////////////////////////////////////////////////////////////
  5611. //
  5612. //          TGIFGlobalColorMap
  5613. //
  5614. ////////////////////////////////////////////////////////////////////////////////
  5615. type
  5616.   TGIFGlobalColorMap = class(TGIFColorMap)
  5617.   private
  5618.     FHeader : TGIFHeader;
  5619.   protected
  5620.     procedure Warning(Severity: TGIFSeverity; Message: string); override;
  5621.     procedure BuildHistogram(var Histogram: TColormapHistogram); override;
  5622.     procedure MapImages(var Map: TColormapReverse); override;
  5623.   public
  5624.     constructor Create(HeaderItem: TGIFHeader);
  5625.     function Optimize: boolean; override;
  5626.     procedure Changed; override;
  5627.   end;
  5628.  
  5629. constructor TGIFGlobalColorMap.Create(HeaderItem: TGIFHeader);
  5630. begin
  5631.   Inherited Create;
  5632.   FHeader := HeaderItem;
  5633. end;
  5634.  
  5635. procedure TGIFGlobalColorMap.Warning(Severity: TGIFSeverity; Message: string);
  5636. begin
  5637.   FHeader.Image.Warning(self, Severity, Message);
  5638. end;
  5639.  
  5640. procedure TGIFGlobalColorMap.BuildHistogram(var Histogram: TColormapHistogram);
  5641. var
  5642.   Pixel         ,
  5643.   LastPixel     : PAnsiChar;
  5644.   i         : integer;
  5645. begin
  5646.   (*
  5647.   ** Init histogram
  5648.   *)
  5649.   for i := 0 to Count-1 do
  5650.   begin
  5651.     Histogram[i].Index := i;
  5652.     Histogram[i].Count := 0;
  5653.   end;
  5654.  
  5655.   for i := 0 to FHeader.Image.Images.Count-1 do
  5656.     if (FHeader.Image.Images[i].ActiveColorMap = self) then
  5657.     begin
  5658.       Pixel := FHeader.Image.Images[i].Data;
  5659.       LastPixel := Pixel + FHeader.Image.Images[i].Width * FHeader.Image.Images[i].Height;
  5660.  
  5661.       (*
  5662.       ** Sum up usage count for each color
  5663.       *)
  5664.       while (Pixel < LastPixel) do
  5665.       begin
  5666.         inc(Histogram[ord(Pixel^)].Count);
  5667.         inc(Pixel);
  5668.       end;
  5669.     end;
  5670. end;
  5671.  
  5672. procedure TGIFGlobalColorMap.MapImages(var Map: TColormapReverse);
  5673. var
  5674.   Pixel         ,
  5675.   LastPixel     : PAnsiChar;
  5676.   i         : integer;
  5677. begin
  5678.   for i := 0 to FHeader.Image.Images.Count-1 do
  5679.     if (FHeader.Image.Images[i].ActiveColorMap = self) then
  5680.     begin
  5681.       Pixel := FHeader.Image.Images[i].Data;
  5682.       LastPixel := Pixel + FHeader.Image.Images[i].Width * FHeader.Image.Images[i].Height;
  5683.  
  5684.       (*
  5685.       **  Reorder all pixel to new map
  5686.       *)
  5687.       while (Pixel < LastPixel) do
  5688.       begin
  5689. // 2008.10.19 ->
  5690. //        Pixel^ := chr(Map[ord(Pixel^)]);
  5691.         Pixel^ := AnsiChar(Map[ord(Pixel^)]);
  5692. // 2008.10.19 <-
  5693.         inc(Pixel);
  5694.       end;
  5695.  
  5696.       (*
  5697.       **  Reorder transparent colors
  5698.       *)
  5699.       if (FHeader.Image.Images[i].Transparent) then
  5700.         FHeader.Image.Images[i].GraphicControlExtension.TransparentColorIndex :=
  5701.           Map[FHeader.Image.Images[i].GraphicControlExtension.TransparentColorIndex];
  5702.     end;
  5703. end;
  5704.  
  5705. function TGIFGlobalColorMap.Optimize: boolean;
  5706. begin
  5707.   { Optimize with first image, Remove unused colors if only one image }
  5708.   if (FHeader.Image.Images.Count > 0) then
  5709.     Result := DoOptimize
  5710.   else
  5711.     Result := False;
  5712. end;
  5713.  
  5714. procedure TGIFGlobalColorMap.Changed;
  5715. begin
  5716.   FHeader.Image.Palette := 0;
  5717. end;
  5718.  
  5719. ////////////////////////////////////////////////////////////////////////////////
  5720. //
  5721. //          TGIFHeader
  5722. //
  5723. ////////////////////////////////////////////////////////////////////////////////
  5724. constructor TGIFHeader.Create(GIFImage: TGIFImage);
  5725. begin
  5726.   inherited Create(GIFImage);
  5727.   FColorMap := TGIFGlobalColorMap.Create(self);
  5728.   Clear;
  5729. end;
  5730.  
  5731. destructor TGIFHeader.Destroy;
  5732. begin
  5733.   FColorMap.Free;
  5734.   inherited Destroy;
  5735. end;
  5736.  
  5737. procedure TGIFHeader.Clear;
  5738. begin
  5739.   FColorMap.Clear;
  5740.   FLogicalScreenDescriptor.ScreenWidth := 0;
  5741.   FLogicalScreenDescriptor.ScreenHeight := 0;
  5742.   FLogicalScreenDescriptor.PackedFields := 0;
  5743.   FLogicalScreenDescriptor.BackgroundColorIndex := 0;
  5744.   FLogicalScreenDescriptor.AspectRatio := 0;
  5745. end;
  5746.  
  5747. procedure TGIFHeader.Assign(Source: TPersistent);
  5748. begin
  5749.   if (Source is TGIFHeader) then
  5750.   begin
  5751.     ColorMap.Assign(TGIFHeader(Source).ColorMap);
  5752.     FLogicalScreenDescriptor := TGIFHeader(Source).FLogicalScreenDescriptor;
  5753.   end else
  5754.   if (Source is TGIFColorMap) then
  5755.   begin
  5756.     Clear;
  5757.     ColorMap.Assign(TGIFColorMap(Source));
  5758.   end else
  5759.     inherited Assign(Source);
  5760. end;
  5761.  
  5762. type
  5763.   TGIFHeaderRec = packed record
  5764.     Signature: array[0..2] of AnsiChar; { contains 'GIF' }
  5765.     Version: TGIFVersionRec;   { '87a' or '89a' }
  5766.   end;
  5767.  
  5768. const
  5769.   { logical screen descriptor packed field masks }
  5770.   lsdGlobalColorTable   = $80;      { set if global color table follows L.S.D. }
  5771.   lsdColorResolution    = $70;      { Color resolution - 3 bits }
  5772.   lsdSort       = $08;      { set if global color table is sorted - 1 bit }
  5773.   lsdColorTableSize = $07;      { size of global color table - 3 bits }
  5774.                     { Actual size = 2^value+1    - value is 3 bits }
  5775. procedure TGIFHeader.Prepare;
  5776. var
  5777.   pack          : BYTE;
  5778. begin
  5779.   Pack := $00;
  5780.   if (ColorMap.Count > 0) then
  5781.   begin
  5782.     Pack := lsdGlobalColorTable;
  5783.     if (ColorMap.Optimized) then
  5784.       Pack := Pack OR lsdSort;
  5785.   end;
  5786.   // Note: The SHL below was SHL 5 in the original source, but that looks wrong
  5787.   Pack := Pack OR ((Image.ColorResolution SHL 4) AND lsdColorResolution);
  5788.   Pack := Pack OR ((Image.BitsPerPixel-1) AND lsdColorTableSize);
  5789.   FLogicalScreenDescriptor.PackedFields := Pack;
  5790. end;
  5791.  
  5792. procedure TGIFHeader.SaveToStream(Stream: TStream);
  5793. var
  5794.   GifHeader     : TGIFHeaderRec;
  5795.   v         : TGIFVersion;
  5796. begin
  5797.   v := Image.Version;
  5798.   if (v = gvUnknown) then
  5799.     Error(sBadVersion);
  5800.  
  5801.   GifHeader.Signature := 'GIF';
  5802.   GifHeader.Version := GIFVersions[v];
  5803.  
  5804.   Prepare;
  5805.   Stream.Write(GifHeader, sizeof(GifHeader));
  5806.   Stream.Write(FLogicalScreenDescriptor, sizeof(FLogicalScreenDescriptor));
  5807.   if (FLogicalScreenDescriptor.PackedFields AND lsdGlobalColorTable = lsdGlobalColorTable) then
  5808.     ColorMap.SaveToStream(Stream);
  5809. end;
  5810.  
  5811. procedure TGIFHeader.LoadFromStream(Stream: TStream);
  5812. var
  5813.   GifHeader     : TGIFHeaderRec;
  5814.   ColorCount        : integer;
  5815.   Position      : integer;
  5816. begin
  5817.   Position := Stream.Position;
  5818.  
  5819.   ReadCheck(Stream, GifHeader, sizeof(GifHeader));
  5820. // 2008.10.19 ->
  5821. //  if (uppercase(GifHeader.Signature) <> 'GIF') then
  5822.   if (uppercase(string(GifHeader.Signature)) <> 'GIF') then
  5823. // 2008.10.19 <-
  5824.   begin
  5825.     // Attempt recovery in case we are reading a GIF stored in a form by rxLib
  5826.     Stream.Position := Position;
  5827.     // Seek past size stored in stream
  5828.     Stream.Seek(sizeof(longInt), soFromCurrent);
  5829.     // Attempt to read signature again
  5830.     ReadCheck(Stream, GifHeader, sizeof(GifHeader));
  5831. // 2008.10.19 ->
  5832. //    if (uppercase(GifHeader.Signature) <> 'GIF') then
  5833.     if (uppercase(string(GifHeader.Signature)) <> 'GIF') then
  5834. // 2008.10.19 <-
  5835.       Error(sBadSignature);
  5836.   end;
  5837.  
  5838.   ReadCheck(Stream, FLogicalScreenDescriptor, sizeof(FLogicalScreenDescriptor));
  5839.  
  5840.   if (FLogicalScreenDescriptor.PackedFields AND lsdGlobalColorTable = lsdGlobalColorTable) then
  5841.   begin
  5842.     ColorCount := 2 SHL (FLogicalScreenDescriptor.PackedFields AND lsdColorTableSize);
  5843.     if (ColorCount < 2) or (ColorCount > 256) then
  5844.       Error(sScreenBadColorSize);
  5845.     ColorMap.LoadFromStream(Stream, ColorCount)
  5846.   end else
  5847.     ColorMap.Clear;
  5848. end;
  5849.  
  5850. function TGIFHeader.GetVersion: TGIFVersion;
  5851. begin
  5852.   if (FColorMap.Optimized) or (AspectRatio <> 0) then
  5853.     Result := gv89a
  5854.   else
  5855.     Result := inherited GetVersion;
  5856. end;
  5857.  
  5858. function TGIFHeader.GetBackgroundColor: TColor;
  5859. begin
  5860.   Result := FColorMap[BackgroundColorIndex];
  5861. end;
  5862.  
  5863. procedure TGIFHeader.SetBackgroundColor(Color: TColor);
  5864. begin
  5865.   BackgroundColorIndex := FColorMap.AddUnique(Color);
  5866. end;
  5867.  
  5868. procedure TGIFHeader.SetBackgroundColorIndex(Index: BYTE);
  5869. begin
  5870.   if ((Index >= FColorMap.Count) and (FColorMap.Count > 0)) then
  5871.   begin
  5872.     Warning(gsWarning, sBadColorIndex);
  5873.     Index := 0;
  5874.   end;
  5875.   FLogicalScreenDescriptor.BackgroundColorIndex := Index;
  5876. end;
  5877.  
  5878. function TGIFHeader.GetBitsPerPixel: integer;
  5879. begin
  5880.   Result := FColorMap.BitsPerPixel;
  5881. end;
  5882.  
  5883. function TGIFHeader.GetColorResolution: integer;
  5884. begin
  5885.   Result := FColorMap.BitsPerPixel-1;
  5886. end;
  5887.  
  5888. ////////////////////////////////////////////////////////////////////////////////
  5889. //
  5890. //          TGIFLocalColorMap
  5891. //
  5892. ////////////////////////////////////////////////////////////////////////////////
  5893. type
  5894.   TGIFLocalColorMap = class(TGIFColorMap)
  5895.   private
  5896.     FSubImage       : TGIFSubImage;
  5897.   protected
  5898.     procedure Warning(Severity: TGIFSeverity; Message: string); override;
  5899.     procedure BuildHistogram(var Histogram: TColormapHistogram); override;
  5900.     procedure MapImages(var Map: TColormapReverse); override;
  5901.   public
  5902.     constructor Create(SubImage: TGIFSubImage);
  5903.     function Optimize: boolean; override;
  5904.     procedure Changed; override;
  5905.   end;
  5906.  
  5907. constructor TGIFLocalColorMap.Create(SubImage: TGIFSubImage);
  5908. begin
  5909.   Inherited Create;
  5910.   FSubImage := SubImage;
  5911. end;
  5912.  
  5913. procedure TGIFLocalColorMap.Warning(Severity: TGIFSeverity; Message: string);
  5914. begin
  5915.   FSubImage.Image.Warning(self, Severity, Message);
  5916. end;
  5917.  
  5918. procedure TGIFLocalColorMap.BuildHistogram(var Histogram: TColormapHistogram);
  5919. var
  5920.   Pixel         ,
  5921.   LastPixel     : PAnsiChar;
  5922.   i         : integer;
  5923. begin
  5924.   Pixel := FSubImage.Data;
  5925.   LastPixel := Pixel + FSubImage.Width * FSubImage.Height;
  5926.  
  5927.   (*
  5928.   ** Init histogram
  5929.   *)
  5930.   for i := 0 to Count-1 do
  5931.   begin
  5932.     Histogram[i].Index := i;
  5933.     Histogram[i].Count := 0;
  5934.   end;
  5935.  
  5936.   (*
  5937.   ** Sum up usage count for each color
  5938.   *)
  5939.   while (Pixel < LastPixel) do
  5940.   begin
  5941.     inc(Histogram[ord(Pixel^)].Count);
  5942.     inc(Pixel);
  5943.   end;
  5944. end;
  5945.  
  5946. procedure TGIFLocalColorMap.MapImages(var Map: TColormapReverse);
  5947. var
  5948.   Pixel         ,
  5949.   LastPixel     : PAnsiChar;
  5950. begin
  5951.   Pixel := FSubImage.Data;
  5952.   LastPixel := Pixel + FSubImage.Width * FSubImage.Height;
  5953.  
  5954.   (*
  5955.   **  Reorder all pixel to new map
  5956.   *)
  5957.   while (Pixel < LastPixel) do
  5958.   begin
  5959. // 2008.10.19 ->
  5960. //    Pixel^ := chr(Map[ord(Pixel^)]);
  5961.     Pixel^ := AnsiChar(Map[ord(Pixel^)]);
  5962. // 2008.10.19 <-
  5963.     inc(Pixel);
  5964.   end;
  5965.  
  5966.   (*
  5967.   **  Reorder transparent colors
  5968.   *)
  5969.   if (FSubImage.Transparent) then
  5970.     FSubImage.GraphicControlExtension.TransparentColorIndex :=
  5971.       Map[FSubImage.GraphicControlExtension.TransparentColorIndex];
  5972. end;
  5973.  
  5974. function TGIFLocalColorMap.Optimize: boolean;
  5975. begin
  5976.   Result := DoOptimize;
  5977. end;
  5978.  
  5979. procedure TGIFLocalColorMap.Changed;
  5980. begin
  5981.   FSubImage.Palette := 0;
  5982. end;
  5983.  
  5984.  
  5985. ////////////////////////////////////////////////////////////////////////////////
  5986. //
  5987. //          LZW Decoder
  5988. //
  5989. ////////////////////////////////////////////////////////////////////////////////
  5990. const
  5991.   GIFCodeBits       = 12;           // Max number of bits per GIF token code
  5992.   GIFCodeMax        = (1 SHL GIFCodeBits)-1;// Max GIF token code
  5993.                         // 12 bits = 4095
  5994.   StackSize     = (2 SHL GIFCodeBits);  // Size of decompression stack
  5995.   TableSize     = (1 SHL GIFCodeBits);  // Size of decompression table
  5996.  
  5997. procedure TGIFSubImage.Decompress(Stream: TStream);
  5998. var
  5999.   table0        : array[0..TableSize-1] of integer;
  6000.   table1        : array[0..TableSize-1] of integer;
  6001.   firstcode, oldcode    : integer;
  6002.   buf           : array[0..257] of BYTE;
  6003.  
  6004.   Dest          : PAnsiChar;
  6005.   v         ,
  6006.   xpos, ypos, pass  : integer;
  6007.  
  6008.   stack         : array[0..StackSize-1] of integer;
  6009.   Source            : ^integer;
  6010.   BitsPerCode       : integer;      // number of CodeTableBits/code
  6011.   InitialBitsPerCode    : BYTE;
  6012.  
  6013.   MaxCode       : integer;      // maximum code, given BitsPerCode
  6014.   MaxCodeSize       : integer;
  6015.   ClearCode     : integer;      // Special code to signal "Clear table"
  6016.   EOFCode       : integer;      // Special code to signal EOF
  6017.   step          : integer;
  6018.   i         : integer;
  6019.  
  6020.   StartBit      ,           // Index of bit buffer start
  6021.   LastBit       ,           // Index of last bit in buffer
  6022.   LastByte      : integer;      // Index of last byte in buffer
  6023.   get_done      ,
  6024.   return_clear      ,
  6025.   ZeroBlock     : boolean;
  6026.   ClearValue        : BYTE;
  6027. {$ifdef DEBUG_DECOMPRESSPERFORMANCE}
  6028.   TimeStartDecompress   ,
  6029.   TimeStopDecompress    : DWORD;
  6030. {$endif}
  6031.  
  6032.   function nextCode(BitsPerCode: integer): integer;
  6033.   const
  6034.     masks: array[0..15] of integer =
  6035.       ($0000, $0001, $0003, $0007,
  6036.        $000f, $001f, $003f, $007f,
  6037.        $00ff, $01ff, $03ff, $07ff,
  6038.        $0fff, $1fff, $3fff, $7fff);
  6039.   var
  6040.     StartIndex, EndIndex        : integer;
  6041.     ret         : integer;
  6042.     EndBit      : integer;
  6043.     count       : BYTE;
  6044.   begin
  6045.     if (return_clear) then
  6046.     begin
  6047.       return_clear := False;
  6048.       Result := ClearCode;
  6049.       exit;
  6050.     end;
  6051.  
  6052.     EndBit := StartBit + BitsPerCode;
  6053.  
  6054.     if (EndBit >= LastBit) then
  6055.     begin
  6056.       if (get_done) then
  6057.       begin
  6058.         if (StartBit >= LastBit) then
  6059.           Warning(gsWarning, sDecodeTooFewBits);
  6060.         Result := -1;
  6061.         exit;
  6062.       end;
  6063.       buf[0] := buf[LastByte-2];
  6064.       buf[1] := buf[LastByte-1];
  6065.  
  6066.       if (Stream.Read(count, 1) <> 1) then
  6067.       begin
  6068.         Result := -1;
  6069.         exit;
  6070.       end;
  6071.       if (count = 0) then
  6072.       begin
  6073.         ZeroBlock := True;
  6074.         get_done := TRUE;
  6075.       end else
  6076.       begin
  6077.         // Handle premature end of file
  6078.         if (Stream.Size - Stream.Position < Count) then
  6079.         begin
  6080.           Warning(gsWarning, sOutOfData);
  6081.           // Not enough data left - Just read as much as we can get
  6082.           Count := Stream.Size - Stream.Position;
  6083.         end;
  6084.         if (Count <> 0) then
  6085.           ReadCheck(Stream, Buf[2], Count);
  6086.       end;
  6087.  
  6088.       LastByte := 2 + count;
  6089.       StartBit := (StartBit - LastBit) + 16;
  6090.       LastBit := LastByte * 8;
  6091.  
  6092.       EndBit := StartBit + BitsPerCode;
  6093.     end;
  6094.  
  6095.     EndIndex := EndBit DIV 8;
  6096.     StartIndex := StartBit DIV 8;
  6097.  
  6098.     ASSERT(StartIndex <= high(buf), 'StartIndex too large');
  6099.     if (StartIndex = EndIndex) then
  6100.       ret := buf[StartIndex]
  6101.     else
  6102.       if (StartIndex + 1 = EndIndex) then
  6103.         ret := buf[StartIndex] OR (buf[StartIndex+1] SHL 8)
  6104.       else
  6105.         ret := buf[StartIndex] OR (buf[StartIndex+1] SHL 8) OR (buf[StartIndex+2] SHL 16);
  6106.  
  6107.     ret := (ret SHR (StartBit AND $0007)) AND masks[BitsPerCode];
  6108.  
  6109.     Inc(StartBit, BitsPerCode);
  6110.  
  6111.     Result := ret;
  6112.   end;
  6113.  
  6114.   function NextLZW: integer;
  6115.   var
  6116.     code, incode    : integer;
  6117.     i           : integer;
  6118.     b           : BYTE;
  6119.   begin
  6120.     code := nextCode(BitsPerCode);
  6121.     while (code >= 0) do
  6122.     begin
  6123.       if (code = ClearCode) then
  6124.       begin
  6125.         ASSERT(ClearCode < TableSize, 'ClearCode too large');
  6126.         for i := 0 to ClearCode-1 do
  6127.         begin
  6128.           table0[i] := 0;
  6129.           table1[i] := i;
  6130.         end;
  6131.         for i := ClearCode to TableSize-1 do
  6132.         begin
  6133.           table0[i] := 0;
  6134.           table1[i] := 0;
  6135.         end;
  6136.         BitsPerCode := InitialBitsPerCode+1;
  6137.         MaxCodeSize := 2 * ClearCode;
  6138.         MaxCode := ClearCode + 2;
  6139.         Source := @stack;
  6140.         repeat
  6141.           firstcode := nextCode(BitsPerCode);
  6142.           oldcode := firstcode;
  6143.         until (firstcode <> ClearCode);
  6144.  
  6145.         Result := firstcode;
  6146.         exit;
  6147.       end;
  6148.       if (code = EOFCode) then
  6149.       begin
  6150.         Result := -2;
  6151.         if (ZeroBlock) then
  6152.           exit;
  6153.         // Eat rest of data blocks
  6154.         if (Stream.Read(b, 1) <> 1) then
  6155.           exit;
  6156.         while (b <> 0) do
  6157.         begin
  6158.           Stream.Seek(b, soFromCurrent);
  6159.           if (Stream.Read(b, 1) <> 1) then
  6160.             exit;
  6161.         end;
  6162.         exit;
  6163.       end;
  6164.  
  6165.       incode := code;
  6166.  
  6167.       if (code >= MaxCode) then
  6168.       begin
  6169.         Source^ := firstcode;
  6170.         Inc(Source);
  6171.         code := oldcode;
  6172.       end;
  6173.  
  6174.       ASSERT(Code < TableSize, 'Code too large');
  6175.       while (code >= ClearCode) do
  6176.       begin
  6177.         Source^ := table1[code];
  6178.         Inc(Source);
  6179.         if (code = table0[code]) then
  6180.           Error(sDecodeCircular);
  6181.         code := table0[code];
  6182.         ASSERT(Code < TableSize, 'Code too large');
  6183.       end;
  6184.  
  6185.       firstcode := table1[code];
  6186.       Source^ := firstcode;
  6187.       Inc(Source);
  6188.  
  6189.       code := MaxCode;
  6190.       if (code <= GIFCodeMax) then
  6191.       begin
  6192.         table0[code] := oldcode;
  6193.         table1[code] := firstcode;
  6194.         Inc(MaxCode);
  6195.         if ((MaxCode >= MaxCodeSize) and (MaxCodeSize <= GIFCodeMax)) then
  6196.         begin
  6197.           MaxCodeSize := MaxCodeSize * 2;
  6198.           Inc(BitsPerCode);
  6199.         end;
  6200.       end;
  6201.  
  6202.       oldcode := incode;
  6203.  
  6204.       if (longInt(Source) > longInt(@stack)) then
  6205.       begin
  6206.         Dec(Source);
  6207.         Result := Source^;
  6208.         exit;
  6209.       end
  6210.     end;
  6211.     Result := code;
  6212.   end;
  6213.  
  6214.   function readLZW: integer;
  6215.   begin
  6216.     if (longInt(Source) > longInt(@stack)) then
  6217.     begin
  6218.       Dec(Source);
  6219.       Result := Source^;
  6220.     end else
  6221.       Result := NextLZW;
  6222.   end;
  6223.  
  6224. begin
  6225.   NewImage;
  6226.  
  6227.   // Clear image data in case decompress doesn't complete
  6228.   if (Transparent) then
  6229.     // Clear to transparent color
  6230.     ClearValue := GraphicControlExtension.GetTransparentColorIndex
  6231.   else
  6232.     // Clear to first color
  6233.     ClearValue := 0;
  6234.  
  6235.   FillChar(FData^, FDataSize, ClearValue);
  6236.  
  6237. {$ifdef DEBUG_DECOMPRESSPERFORMANCE}
  6238.   TimeStartDecompress := timeGetTime;
  6239. {$endif}
  6240.  
  6241.   (*
  6242.   ** Read initial code size in bits from stream
  6243.   *)
  6244.   if (Stream.Read(InitialBitsPerCode, 1) <> 1) then
  6245.     exit;
  6246. // 2006.07.29 ->
  6247.   if InitialBitsPerCode > 8 then
  6248.     InitialBitsPerCode := 8;
  6249. // 2006.07.29 <-
  6250.   (*
  6251.   **  Initialize the Compression routines
  6252.   *)
  6253.   BitsPerCode := InitialBitsPerCode + 1;
  6254.   ClearCode := 1 SHL InitialBitsPerCode;
  6255.   EOFCode := ClearCode + 1;
  6256.   MaxCodeSize := 2 * ClearCode;
  6257.   MaxCode := ClearCode + 2;
  6258.  
  6259.   StartBit := 0;
  6260.   LastBit := 0;
  6261.   LastByte := 2;
  6262.  
  6263.   ZeroBlock := False;
  6264.   get_done := False;
  6265.   return_clear := TRUE;
  6266.  
  6267.   Source := @stack;
  6268.  
  6269.   try
  6270.     if (Interlaced) then
  6271.     begin
  6272.       ypos := 0;
  6273.       pass := 0;
  6274.       step := 8;
  6275.  
  6276.       for i := 0 to Height-1 do
  6277.       begin
  6278.         Dest := FData + Width * ypos;
  6279.         for xpos := 0 to width-1 do
  6280.         begin
  6281.           v := readLZW;
  6282.           if (v < 0) then
  6283.             exit;
  6284.           Dest^ := AnsiChar(v);
  6285.           Inc(Dest);
  6286.         end;
  6287.         Inc(ypos, step);
  6288.         if (ypos >= height) then
  6289.           repeat
  6290.             if (pass > 0) then
  6291.               step := step DIV 2;
  6292.             Inc(pass);
  6293.             ypos := step DIV 2;
  6294.           until (ypos < height);
  6295.       end;
  6296.     end else
  6297.     begin
  6298.       Dest := FData;
  6299.       for ypos := 0 to (height * width)-1 do
  6300.       begin
  6301.         v := readLZW;
  6302.         if (v < 0) then
  6303.           exit;
  6304.         Dest^ := AnsiChar(v);
  6305.         Inc(Dest);
  6306.       end;
  6307.     end;
  6308.   finally
  6309.     if (readLZW >= 0) then
  6310.       ;
  6311. //      raise GIFException.Create('Too much input data, ignoring extra...');
  6312.   end;
  6313. {$ifdef DEBUG_DECOMPRESSPERFORMANCE}
  6314.   TimeStopDecompress := timeGetTime;
  6315.   ShowMessage(format('Decompressed %d pixels in %d mS, Rate %d pixels/mS',
  6316.     [Height*Width, TimeStopDecompress-TimeStartDecompress,
  6317.     (Height*Width) DIV (TimeStopDecompress-TimeStartDecompress+1)]));
  6318. {$endif}
  6319. end;
  6320.  
  6321. ////////////////////////////////////////////////////////////////////////////////
  6322. //
  6323. //          LZW Encoder stuff
  6324. //
  6325. ////////////////////////////////////////////////////////////////////////////////
  6326.  
  6327. ////////////////////////////////////////////////////////////////////////////////
  6328. //          LZW Encoder THashTable
  6329. ////////////////////////////////////////////////////////////////////////////////
  6330. const
  6331.   HashKeyBits       = 13;           // Max number of bits per Hash Key
  6332.  
  6333.   HashSize      = 8009;         // Size of hash table
  6334.                         // Must be prime
  6335.                                                 // Must be > than HashMaxCode
  6336.                                                 // Must be < than HashMaxKey
  6337.  
  6338.   HashKeyMax        = (1 SHL HashKeyBits)-1;// Max hash key value
  6339.                         // 13 bits = 8191
  6340.  
  6341.   HashKeyMask       = HashKeyMax;       // $1FFF
  6342.   GIFCodeMask       = GIFCodeMax;       // $0FFF
  6343.  
  6344.   HashEmpty     = $000FFFFF;        // 20 bits
  6345.  
  6346. type
  6347.   // A Hash Key is 20 bits wide.
  6348.   // - The lower 8 bits are the postfix character (the new pixel).
  6349.   // - The upper 12 bits are the prefix code (the GIF token).
  6350.   // A KeyInt must be able to represent the integer values -1..(2^20)-1
  6351.   KeyInt = longInt; // 32 bits
  6352.   CodeInt = SmallInt;   // 16 bits
  6353.  
  6354.   THashArray = array[0..HashSize-1] of KeyInt;
  6355.   PHashArray = ^THashArray;
  6356.  
  6357.   THashTable = class
  6358. {$ifdef DEBUG_HASHPERFORMANCE}
  6359.     CountLookupFound    : longInt;
  6360.     CountMissFound  : longInt;
  6361.     CountLookupNotFound : longInt;
  6362.     CountMissNotFound   : longInt;
  6363. {$endif}
  6364.     HashTable: PHashArray;
  6365.   public
  6366.     constructor Create;
  6367.     destructor Destroy; override;
  6368.     procedure Clear;
  6369.     procedure Insert(Key: KeyInt; Code: CodeInt);
  6370.     function Lookup(Key: KeyInt): CodeInt;
  6371.   end;
  6372.  
  6373. function HashKey(Key: KeyInt): CodeInt;
  6374. begin
  6375.   Result := ((Key SHR (GIFCodeBits-8)) XOR Key) MOD HashSize;
  6376. end;
  6377.  
  6378. function NextHashKey(HKey: CodeInt): CodeInt;
  6379. var
  6380.   disp      : CodeInt;
  6381. begin
  6382.   (*
  6383.   ** secondary hash (after G. Knott)
  6384.   *)
  6385.   disp := HashSize - HKey;
  6386.   if (HKey = 0) then
  6387.     disp := 1;
  6388. //  disp := 13;     // disp should be prime relative to HashSize, but
  6389.             // it doesn't seem to matter here...
  6390.   dec(HKey, disp);
  6391.   if (HKey < 0) then
  6392.     inc(HKey, HashSize);
  6393.   Result := HKey;
  6394. end;
  6395.  
  6396.  
  6397. constructor THashTable.Create;
  6398. begin
  6399.   ASSERT(longInt($FFFFFFFF) = -1, 'TGIFImage implementation assumes $FFFFFFFF = -1');
  6400.  
  6401.   inherited Create;
  6402.   GetMem(HashTable, sizeof(THashArray));
  6403.   Clear;
  6404. {$ifdef DEBUG_HASHPERFORMANCE}
  6405.   CountLookupFound := 0;
  6406.   CountMissFound := 0;
  6407.   CountLookupNotFound := 0;
  6408.   CountMissNotFound := 0;
  6409. {$endif}
  6410. end;
  6411.  
  6412. destructor THashTable.Destroy;
  6413. begin
  6414. {$ifdef DEBUG_HASHPERFORMANCE}
  6415.   ShowMessage(
  6416.     Format('Found: %d  HitRate: %.2f',
  6417.       [CountLookupFound, (CountLookupFound+1)/(CountMissFound+1)])+#13+
  6418.     Format('Not found: %d  HitRate: %.2f',
  6419.       [CountLookupNotFound, (CountLookupNotFound+1)/(CountMissNotFound+1)]));
  6420. {$endif}
  6421.   FreeMem(HashTable);
  6422.   inherited Destroy;
  6423. end;
  6424.  
  6425. // Clear hash table and fill with empty slots (doh!)
  6426. procedure THashTable.Clear;
  6427. {$ifdef DEBUG_HASHFILLFACTOR}
  6428. var
  6429.   i         ,
  6430.   Count         : longInt;
  6431. {$endif}
  6432. begin
  6433. {$ifdef DEBUG_HASHFILLFACTOR}
  6434.   Count := 0;
  6435.   for i := 0 to HashSize-1 do
  6436.     if (HashTable[i] SHR GIFCodeBits <> HashEmpty) then
  6437.       inc(Count);
  6438.   ShowMessage(format('Size: %d, Filled: %d, Rate %.4f',
  6439.     [HashSize, Count, Count/HashSize]));
  6440. {$endif}
  6441.  
  6442.   FillChar(HashTable^, sizeof(THashArray), $FF);
  6443. end;
  6444.  
  6445. // Insert new key/value pair into hash table
  6446. procedure THashTable.Insert(Key: KeyInt; Code: CodeInt);
  6447. var
  6448.   HKey          : CodeInt;
  6449. begin
  6450.   // Create hash key from prefix string
  6451.   HKey := HashKey(Key);
  6452.  
  6453.   // Scan for empty slot
  6454.   // while (HashTable[HKey] SHR GIFCodeBits <> HashEmpty) do { Unoptimized }
  6455.   while (HashTable[HKey] AND (HashEmpty SHL GIFCodeBits) <> (HashEmpty SHL GIFCodeBits)) do { Optimized }
  6456.     HKey := NextHashKey(HKey);
  6457.   // Fill slot with key/value pair
  6458.   HashTable[HKey] := (Key SHL GIFCodeBits) OR (Code AND GIFCodeMask);
  6459. end;
  6460.  
  6461. // Search for key in hash table.
  6462. // Returns value if found or -1 if not
  6463. function THashTable.Lookup(Key: KeyInt): CodeInt;
  6464. var
  6465.   HKey          : CodeInt;
  6466.   HTKey         : KeyInt;
  6467. {$ifdef DEBUG_HASHPERFORMANCE}
  6468.   n         : LongInt;
  6469. {$endif}
  6470. begin
  6471.   // Create hash key from prefix string
  6472.   HKey := HashKey(Key);
  6473.  
  6474. {$ifdef DEBUG_HASHPERFORMANCE}
  6475.   n := 0;
  6476. {$endif}
  6477.   // Scan table for key
  6478.   // HTKey := HashTable[HKey] SHR GIFCodeBits; { Unoptimized }
  6479.   Key := Key SHL GIFCodeBits; { Optimized }
  6480.   HTKey := HashTable[HKey] AND (HashEmpty SHL GIFCodeBits); { Optimized }
  6481.   // while (HTKey <> HashEmpty) do { Unoptimized }
  6482.   while (HTKey <> HashEmpty SHL GIFCodeBits) do { Optimized }
  6483.   begin
  6484.     if (Key = HTKey) then
  6485.     begin
  6486.       // Extract and return value
  6487.       Result := HashTable[HKey] AND GIFCodeMask;
  6488. {$ifdef DEBUG_HASHPERFORMANCE}
  6489.       inc(CountLookupFound);
  6490.       inc(CountMissFound, n);
  6491. {$endif}
  6492.       exit;
  6493.     end;
  6494. {$ifdef DEBUG_HASHPERFORMANCE}
  6495.     inc(n);
  6496. {$endif}
  6497.     // Try next slot
  6498.     HKey := NextHashKey(HKey);
  6499.     // HTKey := HashTable[HKey] SHR GIFCodeBits; { Unoptimized }
  6500.     HTKey := HashTable[HKey] AND (HashEmpty SHL GIFCodeBits); { Optimized }
  6501.   end;
  6502.   // Found empty slot - key doesn't exist
  6503.   Result := -1;
  6504. {$ifdef DEBUG_HASHPERFORMANCE}
  6505.   inc(CountLookupNotFound);
  6506.   inc(CountMissNotFound, n);
  6507. {$endif}
  6508. end;
  6509.  
  6510. ////////////////////////////////////////////////////////////////////////////////
  6511. //      TGIFStream - Abstract GIF block stream
  6512. //
  6513. // Descendants from TGIFStream either reads or writes data in blocks
  6514. // of up to 255 bytes. These blocks are organized as a leading byte
  6515. // containing the number of bytes in the block (exclusing the count
  6516. // byte itself), followed by the data (up to 254 bytes of data).
  6517. ////////////////////////////////////////////////////////////////////////////////
  6518. type
  6519.   TGIFStream = class(TStream)
  6520.   private
  6521.     FOnWarning      : TGIFWarning;
  6522.     FStream     : TStream;
  6523.     FOnProgress     : TNotifyEvent;
  6524.     FBuffer     : array [BYTE] of AnsiChar;
  6525.     FBufferCount    : integer;
  6526.  
  6527.   protected
  6528.     constructor Create(Stream: TStream);
  6529.  
  6530.     function Read(var Buffer; Count: Longint): Longint; override;
  6531.     function Write(const Buffer; Count: Longint): Longint; override;
  6532.     function Seek(Offset: Longint; Origin: Word): Longint; override;
  6533.  
  6534.     procedure Progress(Sender: TObject); dynamic;
  6535.     property OnProgress: TNotifyEvent read FOnProgress write FOnProgress;
  6536.   public
  6537.     property Warning: TGIFWarning read FOnWarning write FOnWarning;
  6538.   end;
  6539.  
  6540. constructor TGIFStream.Create(Stream: TStream);
  6541. begin
  6542.   inherited Create;
  6543.   FStream := Stream;
  6544.   FBufferCount := 1; // Reserve first byte of buffer for length
  6545. end;
  6546.  
  6547. procedure TGIFStream.Progress(Sender: TObject);
  6548. begin
  6549.   if Assigned(FOnProgress) then
  6550.     FOnProgress(Sender);
  6551. end;
  6552.  
  6553. function TGIFStream.Write(const Buffer; Count: Longint): Longint;
  6554. begin
  6555.   raise Exception.Create(sInvalidStream);
  6556. end;
  6557.  
  6558. function TGIFStream.Read(var Buffer; Count: Longint): Longint;
  6559. begin
  6560.   raise Exception.Create(sInvalidStream);
  6561. end;
  6562.  
  6563. function TGIFStream.Seek(Offset: Longint; Origin: Word): Longint;
  6564. begin
  6565.   raise Exception.Create(sInvalidStream);
  6566. end;
  6567.  
  6568. ////////////////////////////////////////////////////////////////////////////////
  6569. //      TGIFReader - GIF block reader
  6570. ////////////////////////////////////////////////////////////////////////////////
  6571. type
  6572.   TGIFReader = class(TGIFStream)
  6573.   public
  6574.     constructor Create(Stream: TStream);
  6575.  
  6576.     function Read(var Buffer; Count: Longint): Longint; override;
  6577.   end;
  6578.  
  6579. constructor TGIFReader.Create(Stream: TStream);
  6580. begin
  6581.   inherited Create(Stream);
  6582.   FBufferCount := 0;
  6583. end;
  6584.  
  6585. function TGIFReader.Read(var Buffer; Count: Longint): Longint;
  6586. var
  6587.   n         : integer;
  6588.   Dst           : PAnsiChar;
  6589.   size          : BYTE;
  6590. begin
  6591.   Dst := @Buffer;
  6592.   Result := 0;
  6593.  
  6594.   while (Count > 0) do
  6595.   begin
  6596.     // Get data from buffer
  6597.     while (FBufferCount > 0) and (Count > 0) do
  6598.     begin
  6599.       if (FBufferCount > Count) then
  6600.         n := Count
  6601.       else
  6602.         n := FBufferCount;
  6603.       Move(FBuffer, Dst^, n);
  6604.       dec(FBufferCount, n);
  6605.       dec(Count, n);
  6606.       inc(Result, n);
  6607.       inc(Dst, n);
  6608.     end;
  6609.  
  6610.     // Refill buffer when it becomes empty
  6611.     if (FBufferCount <= 0) then
  6612.     begin
  6613.       FStream.Read(size, 1);
  6614.       { TODO -oanme -cImprovement : Should be handled as a warning instead of an error. }
  6615.       if (size >= 255) then
  6616.         Error('GIF block too large');
  6617.       FBufferCount := size;
  6618.       if (FBufferCount > 0) then
  6619.       begin
  6620.         n := FStream.Read(FBuffer, size);
  6621.         if (n = FBufferCount) then
  6622.         begin
  6623.           Warning(self, gsWarning, sOutOfData);
  6624.           break;
  6625.         end;
  6626.       end else
  6627.         break;
  6628.     end;
  6629.   end;
  6630. end;
  6631.  
  6632. ////////////////////////////////////////////////////////////////////////////////
  6633. //      TGIFWriter - GIF block writer
  6634. ////////////////////////////////////////////////////////////////////////////////
  6635. type
  6636.   TGIFWriter = class(TGIFStream)
  6637.   private
  6638.     FOutputDirty    : boolean;
  6639.  
  6640.   protected
  6641.     procedure FlushBuffer;
  6642.  
  6643.   public
  6644.     constructor Create(Stream: TStream);
  6645.     destructor Destroy; override;
  6646.  
  6647.     function Write(const Buffer; Count: Longint): Longint; override;
  6648.     function WriteByte(Value: BYTE): Longint;
  6649.   end;
  6650.  
  6651. constructor TGIFWriter.Create(Stream: TStream);
  6652. begin
  6653.   inherited Create(Stream);
  6654.   FBufferCount := 1; // Reserve first byte of buffer for length
  6655.   FOutputDirty := False;
  6656. end;
  6657.  
  6658. destructor TGIFWriter.Destroy;
  6659. begin
  6660.   inherited Destroy;
  6661.   if (FOutputDirty) then
  6662.     FlushBuffer;
  6663. end;
  6664.  
  6665. procedure TGIFWriter.FlushBuffer;
  6666. begin
  6667.   if (FBufferCount <= 0) then
  6668.     exit;
  6669.  
  6670.   FBuffer[0] := AnsiChar(FBufferCount-1); // Block size excluding the count
  6671.   FStream.WriteBuffer(FBuffer, FBufferCount);
  6672.   FBufferCount := 1; // Reserve first byte of buffer for length
  6673.   FOutputDirty := False;
  6674. end;
  6675.  
  6676. function TGIFWriter.Write(const Buffer; Count: Longint): Longint;
  6677. var
  6678.   n         : integer;
  6679.   Src           : PAnsiChar;
  6680. begin
  6681.   Result := Count;
  6682.   FOutputDirty := True;
  6683.   Src := @Buffer;
  6684.   while (Count > 0) do
  6685.   begin
  6686.     // Move data to the internal buffer in 255 byte chunks
  6687.     while (FBufferCount < sizeof(FBuffer)) and (Count > 0) do
  6688.     begin
  6689.       n := sizeof(FBuffer) - FBufferCount;
  6690.       if (n > Count) then
  6691.         n := Count;
  6692.       Move(Src^, FBuffer[FBufferCount], n);
  6693.       inc(Src, n);
  6694.       inc(FBufferCount, n);
  6695.       dec(Count, n);
  6696.     end;
  6697.  
  6698.     // Flush the buffer when it is full
  6699.     if (FBufferCount >= sizeof(FBuffer)) then
  6700.       FlushBuffer;
  6701.   end;
  6702. end;
  6703.  
  6704. function TGIFWriter.WriteByte(Value: BYTE): Longint;
  6705. begin
  6706.   Result := Write(Value, 1);
  6707. end;
  6708.  
  6709. ////////////////////////////////////////////////////////////////////////////////
  6710. //      TGIFEncoder - Abstract encoder
  6711. ////////////////////////////////////////////////////////////////////////////////
  6712. type
  6713.   TGIFEncoder = class(TObject)
  6714.   protected
  6715.     FOnWarning      : TGIFWarning;
  6716.     MaxColor        : integer;
  6717.     BitsPerPixel    : BYTE;     // Bits per pixel of image
  6718.     Stream      : TStream;  // Output stream
  6719.     Width       ,       // Width of image in pixels
  6720.     Height      : integer;  // height of image in pixels
  6721.     Interlace       : boolean;  // Interlace flag (True = interlaced image)
  6722.     Data        : PAnsiChar;    // Pointer to pixel data
  6723.     GIFStream       : TGIFWriter;   // Output buffer
  6724.  
  6725.     OutputBucket    : longInt;  // Output bit bucket
  6726.     OutputBits      : integer;  // Current # of bits in bucket
  6727.  
  6728.     ClearFlag       : Boolean;  // True if dictionary has just been cleared
  6729.     BitsPerCode     ,       // Current # of bits per code
  6730.     InitialBitsPerCode  : integer;  // Initial # of bits per code after
  6731.                     // dictionary has been cleared
  6732.     MaxCode     : CodeInt;  // maximum code, given BitsPerCode
  6733.     ClearCode       : CodeInt;  // Special output code to signal "Clear table"
  6734.     EOFCode     : CodeInt;  // Special output code to signal EOF
  6735.     BaseCode        : CodeInt;  // ...
  6736.  
  6737.     Pixel       : PAnsiChar;    // Pointer to current pixel
  6738.  
  6739.     cX          ,       // Current X counter (Width - X)
  6740.     Y           : integer;  // Current Y
  6741.     Pass        : integer;  // Interlace pass
  6742.  
  6743.     function MaxCodesFromBits(Bits: integer): CodeInt;
  6744.     procedure Output(Value: integer); virtual;
  6745.     procedure Clear; virtual;
  6746.     function BumpPixel: boolean;
  6747.     procedure DoCompress; virtual; abstract;
  6748.   public
  6749.     procedure Compress(AStream: TStream; ABitsPerPixel: integer;
  6750.       AWidth, AHeight: integer; AInterlace: boolean; AData: PAnsiChar; AMaxColor: integer);
  6751.     property Warning: TGIFWarning read FOnWarning write FOnWarning;
  6752.   end;
  6753.  
  6754. // Calculate the maximum number of codes that a given number of bits can represent
  6755. // MaxCodes := (1^bits)-1
  6756. function TGIFEncoder.MaxCodesFromBits(Bits: integer): CodeInt;
  6757. begin
  6758.   Result := (CodeInt(1) SHL Bits) - 1;
  6759. end;
  6760.  
  6761. // Stuff bits (variable sized codes) into a buffer and output them
  6762. // a byte at a time
  6763. procedure TGIFEncoder.Output(Value: integer);
  6764. const
  6765.   BitBucketMask: array[0..16] of longInt =
  6766.     ($0000,
  6767.      $0001, $0003, $0007, $000F,
  6768.      $001F, $003F, $007F, $00FF,
  6769.      $01FF, $03FF, $07FF, $0FFF,
  6770.      $1FFF, $3FFF, $7FFF, $FFFF);
  6771. begin
  6772.   if (OutputBits > 0) then
  6773.     OutputBucket :=
  6774.       (OutputBucket AND BitBucketMask[OutputBits]) OR (longInt(Value) SHL OutputBits)
  6775.   else
  6776.     OutputBucket := Value;
  6777.  
  6778.   inc(OutputBits, BitsPerCode);
  6779.  
  6780.   while (OutputBits >= 8) do
  6781.   begin
  6782.     GIFStream.WriteByte(OutputBucket AND $FF);
  6783.     OutputBucket := OutputBucket SHR 8;
  6784.     dec(OutputBits, 8);
  6785.   end;
  6786.  
  6787.   if (Value = EOFCode) then
  6788.   begin
  6789.     // At EOF, write the rest of the buffer.
  6790.     while (OutputBits > 0) do
  6791.     begin
  6792.       GIFStream.WriteByte(OutputBucket AND $FF);
  6793.       OutputBucket := OutputBucket SHR 8;
  6794.       dec(OutputBits, 8);
  6795.     end;
  6796.   end;
  6797. end;
  6798.  
  6799. procedure TGIFEncoder.Clear;
  6800. begin
  6801.   // just_cleared = 1;
  6802.   ClearFlag := TRUE;
  6803.   Output(ClearCode);
  6804. end;
  6805.  
  6806. // Bump (X,Y) and data pointer to point to the next pixel
  6807. function TGIFEncoder.BumpPixel: boolean;
  6808. begin
  6809.   // Bump the current X position
  6810.   dec(cX);
  6811.  
  6812.   // If we are at the end of a scan line, set cX back to the beginning
  6813.   // If we are interlaced, bump Y to the appropriate spot, otherwise,
  6814.   // just increment it.
  6815.   if (cX <= 0) then
  6816.   begin
  6817.  
  6818.     if not(Interlace) then
  6819.     begin
  6820.       // Done - no more data
  6821.       Result := False;
  6822.       exit;
  6823.     end;
  6824.  
  6825.     cX := Width;
  6826.     case (Pass) of
  6827.       0:
  6828.         begin
  6829.           inc(Y, 8);
  6830.           if (Y >= Height) then
  6831.           begin
  6832.             inc(Pass);
  6833.             Y := 4;
  6834.           end;
  6835.         end;
  6836.       1:
  6837.         begin
  6838.           inc(Y, 8);
  6839.           if (Y >= Height) then
  6840.           begin
  6841.             inc(Pass);
  6842.             Y := 2;
  6843.           end;
  6844.         end;
  6845.       2:
  6846.         begin
  6847.           inc(Y, 4);
  6848.           if (Y >= Height) then
  6849.           begin
  6850.             inc(Pass);
  6851.             Y := 1;
  6852.           end;
  6853.         end;
  6854.       3:
  6855.         inc(Y, 2);
  6856.     end;
  6857.  
  6858.     if (Y >= height) then
  6859.     begin
  6860.       // Done - No more data
  6861.       Result := False;
  6862.       exit;
  6863.     end;
  6864.     Pixel := Data + (Y * Width);
  6865.   end;
  6866.   Result := True;
  6867. end;
  6868.  
  6869.  
  6870. procedure TGIFEncoder.Compress(AStream: TStream; ABitsPerPixel: integer;
  6871.   AWidth, AHeight: integer; AInterlace: boolean; AData: PAnsiChar; AMaxColor: integer);
  6872. const
  6873.   EndBlockByte      = $00;          // End of block marker
  6874. {$ifdef DEBUG_COMPRESSPERFORMANCE}
  6875. var
  6876.   TimeStartCompress ,
  6877.   TimeStopCompress  : DWORD;
  6878. {$endif}
  6879. begin
  6880.   MaxColor := AMaxColor;
  6881.   Stream := AStream;
  6882.   BitsPerPixel := ABitsPerPixel;
  6883.   Width := AWidth;
  6884.   Height := AHeight;
  6885.   Interlace := AInterlace;
  6886.   Data := AData;
  6887.  
  6888.   if (BitsPerPixel <= 1) then
  6889.     BitsPerPixel := 2;
  6890.  
  6891.   InitialBitsPerCode := BitsPerPixel + 1;
  6892.   Stream.Write(BitsPerPixel, 1);
  6893.  
  6894.   // out_bits_init = init_bits;
  6895.   BitsPerCode := InitialBitsPerCode;
  6896.   MaxCode := MaxCodesFromBits(BitsPerCode);
  6897.  
  6898.   ClearCode := (1 SHL (InitialBitsPerCode - 1));
  6899.   EOFCode := ClearCode + 1;
  6900.   BaseCode := EOFCode + 1;
  6901.  
  6902.   // Clear bit bucket
  6903.   OutputBucket := 0;
  6904.   OutputBits  := 0;
  6905.  
  6906.   // Reset pixel counter
  6907.   if (Interlace) then
  6908.     cX := Width
  6909.   else
  6910.     cX := Width*Height;
  6911.   // Reset row counter
  6912.   Y := 0;
  6913.   Pass := 0;
  6914.  
  6915.   GIFStream := TGIFWriter.Create(AStream);
  6916.   try
  6917.     GIFStream.Warning := Warning;
  6918.     if (Data <> nil) and (Height > 0) and (Width > 0) then
  6919.     begin
  6920. {$ifdef DEBUG_COMPRESSPERFORMANCE}
  6921.       TimeStartCompress := timeGetTime;
  6922. {$endif}
  6923.  
  6924.       // Call compress implementation
  6925.       DoCompress;
  6926.  
  6927. {$ifdef DEBUG_COMPRESSPERFORMANCE}
  6928.       TimeStopCompress := timeGetTime;
  6929.       ShowMessage(format('Compressed %d pixels in %d mS, Rate %d pixels/mS',
  6930.         [Height*Width, TimeStopCompress-TimeStartCompress,
  6931.         DWORD(Height*Width) DIV (TimeStopCompress-TimeStartCompress+1)]));
  6932. {$endif}
  6933.       // Output the final code.
  6934.       Output(EOFCode);
  6935.     end else
  6936.       // Output the final code (and nothing else).
  6937.       TGIFEncoder(self).Output(EOFCode);
  6938.   finally
  6939.     GIFStream.Free;
  6940.   end;
  6941.  
  6942.   WriteByte(Stream, EndBlockByte);
  6943. end;
  6944.  
  6945. ////////////////////////////////////////////////////////////////////////////////
  6946. //      TRLEEncoder - RLE encoder
  6947. ////////////////////////////////////////////////////////////////////////////////
  6948. type
  6949.   TRLEEncoder = class(TGIFEncoder)
  6950.   private
  6951.     MaxCodes        : integer;
  6952.     OutBumpInit     ,
  6953.     OutClearInit    : integer;
  6954.     Prefix      : integer;  // Current run color
  6955.     RunLengthTableMax   ,
  6956.     RunLengthTablePixel ,
  6957.     OutCount        ,
  6958.     OutClear        ,
  6959.     OutBump     : integer;
  6960.   protected
  6961.     function ComputeTriangleCount(count: integer; nrepcodes: integer): integer;
  6962.     procedure MaxOutClear;
  6963.     procedure ResetOutClear;
  6964.     procedure FlushFromClear(Count: integer);
  6965.     procedure FlushClearOrRepeat(Count: integer);
  6966.     procedure FlushWithTable(Count: integer);
  6967.     procedure Flush(RunLengthCount: integer);
  6968.     procedure OutputPlain(Value: integer);
  6969.     procedure Clear; override;
  6970.     procedure DoCompress; override;
  6971.   end;
  6972.  
  6973.  
  6974. procedure TRLEEncoder.Clear;
  6975. begin
  6976.   OutBump := OutBumpInit;
  6977.   OutClear := OutClearInit;
  6978.   OutCount := 0;
  6979.   RunLengthTableMax := 0;
  6980.  
  6981.   inherited Clear;
  6982.  
  6983.   BitsPerCode := InitialBitsPerCode;
  6984. end;
  6985.  
  6986. procedure TRLEEncoder.OutputPlain(Value: integer);
  6987. begin
  6988.   ClearFlag := False;
  6989.   Output(Value);
  6990.   inc(OutCount);
  6991.  
  6992.   if (OutCount >= OutBump) then
  6993.   begin
  6994.     inc(BitsPerCode);
  6995.     inc(OutBump, 1 SHL (BitsPerCode - 1));
  6996.   end;
  6997.  
  6998.   if (OutCount >= OutClear) then
  6999.     Clear;
  7000. end;
  7001.  
  7002. function TRLEEncoder.ComputeTriangleCount(count: integer; nrepcodes: integer): integer;
  7003. var
  7004.   PerRepeat     : integer;
  7005.   n         : integer;
  7006.  
  7007.   function iSqrt(x: integer): integer;
  7008.   var
  7009.     r, v        : integer;
  7010.   begin
  7011.     if (x < 2) then
  7012.     begin
  7013.       Result := x;
  7014.       exit;
  7015.     end else
  7016.     begin
  7017.       v := x;
  7018.       r := 1;
  7019.       while (v > 0) do
  7020.       begin
  7021.         v := v DIV 4;
  7022.         r := r * 2;
  7023.       end;
  7024.     end;
  7025.  
  7026.     while (True) do
  7027.     begin
  7028.       v := ((x DIV r) + r) DIV 2;
  7029.       if ((v = r) or (v = r+1)) then
  7030.       begin
  7031.         Result := r;
  7032.         exit;
  7033.       end;
  7034.       r := v;
  7035.     end;
  7036.   end;
  7037.  
  7038. begin
  7039.   Result := 0;
  7040.   PerRepeat := (nrepcodes * (nrepcodes+1)) DIV 2;
  7041.  
  7042.   while (Count >= PerRepeat) do
  7043.   begin
  7044.     inc(Result, nrepcodes);
  7045.     dec(Count, PerRepeat);
  7046.   end;
  7047.  
  7048.   if (Count > 0) then
  7049.   begin
  7050.     n := iSqrt(Count);
  7051.     while ((n * (n+1)) >= 2*Count) do
  7052.       dec(n);
  7053.     while ((n * (n+1)) < 2*Count) do
  7054.       inc(n);
  7055.     inc(Result, n);
  7056.   end;
  7057. end;
  7058.  
  7059. procedure TRLEEncoder.MaxOutClear;
  7060. begin
  7061.   OutClear := MaxCodes;
  7062. end;
  7063.  
  7064. procedure TRLEEncoder.ResetOutClear;
  7065. begin
  7066.   OutClear := OutClearInit;
  7067.   if (OutCount >= OutClear) then
  7068.     Clear;
  7069. end;
  7070.  
  7071. procedure TRLEEncoder.FlushFromClear(Count: integer);
  7072. var
  7073.   n         : integer;
  7074. begin
  7075.   MaxOutClear;
  7076.   RunLengthTablePixel := Prefix;
  7077.   n := 1;
  7078.   while (Count > 0) do
  7079.   begin
  7080.     if (n = 1) then
  7081.     begin
  7082.       RunLengthTableMax := 1;
  7083.       OutputPlain(Prefix);
  7084.       dec(Count);
  7085.     end else
  7086.     if (Count >= n) then
  7087.     begin
  7088.       RunLengthTableMax := n;
  7089.       OutputPlain(BaseCode + n - 2);
  7090.       dec(Count, n);
  7091.     end else
  7092.     if (Count = 1) then
  7093.     begin
  7094.       inc(RunLengthTableMax);
  7095.       OutputPlain(Prefix);
  7096.       break;
  7097.     end else
  7098.     begin
  7099.       inc(RunLengthTableMax);
  7100.       OutputPlain(BaseCode + Count - 2);
  7101.       break;
  7102.     end;
  7103.  
  7104.     if (OutCount = 0) then
  7105.       n := 1
  7106.     else
  7107.       inc(n);
  7108.   end;
  7109.   ResetOutClear;
  7110. end;
  7111.  
  7112. procedure TRLEEncoder.FlushClearOrRepeat(Count: integer);
  7113. var
  7114.   WithClear     : integer;
  7115. begin
  7116.   WithClear := 1 + ComputeTriangleCount(Count, MaxCodes);
  7117.  
  7118.   if (WithClear < Count) then
  7119.   begin
  7120.     Clear;
  7121.     FlushFromClear(Count);
  7122.   end else
  7123.     while (Count > 0) do
  7124.     begin
  7125.       OutputPlain(Prefix);
  7126.       dec(Count);
  7127.     end;
  7128. end;
  7129.  
  7130. procedure TRLEEncoder.FlushWithTable(Count: integer);
  7131. var
  7132.   RepeatMax     ,
  7133.   RepeatLeft        ,
  7134.   LeftOver      : integer;
  7135. begin
  7136.   RepeatMax := Count DIV RunLengthTableMax;
  7137.   LeftOver := Count MOD RunLengthTableMax;
  7138.   if (LeftOver <> 0) then
  7139.     RepeatLeft := 1
  7140.   else
  7141.     RepeatLeft := 0;
  7142.  
  7143.   if (OutCount + RepeatMax + RepeatLeft > MaxCodes) then
  7144.   begin
  7145.     RepeatMax := MaxCodes - OutCount;
  7146.     LeftOver := Count - (RepeatMax * RunLengthTableMax);
  7147.     RepeatLeft := 1 + ComputeTriangleCount(LeftOver, MaxCodes);
  7148.   end;
  7149.  
  7150.   if (1 + ComputeTriangleCount(Count, MaxCodes) < RepeatMax + RepeatLeft) then
  7151.   begin
  7152.     Clear;
  7153.     FlushFromClear(Count);
  7154.     exit;
  7155.   end;
  7156.   MaxOutClear;
  7157.  
  7158.   while (RepeatMax > 0) do
  7159.   begin
  7160.     OutputPlain(BaseCode + RunLengthTableMax-2);
  7161.     dec(RepeatMax);
  7162.   end;
  7163.  
  7164.   if (LeftOver > 0) then
  7165.   begin
  7166.     if (ClearFlag) then
  7167.       FlushFromClear(LeftOver)
  7168.     else if (LeftOver = 1) then
  7169.       OutputPlain(Prefix)
  7170.     else
  7171.       OutputPlain(BaseCode +  LeftOver - 2);
  7172.   end;
  7173.   ResetOutClear;
  7174. end;
  7175.  
  7176. procedure TRLEEncoder.Flush(RunLengthCount: integer);
  7177. begin
  7178.   if (RunLengthCount = 1) then
  7179.   begin
  7180.     OutputPlain(Prefix);
  7181.     exit;
  7182.   end;
  7183.  
  7184.   if (ClearFlag) then
  7185.     FlushFromClear(RunLengthCount)
  7186.   else if ((RunLengthTableMax < 2) or (RunLengthTablePixel <> Prefix)) then
  7187.     FlushClearOrRepeat(RunLengthCount)
  7188.   else
  7189.     FlushWithTable(RunLengthCount);
  7190. end;
  7191.  
  7192. procedure TRLEEncoder.DoCompress;
  7193. var
  7194.   Color         : CodeInt;
  7195.   RunLengthCount    : integer;
  7196.  
  7197. begin
  7198.   OutBumpInit := ClearCode - 1;
  7199.  
  7200.   // For images with a lot of runs, making OutClearInit larger will
  7201.   // give better compression.
  7202.   if (BitsPerPixel <= 3) then
  7203.     OutClearInit := 9
  7204.   else
  7205.     OutClearInit := OutBumpInit - 1;
  7206.  
  7207.   // max_ocodes = (1 << GIFBITS) - ((1 << (out_bits_init - 1)) + 3);
  7208.   // <=> MaxCodes := (1 SHL GIFCodeBits) - ((1 SHL (BitsPerCode - 1)) + 3);
  7209.   // <=> MaxCodes := (1 SHL GIFCodeBits) - ((1 SHL (InitialBitsPerCode - 1)) + 3);
  7210.   // <=> MaxCodes := (1 SHL GIFCodeBits) - (ClearCode + 3);
  7211.   // <=> MaxCodes := (1 SHL GIFCodeBits) - (EOFCode + 2);
  7212.   // <=> MaxCodes := (1 SHL GIFCodeBits) - (BaseCode + 1);
  7213.   // <=> MaxCodes := MaxCodesFromBits(GIFCodeBits) - BaseCode;
  7214.   MaxCodes := MaxCodesFromBits(GIFCodeBits) - BaseCode;
  7215.  
  7216.   Clear;
  7217.   RunLengthCount := 0;
  7218.  
  7219.   Pixel := Data;
  7220.   Prefix := -1; // Dummy value to make Color <> Prefix
  7221.   repeat
  7222.     // Fetch the next pixel
  7223.     Color := CodeInt(Pixel^);
  7224.     inc(Pixel);
  7225.  
  7226.     if (Color >= MaxColor) then
  7227.       Error(sInvalidColor);
  7228.  
  7229.     if (RunLengthCount > 0) and (Color <> Prefix) then
  7230.     begin
  7231.       // End of current run
  7232.       Flush(RunLengthCount);
  7233.       RunLengthCount := 0;
  7234.     end;
  7235.  
  7236.     if (Color = Prefix) then
  7237.       // Increment run length
  7238.       inc(RunLengthCount)
  7239.     else
  7240.     begin
  7241.       // Start new run
  7242.       Prefix := Color;
  7243.       RunLengthCount := 1;
  7244.     end;
  7245.   until not(BumpPixel);
  7246.   Flush(RunLengthCount);
  7247. end;
  7248.  
  7249. ////////////////////////////////////////////////////////////////////////////////
  7250. //      TLZWEncoder - LZW encoder
  7251. ////////////////////////////////////////////////////////////////////////////////
  7252. const
  7253.   TableMaxMaxCode   = (1 SHL GIFCodeBits);  //
  7254.   TableMaxFill      = TableMaxMaxCode-1;    // Clear table when it fills to
  7255.                         // this point.
  7256.                         // Note: Must be <= GIFCodeMax
  7257. type
  7258.   TLZWEncoder = class(TGIFEncoder)
  7259.   private
  7260.     Prefix      : CodeInt;  // Current run color
  7261.     FreeEntry       : CodeInt;  // next unused code in table
  7262.     HashTable       : THashTable;
  7263.   protected
  7264.     procedure Output(Value: integer); override;
  7265.     procedure Clear; override;
  7266.     procedure DoCompress; override;
  7267.   end;
  7268.  
  7269.  
  7270. procedure TLZWEncoder.Output(Value: integer);
  7271. begin
  7272.   inherited Output(Value);
  7273.  
  7274.   // If the next entry is going to be too big for the code size,
  7275.   // then increase it, if possible.
  7276.   if (FreeEntry > MaxCode) or (ClearFlag) then
  7277.   begin
  7278.     if (ClearFlag) then
  7279.     begin
  7280.       BitsPerCode := InitialBitsPerCode;
  7281.       MaxCode := MaxCodesFromBits(BitsPerCode);
  7282.       ClearFlag := False;
  7283.     end else
  7284.     begin
  7285.       inc(BitsPerCode);
  7286.       if (BitsPerCode = GIFCodeBits) then
  7287.         MaxCode := TableMaxMaxCode
  7288.       else
  7289.         MaxCode := MaxCodesFromBits(BitsPerCode);
  7290.     end;
  7291.   end;
  7292. end;
  7293.  
  7294. procedure TLZWEncoder.Clear;
  7295. begin
  7296.   inherited Clear;
  7297.   HashTable.Clear;
  7298.   FreeEntry := ClearCode + 2;
  7299. end;
  7300.  
  7301.  
  7302. procedure TLZWEncoder.DoCompress;
  7303. var
  7304.   Color         : AnsiChar;
  7305.   NewKey        : KeyInt;
  7306.   NewCode       : CodeInt;
  7307.  
  7308. begin
  7309.   HashTable := THashTable.Create;
  7310.   try
  7311.     // clear hash table and sync decoder
  7312.     Clear;
  7313.  
  7314.     Pixel := Data;
  7315.     Prefix := CodeInt(Pixel^);
  7316.     inc(Pixel);
  7317.     if (Prefix >= MaxColor) then
  7318.       Error(sInvalidColor);
  7319.     while (BumpPixel) do
  7320.     begin
  7321.       // Fetch the next pixel
  7322.       Color := Pixel^;
  7323.       inc(Pixel);
  7324.       if (ord(Color) >= MaxColor) then
  7325.         Error(sInvalidColor);
  7326.  
  7327.       // Append Postfix to Prefix and lookup in table...
  7328.       NewKey := (KeyInt(Prefix) SHL 8) OR ord(Color);
  7329.       NewCode := HashTable.Lookup(NewKey);
  7330.       if (NewCode >= 0) then
  7331.       begin
  7332.         // ...if found, get next pixel
  7333.         Prefix := NewCode;
  7334.         continue;
  7335.       end;
  7336.  
  7337.       // ...if not found, output and start over
  7338.       Output(Prefix);
  7339.       Prefix := CodeInt(Color);
  7340.  
  7341.       if (FreeEntry < TableMaxFill) then
  7342.       begin
  7343.         HashTable.Insert(NewKey, FreeEntry);
  7344.         inc(FreeEntry);
  7345.       end else
  7346.         Clear;
  7347.     end;
  7348.     Output(Prefix);
  7349.   finally
  7350.     HashTable.Free;
  7351.   end;
  7352. end;
  7353.  
  7354. ////////////////////////////////////////////////////////////////////////////////
  7355. //
  7356. //          TGIFSubImage
  7357. //
  7358. ////////////////////////////////////////////////////////////////////////////////
  7359.  
  7360. /////////////////////////////////////////////////////////////////////////
  7361. //      TGIFSubImage.Compress
  7362. /////////////////////////////////////////////////////////////////////////
  7363. procedure TGIFSubImage.Compress(Stream: TStream);
  7364. var
  7365.   Encoder       : TGIFEncoder;
  7366.   BitsPerPixel      : BYTE;
  7367.   MaxColors     : integer;
  7368. begin
  7369.   if (ColorMap.Count > 0) then
  7370.   begin
  7371.     MaxColors := ColorMap.Count;
  7372.     BitsPerPixel := ColorMap.BitsPerPixel
  7373.   end else
  7374.   begin
  7375.     BitsPerPixel := Image.BitsPerPixel;
  7376.     MaxColors := 1 SHL BitsPerPixel;
  7377.   end;
  7378.  
  7379.   // Create a RLE or LZW GIF encoder
  7380.   if (Image.Compression = gcRLE) then
  7381.     Encoder := TRLEEncoder.Create
  7382.   else
  7383.     Encoder := TLZWEncoder.Create;
  7384.   try
  7385.     Encoder.Warning := Image.Warning;
  7386.     Encoder.Compress(Stream, BitsPerPixel, Width, Height, Interlaced, FData, MaxColors);
  7387.   finally
  7388.     Encoder.Free;
  7389.   end;
  7390. end;
  7391.  
  7392. function TGIFExtensionList.GetExtension(Index: Integer): TGIFExtension;
  7393. begin
  7394.   Result := TGIFExtension(Items[Index]);
  7395. end;
  7396.  
  7397. procedure TGIFExtensionList.SetExtension(Index: Integer; Extension: TGIFExtension);
  7398. begin
  7399.   Items[Index] := Extension;
  7400. end;
  7401.  
  7402. procedure TGIFExtensionList.LoadFromStream(Stream: TStream; Parent: TObject);
  7403. var
  7404.   b         : BYTE;
  7405.   Extension     : TGIFExtension;
  7406.   ExtensionClass    : TGIFExtensionClass;
  7407. begin
  7408.   // Peek ahead to determine block type
  7409.   if (Stream.Read(b, 1) <> 1) then
  7410.     exit;
  7411.   while not(b in [bsTrailer, bsImageDescriptor]) do
  7412.   begin
  7413.     if (b = bsExtensionIntroducer) then
  7414.     begin
  7415.       ExtensionClass := TGIFExtension.FindExtension(Stream);
  7416.       if (ExtensionClass = nil) then
  7417.         Error(sUnknownExtension);
  7418.       Stream.Seek(-1, soFromCurrent);
  7419.       Extension := ExtensionClass.Create(Parent as TGIFSubImage);
  7420.       try
  7421.         Extension.LoadFromStream(Stream);
  7422.         Add(Extension);
  7423.       except
  7424.         Extension.Free;
  7425.         raise;
  7426.       end;
  7427.     end else
  7428.     begin
  7429.       Warning(gsWarning, sBadExtensionLabel);
  7430.       break;
  7431.     end;
  7432.     if (Stream.Read(b, 1) <> 1) then
  7433.       exit;
  7434.   end;
  7435.   Stream.Seek(-1, soFromCurrent);
  7436. end;
  7437.  
  7438. const
  7439.   { image descriptor bit masks }
  7440.   idLocalColorTable = $80;    { set if a local color table follows }
  7441.   idInterlaced      = $40;    { set if image is interlaced }
  7442.   idSort        = $20;    { set if color table is sorted }
  7443.   idReserved        = $0C;    { reserved - must be set to $00 }
  7444.   idColorTableSize  = $07;    { size of color table as above }
  7445.  
  7446. constructor TGIFSubImage.Create(GIFImage: TGIFImage);
  7447. begin
  7448.   inherited Create(GIFImage);
  7449.   FExtensions := TGIFExtensionList.Create(GIFImage);
  7450.   FColorMap := TGIFLocalColorMap.Create(self);
  7451.   FImageDescriptor.Separator := bsImageDescriptor;
  7452.   FImageDescriptor.Left := 0;
  7453.   FImageDescriptor.Top := 0;
  7454.   FImageDescriptor.Width := 0;
  7455.   FImageDescriptor.Height := 0;
  7456.   FImageDescriptor.PackedFields := 0;
  7457.   FBitmap := nil;
  7458.   FMask := 0;
  7459.   FNeedMask := True;
  7460.   FData := nil;
  7461.   FDataSize := 0;
  7462.   FTransparent := False;
  7463.   FGCE := nil;
  7464.   // Remember to synchronize with TGIFSubImage.Clear
  7465. end;
  7466.  
  7467. destructor TGIFSubImage.Destroy;
  7468. begin
  7469.   if (FGIFImage <> nil) then
  7470.     FGIFImage.Images.Remove(self);
  7471.   Clear;
  7472.   FExtensions.Free;
  7473.   FColorMap.Free;
  7474.   if (FLocalPalette <> 0) then
  7475.     DeleteObject(FLocalPalette);
  7476.   inherited Destroy;
  7477. end;
  7478.  
  7479. procedure TGIFSubImage.Clear;
  7480. begin
  7481.   FExtensions.Clear;
  7482.   FColorMap.Clear;
  7483.   FreeImage;
  7484.   Height := 0;
  7485.   Width := 0;
  7486.   FTransparent := False;
  7487.   FGCE := nil;
  7488.   FreeBitmap;
  7489.   FreeMask;
  7490.   // Remember to synchronize with TGIFSubImage.Create
  7491. end;
  7492.  
  7493. function TGIFSubImage.GetEmpty: Boolean;
  7494. begin
  7495.   Result := ((FData = nil) or (FDataSize = 0) or (Height = 0) or (Width = 0));
  7496. end;
  7497.  
  7498. function TGIFSubImage.GetPalette: HPALETTE;
  7499. begin
  7500.   if (FBitmap <> nil) and (FBitmap.Palette <> 0) then
  7501.     // Use bitmaps own palette if possible
  7502.     Result := FBitmap.Palette
  7503.   else if (FLocalPalette <> 0) then
  7504.     // Or a previously exported local palette
  7505.     Result := FLocalPalette
  7506.   else if (Image.DoDither) then
  7507.   begin
  7508.     // or create a new dither palette
  7509.     FLocalPalette := WebPalette;
  7510.     Result := FLocalPalette;
  7511.   end
  7512.   else if (ColorMap.Count > 0) then
  7513.   begin
  7514.     // or create a new if first time
  7515.     FLocalPalette := ColorMap.ExportPalette;
  7516.     Result := FLocalPalette;
  7517.   end else
  7518.     // Use global palette if everything else fails
  7519.     Result := Image.Palette;
  7520. end;
  7521.  
  7522. procedure TGIFSubImage.SetPalette(Value: HPalette);
  7523. var
  7524.   NeedNewBitmap     : boolean;
  7525. begin
  7526.   if (Value <> FLocalPalette) then
  7527.   begin
  7528.     // Zap old palette
  7529.     if (FLocalPalette <> 0) then
  7530.       DeleteObject(FLocalPalette);
  7531.     // Zap bitmap unless new palette is same as bitmaps own
  7532.     NeedNewBitmap := (FBitmap <> nil) and (Value <> FBitmap.Palette);
  7533.  
  7534.     // Use new palette
  7535.     FLocalPalette := Value;
  7536.     if (NeedNewBitmap) then
  7537.     begin
  7538.       // Need to create new bitmap and repaint
  7539.       FreeBitmap;
  7540.       Image.PaletteModified := True;
  7541.       Image.Changed(Self);
  7542.     end;
  7543.   end;
  7544. end;
  7545.  
  7546. procedure TGIFSubImage.NeedImage;
  7547. begin
  7548.   if (FData = nil) then
  7549.     NewImage;
  7550.   if (FDataSize = 0) then
  7551.     Error(sEmptyImage);
  7552. end;
  7553.  
  7554. procedure TGIFSubImage.NewImage;
  7555. var
  7556.   NewSize       : longInt;
  7557. begin
  7558.   FreeImage;
  7559.   NewSize := Height * Width;
  7560.   if (NewSize <> 0) then
  7561.   begin
  7562.     GetMem(FData, NewSize);
  7563.     FillChar(FData^, NewSize, 0);
  7564.   end else
  7565.     FData := nil;
  7566.   FDataSize := NewSize;
  7567. end;
  7568.  
  7569. procedure TGIFSubImage.FreeImage;
  7570. begin
  7571.   if (FData <> nil) then
  7572.     FreeMem(FData);
  7573.   FDataSize := 0;
  7574.   FData := nil;
  7575. end;
  7576.  
  7577. function TGIFSubImage.GetHasBitmap: boolean;
  7578. begin
  7579.   Result := (FBitmap <> nil);
  7580. end;
  7581.  
  7582. procedure TGIFSubImage.SetHasBitmap(Value: boolean);
  7583. begin
  7584.   if (Value <> (FBitmap <> nil)) then
  7585.   begin
  7586.     if (Value) then
  7587.       Bitmap // Referencing Bitmap will automatically create it
  7588.     else
  7589.       FreeBitmap;
  7590.   end;
  7591. end;
  7592.  
  7593. procedure TGIFSubImage.NewBitmap;
  7594. begin
  7595.   FreeBitmap;
  7596.   FBitmap := TBitmap.Create;
  7597. end;
  7598.  
  7599. procedure TGIFSubImage.FreeBitmap;
  7600. begin
  7601.   if (FBitmap <> nil) then
  7602.   begin
  7603.     FBitmap.Free;
  7604.     FBitmap := nil;
  7605.   end;
  7606. end;
  7607.  
  7608. procedure TGIFSubImage.FreeMask;
  7609. begin
  7610.   if (FMask <> 0) then
  7611.   begin
  7612.     DeleteObject(FMask);
  7613.     FMask := 0;
  7614.   end;
  7615.   FNeedMask := True;
  7616. end;
  7617.  
  7618. function TGIFSubImage.HasMask: boolean;
  7619. begin
  7620.   if (FNeedMask) and (Transparent) then
  7621.   begin
  7622.     // Zap old bitmap
  7623.     FreeBitmap;
  7624.     // Create new bitmap and mask
  7625.     GetBitmap;
  7626.   end;
  7627.   Result := (FMask <> 0);
  7628. end;
  7629.  
  7630. function TGIFSubImage.GetBounds(Index: integer): WORD;
  7631. begin
  7632.   case (Index) of
  7633.     1: Result := FImageDescriptor.Left;
  7634.     2: Result := FImageDescriptor.Top;
  7635.     3: Result := FImageDescriptor.Width;
  7636.     4: Result := FImageDescriptor.Height;
  7637.   else
  7638.     Result := 0; // To avoid compiler warnings
  7639.   end;
  7640. end;
  7641.  
  7642. procedure TGIFSubImage.SetBounds(Index: integer; Value: WORD);
  7643. begin
  7644.   case (Index) of
  7645.     1: DoSetBounds(Value, FImageDescriptor.Top, FImageDescriptor.Width, FImageDescriptor.Height);
  7646.     2: DoSetBounds(FImageDescriptor.Left, Value, FImageDescriptor.Width, FImageDescriptor.Height);
  7647.     3: DoSetBounds(FImageDescriptor.Left, FImageDescriptor.Top, Value, FImageDescriptor.Height);
  7648.     4: DoSetBounds(FImageDescriptor.Left, FImageDescriptor.Top, FImageDescriptor.Width, Value);
  7649.   end;
  7650. end;
  7651.  
  7652. {$IFOPT R+}
  7653.   {$DEFINE R_PLUS}
  7654.   {$RANGECHECKS OFF}
  7655. {$ENDIF}
  7656. function TGIFSubImage.DoGetDitherBitmap: TBitmap;
  7657. var
  7658.   ColorLookup       : TColorLookup;
  7659.   Ditherer      : TDitherEngine;
  7660.   DIBResult     : TDIB;
  7661.   Src           : PAnsiChar;
  7662.   Dst           : PAnsiChar;
  7663.  
  7664.   Row           : integer;
  7665.   Color         : TGIFColor;
  7666.   ColMap        : PColorMap;
  7667.   Index         : byte;
  7668.   TransparentIndex  : byte;
  7669.   IsTransparent     : boolean;
  7670.   WasTransparent    : boolean;
  7671.   MappedTransparentIndex: AnsiChar;
  7672.  
  7673.   MaskBits      : PAnsiChar;
  7674.   MaskDest      : PAnsiChar;
  7675.   MaskRow       : PAnsiChar;
  7676.   MaskRowWidth      ,
  7677.   MaskRowBitWidth   : integer;
  7678.   Bit           ,
  7679.   RightBit      : BYTE;
  7680.  
  7681. begin
  7682.   Result := TBitmap.Create;
  7683.   try
  7684.  
  7685. {$IFNDEF VER9x}
  7686.     if (Width*Height > BitmapAllocationThreshold) then
  7687.       SetPixelFormat(Result, pf1bit); // To reduce resource consumption of resize
  7688. {$ENDIF}
  7689.  
  7690.     if (Empty) then
  7691.     begin
  7692.       // Set bitmap width and height
  7693.       Result.Width := Width;
  7694.       Result.Height := Height;
  7695.  
  7696.       // Build and copy palette to bitmap
  7697.       Result.Palette := CopyPalette(Palette);
  7698.  
  7699.       exit;
  7700.     end;
  7701.  
  7702.     ColorLookup := nil;
  7703.     Ditherer := nil;
  7704.     DIBResult := nil;
  7705.     try // Protect above resources
  7706.       ColorLookup := TNetscapeColorLookup.Create(Palette);
  7707.       Ditherer := TFloydSteinbergDitherer.Create(Width, ColorLookup);
  7708.       // Get DIB buffer for scanline operations
  7709.       // It is assumed that the source palette is the 216 color Netscape palette
  7710.       DIBResult := TDIBWriter.Create(Result, pf8bit, Width, Height, Palette);
  7711.  
  7712.       // Determine if this image is transparent
  7713.       ColMap := ActiveColorMap.Data;
  7714.       IsTransparent := FNeedMask and Transparent;
  7715.       WasTransparent := False;
  7716.       FNeedMask := False;
  7717.       TransparentIndex := 0;
  7718.       MappedTransparentIndex := #0;
  7719.       if (FMask = 0) and (IsTransparent) then
  7720.       begin
  7721.         IsTransparent := True;
  7722.         TransparentIndex := GraphicControlExtension.TransparentColorIndex;
  7723.         Color := ColMap[ord(TransparentIndex)];
  7724.         MappedTransparentIndex := AnsiChar(Color.Blue DIV 51 +
  7725.           MulDiv(6, Color.Green, 51) + MulDiv(36, Color.Red, 51)+1);
  7726.       end;
  7727.  
  7728.       // Allocate bit buffer for transparency mask
  7729.       MaskDest := nil;
  7730.       Bit := $00;
  7731.       if (IsTransparent) then
  7732.       begin
  7733.         MaskRowWidth := ((Width+15) DIV 16) * 2;
  7734.         MaskRowBitWidth := (Width+7) DIV 8;
  7735.         RightBit := $01 SHL ((8 - (Width AND $0007)) AND $0007);
  7736.         GetMem(MaskBits, MaskRowWidth * Height);
  7737.         FillChar(MaskBits^, MaskRowWidth * Height, 0);
  7738.       end else
  7739.       begin
  7740.         MaskBits := nil;
  7741.         MaskRowWidth := 0;
  7742.         MaskRowBitWidth := 0;
  7743.         RightBit := $00;
  7744.       end;
  7745.  
  7746.       try
  7747.         // Process the image
  7748.         Row := 0;
  7749.         MaskRow := MaskBits;
  7750.         Src := FData;
  7751.         while (Row < Height) do
  7752.         begin
  7753.           if ((Row AND $1F) = 0) then
  7754.             Image.Progress(Self, psRunning, MulDiv(Row, 100, Height),
  7755.               False, Rect(0,0,0,0), sProgressRendering);
  7756.  
  7757.           Dst := DIBResult.ScanLine[Row];
  7758.           if (IsTransparent) then
  7759.           begin
  7760.             // Preset all pixels to transparent
  7761.             FillChar(Dst^, Width, ord(MappedTransparentIndex));
  7762.             if (Ditherer.Direction = 1) then
  7763.             begin
  7764.               MaskDest := MaskRow;
  7765.               Bit := $80;
  7766.             end else
  7767.             begin
  7768.               MaskDest := MaskRow + MaskRowBitWidth-1;
  7769.               Bit := RightBit;
  7770.             end;
  7771.           end;
  7772.           inc(Dst, Ditherer.Column);
  7773.  
  7774.           while (Ditherer.Column < Ditherer.Width) and (Ditherer.Column >= 0) do
  7775.           begin
  7776.             Index := ord(Src^);
  7777.             Color := ColMap[ord(Index)];
  7778.  
  7779.             if (IsTransparent) and (Index = TransparentIndex) then
  7780.             begin
  7781.               MaskDest^ := AnsiChar(byte(MaskDest^) OR Bit);
  7782.               WasTransparent := True;
  7783.               Ditherer.NextColumn;
  7784.             end else
  7785.             begin
  7786.               // Dither and map a single pixel
  7787.               Dst^ := Ditherer.Dither(Color.Red, Color.Green, Color.Blue,
  7788.                 Color.Red, Color.Green, Color.Blue);
  7789.             end;
  7790.  
  7791.             if (IsTransparent) then
  7792.             begin
  7793.               if (Ditherer.Direction = 1) then
  7794.               begin
  7795.                 Bit := Bit SHR 1;
  7796.                 if (Bit = $00) then
  7797.                 begin
  7798.                   Bit := $80;
  7799.                   inc(MaskDest, 1);
  7800.                 end;
  7801.               end else
  7802.               begin
  7803.                 Bit := Bit SHL 1;
  7804.                 if (Bit = $00) then
  7805.                 begin
  7806.                   Bit := $01;
  7807.                   dec(MaskDest, 1);
  7808.                 end;
  7809.               end;
  7810.             end;
  7811.  
  7812.             inc(Src, Ditherer.Direction);
  7813.             inc(Dst, Ditherer.Direction);
  7814.           end;
  7815.  
  7816.           if (IsTransparent) then
  7817.             Inc(MaskRow, MaskRowWidth);
  7818.           Inc(Row);
  7819.           inc(Src, Width-Ditherer.Direction);
  7820.           Ditherer.NextLine;
  7821.         end;
  7822.  
  7823.         // Transparent paint needs a mask bitmap
  7824.         if (IsTransparent) and (WasTransparent) then
  7825.           FMask := CreateBitmap(Width, Height, 1, 1, MaskBits);
  7826.       finally
  7827.         if (MaskBits <> nil) then
  7828.           FreeMem(MaskBits);
  7829.       end;
  7830.     finally
  7831.       if (ColorLookup <> nil) then
  7832.         ColorLookup.Free;
  7833.       if (Ditherer <> nil) then
  7834.         Ditherer.Free;
  7835.       if (DIBResult <> nil) then
  7836.         DIBResult.Free;
  7837.     end;
  7838.   except
  7839.     Result.Free;
  7840.     raise;
  7841.   end;
  7842. end;
  7843. {$IFDEF R_PLUS}
  7844.   {$RANGECHECKS ON}
  7845.   {$UNDEF R_PLUS}
  7846. {$ENDIF}
  7847.  
  7848. function TGIFSubImage.DoGetBitmap: TBitmap;
  7849. var
  7850.   ScanLineRow       : Integer;
  7851.   DIBResult     : TDIB;
  7852.   DestScanLine      ,
  7853.   Src           : PAnsiChar;
  7854.   TransparentIndex  : byte;
  7855.   IsTransparent     : boolean;
  7856.   WasTransparent    : boolean;
  7857.  
  7858.   MaskBits      : PAnsiChar;
  7859.   MaskDest      : PAnsiChar;
  7860.   MaskRow       : PAnsiChar;
  7861.   MaskRowWidth      : integer;
  7862.   Col           : integer;
  7863.   MaskByte      : byte;
  7864.   Bit           : byte;
  7865. begin
  7866.   Result := TBitmap.Create;
  7867.   try
  7868.  
  7869. {$IFNDEF VER9x}
  7870.     if (Width*Height > BitmapAllocationThreshold) then
  7871.       SetPixelFormat(Result, pf1bit); // To reduce resource consumption of resize
  7872. {$ENDIF}
  7873.  
  7874.     if (Empty) then
  7875.     begin
  7876.       // Set bitmap width and height
  7877.       Result.Width := Width;
  7878.       Result.Height := Height;
  7879.  
  7880.       // Build and copy palette to bitmap
  7881.       Result.Palette := CopyPalette(Palette);
  7882.  
  7883.       exit;
  7884.     end;
  7885.  
  7886.     // Get DIB buffer for scanline operations
  7887.     DIBResult := TDIBWriter.Create(Result, pf8bit, Width, Height, Palette);
  7888.     try
  7889.  
  7890.       // Determine if this image is transparent
  7891.       IsTransparent := FNeedMask and Transparent;
  7892.       WasTransparent := False;
  7893.       FNeedMask := False;
  7894.       TransparentIndex := 0;
  7895.       if (FMask = 0) and (IsTransparent) then
  7896.       begin
  7897.         IsTransparent := True;
  7898.         TransparentIndex := GraphicControlExtension.TransparentColorIndex;
  7899.       end;
  7900.       // Allocate bit buffer for transparency mask
  7901.       if (IsTransparent) then
  7902.       begin
  7903.         MaskRowWidth := ((Width+15) DIV 16) * 2;
  7904.         GetMem(MaskBits, MaskRowWidth * Height);
  7905.         FillChar(MaskBits^, MaskRowWidth * Height, 0);
  7906.         IsTransparent := (MaskBits <> nil);
  7907.       end else
  7908.       begin
  7909.         MaskBits := nil;
  7910.         MaskRowWidth := 0;
  7911.       end;
  7912.  
  7913.       try
  7914.         ScanLineRow := 0;
  7915.         Src := FData;
  7916.         MaskRow := MaskBits;
  7917.         while (ScanLineRow < Height) do
  7918.         begin
  7919.           DestScanline := DIBResult.ScanLine[ScanLineRow];
  7920.  
  7921.           if ((ScanLineRow AND $1F) = 0) then
  7922.             Image.Progress(Self, psRunning, MulDiv(ScanLineRow, 100, Height),
  7923.               False, Rect(0,0,0,0), sProgressRendering);
  7924.  
  7925.           Move(Src^, DestScanline^, Width);
  7926.           Inc(ScanLineRow);
  7927.  
  7928.           if (IsTransparent) then
  7929.           begin
  7930.             Bit := $80;
  7931.             MaskDest := MaskRow;
  7932.             MaskByte := 0;
  7933.             for Col := 0 to Width-1 do
  7934.             begin
  7935.               // Set a bit in the mask if the pixel is transparent
  7936.               if (Src^ = AnsiChar(TransparentIndex)) then
  7937.                 MaskByte := MaskByte OR Bit;
  7938.  
  7939.               Bit := Bit SHR 1;
  7940.               if (Bit = $00) then
  7941.               begin
  7942.                 // Store a mask byte for each 8 pixels
  7943.                 Bit := $80;
  7944.                 WasTransparent := WasTransparent or (MaskByte <> 0);
  7945.                 MaskDest^ := AnsiChar(MaskByte);
  7946.                 inc(MaskDest);
  7947.                 MaskByte := 0;
  7948.               end;
  7949.               Inc(Src);
  7950.             end;
  7951.             // Save the last mask byte in case the width isn't divisable by 8
  7952.             if (MaskByte <> 0) then
  7953.             begin
  7954.               WasTransparent := True;
  7955.               MaskDest^ := AnsiChar(MaskByte);
  7956.             end;
  7957.             Inc(MaskRow, MaskRowWidth);
  7958.           end else
  7959.             Inc(Src, Width);
  7960.         end;
  7961.  
  7962.         // Transparent paint needs a mask bitmap
  7963.         if (IsTransparent) and (WasTransparent) then
  7964.           FMask := CreateBitmap(Width, Height, 1, 1, MaskBits);
  7965.       finally
  7966.         if (MaskBits <> nil) then
  7967.           FreeMem(MaskBits);
  7968.       end;
  7969.     finally
  7970.       // Free DIB buffer used for scanline operations
  7971.       DIBResult.Free;
  7972.     end;
  7973.   except
  7974.     Result.Free;
  7975.     raise;
  7976.   end;
  7977. end;
  7978.  
  7979. {$ifdef DEBUG_RENDERPERFORMANCE}
  7980. var
  7981.   ImageCount        : DWORD = 0;
  7982.   RenderTime        : DWORD = 0;
  7983. {$endif}
  7984. function TGIFSubImage.GetBitmap: TBitmap;
  7985. var
  7986.   n         : integer;
  7987. {$ifdef DEBUG_RENDERPERFORMANCE}
  7988.   RenderStartTime   : DWORD;
  7989. {$endif}
  7990. begin
  7991. {$ifdef DEBUG_RENDERPERFORMANCE}
  7992.   if (GetAsyncKeyState(VK_CONTROL) <> 0) then
  7993.   begin
  7994.     ShowMessage(format('Render %d images in %d mS, Rate %d mS/image (%d images/S)',
  7995.       [ImageCount, RenderTime,
  7996.        RenderTime DIV (ImageCount+1),
  7997.        MulDiv(ImageCount, 1000, RenderTime+1)]));
  7998.   end;
  7999. {$endif}
  8000.   Result := FBitmap;
  8001.   if (Result <> nil) or (Empty) then
  8002.     Exit;
  8003.  
  8004. {$ifdef DEBUG_RENDERPERFORMANCE}
  8005.   inc(ImageCount);
  8006.   RenderStartTime := timeGetTime;
  8007. {$endif}
  8008.   try
  8009.     Image.Progress(Self, psStarting, 0, False, Rect(0,0,0,0), sProgressRendering);
  8010.     try
  8011.  
  8012.       if (Image.DoDither) then
  8013.         // Create dithered bitmap
  8014.         FBitmap := DoGetDitherBitmap
  8015.       else
  8016.         // Create "regular" bitmap
  8017.         FBitmap := DoGetBitmap;
  8018.  
  8019.       Result := FBitmap;
  8020.  
  8021.     finally
  8022.       if ExceptObject = nil then
  8023.         n := 100
  8024.       else
  8025.         n := 0;
  8026.       Image.Progress(Self, psEnding, n, Image.PaletteModified, Rect(0,0,0,0),
  8027.         sProgressRendering);
  8028.       // Make sure new palette gets realized, in case OnProgress event didn't.
  8029.       if Image.PaletteModified then
  8030.         Image.Changed(Self);
  8031.     end;
  8032.   except
  8033.     on EAbort do ;   // OnProgress can raise EAbort to cancel image load
  8034.   end;
  8035. {$ifdef DEBUG_RENDERPERFORMANCE}
  8036.   inc(RenderTime, timeGetTime-RenderStartTime);
  8037. {$endif}
  8038. end;
  8039.  
  8040. procedure TGIFSubImage.SetBitmap(Value: TBitmap);
  8041. begin
  8042.   FreeBitmap;
  8043.   if (Value <> nil) then
  8044.     Assign(Value);
  8045. end;
  8046.  
  8047. function TGIFSubImage.GetActiveColorMap: TGIFColorMap;
  8048. begin
  8049.   if (ColorMap.Count > 0) or (Image.GlobalColorMap.Count = 0) then
  8050.     Result := ColorMap
  8051.   else
  8052.     Result := Image.GlobalColorMap;
  8053. end;
  8054.  
  8055. function TGIFSubImage.GetInterlaced: boolean;
  8056. begin
  8057.   Result := (FImageDescriptor.PackedFields AND idInterlaced) <> 0;
  8058. end;
  8059.  
  8060. procedure TGIFSubImage.SetInterlaced(Value: boolean);
  8061. begin
  8062.   if (Value) then
  8063.     FImageDescriptor.PackedFields := FImageDescriptor.PackedFields OR idInterlaced
  8064.   else
  8065.     FImageDescriptor.PackedFields := FImageDescriptor.PackedFields AND NOT(idInterlaced);
  8066. end;
  8067.  
  8068. function TGIFSubImage.GetVersion: TGIFVersion;
  8069. var
  8070.   v         : TGIFVersion;
  8071.   i         : integer;
  8072. begin
  8073.   if (ColorMap.Optimized) then
  8074.     Result := gv89a
  8075.   else
  8076.     Result := inherited GetVersion;
  8077.   i := 0;
  8078.   while (Result < high(TGIFVersion)) and (i < FExtensions.Count) do
  8079.   begin
  8080.     v := FExtensions[i].Version;
  8081.     if (v > Result) then
  8082.       Result := v;
  8083.   end;
  8084. end;
  8085.  
  8086. function TGIFSubImage.GetColorResolution: integer;
  8087. begin
  8088.   Result := ColorMap.BitsPerPixel-1;
  8089. end;
  8090.  
  8091. function TGIFSubImage.GetBitsPerPixel: integer;
  8092. begin
  8093.   Result := ColorMap.BitsPerPixel;
  8094. end;
  8095.  
  8096. function TGIFSubImage.GetBoundsRect: TRect;
  8097. begin
  8098.   Result := Rect(FImageDescriptor.Left,
  8099.     FImageDescriptor.Top,
  8100.     FImageDescriptor.Left+FImageDescriptor.Width,
  8101.     FImageDescriptor.Top+FImageDescriptor.Height);
  8102. end;
  8103.  
  8104. procedure TGIFSubImage.DoSetBounds(ALeft, ATop, AWidth, AHeight: integer);
  8105. var
  8106.   TooLarge      : boolean;
  8107.   Zap           : boolean;
  8108. begin
  8109.   Zap := (FImageDescriptor.Width <> Width) or (FImageDescriptor.Height <> AHeight);
  8110.   FImageDescriptor.Left := ALeft;
  8111.   FImageDescriptor.Top := ATop;
  8112.   FImageDescriptor.Width := AWidth;
  8113.   FImageDescriptor.Height := AHeight;
  8114.  
  8115.   // Delete existing image and bitmaps if size has changed
  8116.   if (Zap) then
  8117.   begin
  8118.     FreeBitmap;
  8119.     FreeMask;
  8120.     FreeImage;
  8121.     // ...and allocate a new image
  8122.     NewImage;
  8123.   end;
  8124.  
  8125.   TooLarge := False;
  8126.   // Set width & height if added image is larger than existing images
  8127. {$IFDEF STRICT_MOZILLA}
  8128.   // From Mozilla source:
  8129.   // Work around broken GIF files where the logical screen
  8130.   // size has weird width or height. [...]
  8131.   if (Image.Width < AWidth) or (Image.Height < AHeight) then
  8132.   begin
  8133.     TooLarge := True;
  8134.     Image.Width := AWidth;
  8135.     Image.Height := AHeight;
  8136.     Left := 0;
  8137.     Top := 0;
  8138.   end;
  8139. {$ELSE}
  8140.   if (Image.Width < ALeft+AWidth) then
  8141.   begin
  8142.     if (Image.Width > 0) then
  8143.     begin
  8144.       TooLarge := True;
  8145.       Warning(gsWarning, sBadWidth)
  8146.     end;
  8147.     Image.Width := ALeft+AWidth;
  8148.   end;
  8149.   if (Image.Height < ATop+AHeight) then
  8150.   begin
  8151.     if (Image.Height > 0) then
  8152.     begin
  8153.       TooLarge := True;
  8154.       Warning(gsWarning, sBadHeight)
  8155.     end;
  8156.     Image.Height := ATop+AHeight;
  8157.   end;
  8158. {$ENDIF}
  8159.  
  8160.   if (TooLarge) then
  8161.     Warning(gsWarning, sScreenSizeExceeded);
  8162. end;
  8163.  
  8164. procedure TGIFSubImage.SetBoundsRect(const Value: TRect);
  8165. begin
  8166.   DoSetBounds(Value.Left, Value.Top, Value.Right-Value.Left+1, Value.Bottom-Value.Top+1);
  8167. end;
  8168.  
  8169. function TGIFSubImage.GetClientRect: TRect;
  8170. begin
  8171.   Result := Rect(0, 0, FImageDescriptor.Width, FImageDescriptor.Height);
  8172. end;
  8173.  
  8174. function TGIFSubImage.GetPixel(x, y: integer): BYTE;
  8175. begin
  8176.   if (x < 0) or (x > Width-1) then
  8177.     Error(sBadPixelCoordinates);
  8178.   Result := BYTE(PAnsiChar(longInt(Scanline[y]) + x)^);
  8179. end;
  8180.  
  8181. // 2006.10.09 ->
  8182. procedure TGIFSubImage.SetPixel(x, y: integer; Value: BYTE );
  8183. begin
  8184.   if (x < 0) or (x > Width-1) or (y < 0) or (y > Height-1) then
  8185.     Error(sBadPixelCoordinates);
  8186.   if Value >= ActiveColorMap.FCount then
  8187.     Error(sBadColorIndex);
  8188. // 2008.10.19 ->
  8189. //  BYTE(PChar(longInt(Scanline[y]) + x)^) := Value;
  8190.   PByte(LongInt(Scanline[y]) + x)^ := Value;
  8191. // 2008.10.19 <-
  8192. end;
  8193. // 2006.10.09 <-
  8194.  
  8195. function TGIFSubImage.GetScanline(y: integer): pointer;
  8196. begin
  8197.   if (y < 0) or (y > Height-1) then
  8198.     Error(sBadPixelCoordinates);
  8199.   NeedImage;
  8200.   Result := pointer(longInt(FData) + y * Width);
  8201. end;
  8202.  
  8203. procedure TGIFSubImage.Prepare;
  8204. var
  8205.   Pack          : BYTE;
  8206. begin
  8207.   Pack := FImageDescriptor.PackedFields;
  8208.   if (ColorMap.Count > 0) then
  8209.   begin
  8210.     Pack := idLocalColorTable;
  8211.     if (ColorMap.Optimized) then
  8212.       Pack := Pack OR idSort;
  8213.     Pack := (Pack AND NOT(idColorTableSize)) OR (ColorResolution AND idColorTableSize);
  8214.   end else
  8215.     Pack := Pack AND NOT(idLocalColorTable OR idSort OR idColorTableSize);
  8216.   FImageDescriptor.PackedFields := Pack;
  8217. end;
  8218.  
  8219. procedure TGIFSubImage.SaveToStream(Stream: TStream);
  8220. begin
  8221.   FExtensions.SaveToStream(Stream);
  8222.   if (Empty) then
  8223.     exit;
  8224.   Prepare;
  8225.   Stream.Write(FImageDescriptor, sizeof(TImageDescriptor));
  8226.   ColorMap.SaveToStream(Stream);
  8227.   Compress(Stream);
  8228. end;
  8229.  
  8230. procedure TGIFSubImage.LoadFromStream(Stream: TStream);
  8231. var
  8232.   ColorCount        : integer;
  8233.   b         : BYTE;
  8234. begin
  8235.   Clear;
  8236.   FExtensions.LoadFromStream(Stream, self);
  8237.   // Check for extension without image
  8238.   if (Stream.Read(b, 1) <> 1) then
  8239.     exit;
  8240.   Stream.Seek(-1, soFromCurrent);
  8241.   if (b = bsTrailer) or (b = 0) then
  8242.     exit;
  8243.  
  8244.   ReadCheck(Stream, FImageDescriptor, sizeof(TImageDescriptor));
  8245.  
  8246.   // From Mozilla source:
  8247.   // Work around more broken GIF files that have zero image
  8248.   // width or height
  8249.   if (FImageDescriptor.Height = 0) or (FImageDescriptor.Width = 0) then
  8250.   begin
  8251.     FImageDescriptor.Height := Image.Height;
  8252.     FImageDescriptor.Width := Image.Width;
  8253.     Warning(gsWarning, sScreenSizeExceeded);
  8254.   end;
  8255.  
  8256.   if (FImageDescriptor.PackedFields AND idLocalColorTable = idLocalColorTable) then
  8257.   begin
  8258.     ColorCount := 2 SHL (FImageDescriptor.PackedFields AND idColorTableSize);
  8259.     if (ColorCount < 2) or (ColorCount > 256) then
  8260.       Error(sImageBadColorSize);
  8261.     ColorMap.LoadFromStream(Stream, ColorCount);
  8262.   end;
  8263.  
  8264.   Decompress(Stream);
  8265.  
  8266.   // On-load rendering
  8267.   if (GIFImageRenderOnLoad) then
  8268.     // Touch bitmap to force frame to be rendered
  8269.     Bitmap;
  8270. end;
  8271.  
  8272. procedure TGIFSubImage.AssignTo(Dest: TPersistent);
  8273. begin
  8274.   if (Dest is TBitmap) then
  8275.     Dest.Assign(Bitmap)
  8276.   else
  8277.     inherited AssignTo(Dest);
  8278. end;
  8279.  
  8280. procedure TGIFSubImage.Assign(Source: TPersistent);
  8281. var
  8282.   MemoryStream      : TMemoryStream;
  8283.   i         : integer;
  8284.   PixelFormat       : TPixelFormat;
  8285.   DIBSource     : TDIB;
  8286.   ABitmap       : TBitmap;
  8287.  
  8288.   procedure Import8Bit(Dest: PAnsiChar);
  8289.   var
  8290.     y           : integer;
  8291.   begin
  8292.     // Copy colormap
  8293. {$ifdef VER10_PLUS}
  8294.     if (FBitmap.HandleType = bmDIB) then
  8295.       FColorMap.ImportDIBColors(FBitmap.Canvas.Handle)
  8296.     else
  8297. {$ENDIF}
  8298.       FColorMap.ImportPalette(FBitmap.Palette);
  8299.     // Copy pixels
  8300.     for y := 0 to Height-1 do
  8301.     begin
  8302.       if ((y AND $1F) = 0) then
  8303.         Image.Progress(Self, psRunning, MulDiv(y, 100, Height), False, Rect(0,0,0,0), sProgressConverting);
  8304.       Move(DIBSource.Scanline[y]^, Dest^, Width);
  8305.       inc(Dest, Width);
  8306.     end;
  8307.   end;
  8308.  
  8309.   procedure Import4Bit(Dest: PAnsiChar);
  8310.   var
  8311.     x, y        : integer;
  8312.     Scanline        : PAnsiChar;
  8313.   begin
  8314.     // Copy colormap
  8315.     FColorMap.ImportPalette(FBitmap.Palette);
  8316.     // Copy pixels
  8317.     for y := 0 to Height-1 do
  8318.     begin
  8319.       if ((y AND $1F) = 0) then
  8320.         Image.Progress(Self, psRunning, MulDiv(y, 100, Height), False, Rect(0,0,0,0), sProgressConverting);
  8321.       ScanLine := DIBSource.Scanline[y];
  8322.       for x := 0 to Width-1 do
  8323.       begin
  8324.         if (x AND $01 = 0) then
  8325. // 2008.10.19 ->
  8326. //          Dest^ := chr(ord(ScanLine^) SHR 4)
  8327.           Dest^ := AnsiChar(ord(ScanLine^) SHR 4)
  8328. // 2008.10.19 <-
  8329.         else
  8330.         begin
  8331. // 2008.10.19 ->
  8332. //          Dest^ := chr(ord(ScanLine^) AND $0F);
  8333.           Dest^ := AnsiChar(ord(ScanLine^) AND $0F);
  8334. // 2008.10.19 <-
  8335.           inc(ScanLine);
  8336.         end;
  8337.         inc(Dest);
  8338.       end;
  8339.     end;
  8340.   end;
  8341.  
  8342.   procedure Import1Bit(Dest: PAnsiChar);
  8343.   var
  8344.     x, y        : integer;
  8345.     Scanline        : PAnsiChar;
  8346.     Bit         : integer;
  8347.     Byte        : integer;
  8348.   begin
  8349.     // Copy colormap
  8350.     FColorMap.ImportPalette(FBitmap.Palette);
  8351.     // Copy pixels
  8352.     for y := 0 to Height-1 do
  8353.     begin
  8354.       if ((y AND $1F) = 0) then
  8355.         Image.Progress(Self, psRunning, MulDiv(y, 100, Height), False, Rect(0,0,0,0), sProgressConverting);
  8356.       ScanLine := DIBSource.Scanline[y];
  8357.       x := Width;
  8358.       Bit := 0;
  8359.       Byte := 0; // To avoid compiler warning
  8360.       while (x > 0) do
  8361.       begin
  8362.         if (Bit = 0) then
  8363.         begin
  8364.           Bit := 8;
  8365.           Byte := ord(ScanLine^);
  8366.           inc(Scanline);
  8367.         end;
  8368. // 2008.10.19 ->
  8369. //        Dest^ := chr((Byte AND $80) SHR 7);
  8370.         Dest^ := AnsiChar((Byte AND $80) SHR 7);
  8371. // 2008.10.19 <-
  8372.         Byte := Byte SHL 1;
  8373.         inc(Dest);
  8374.         dec(Bit);
  8375.         dec(x);
  8376.       end;
  8377.     end;
  8378.   end;
  8379.  
  8380.   procedure Import24Bit(Dest: PAnsiChar);
  8381.   type
  8382.     TCacheEntry = record
  8383.       Color     : TColor;
  8384.       Index     : integer;
  8385.     end;
  8386.   const
  8387.     // Size of palette cache. Must be 2^n.
  8388.     // The cache holds the palette index of the last "CacheSize" colors
  8389.     // processed. Hopefully the cache can speed things up a bit... Initial
  8390.     // testing shows that this is indeed the case at least for non-dithered
  8391.     // bitmaps.
  8392.     // All the same, a small hash table would probably be much better.
  8393.     CacheSize       = 8;
  8394.   var
  8395.     i           : integer;
  8396.     Cache       : array[0..CacheSize-1] of TCacheEntry;
  8397.     LastEntry       : integer;
  8398.     Scanline        : PRGBTriple;
  8399.     Pixel       : TColor;
  8400.     RGBTriple       : TRGBTriple absolute Pixel;
  8401.     x, y        : integer;
  8402.     ColorMap        : PColorMap;
  8403.     t           : byte;
  8404.   label
  8405.     NextPixel;
  8406.   begin
  8407.     for i := 0 to CacheSize-1 do
  8408.       Cache[i].Index := -1;
  8409.     LastEntry := 0;
  8410.  
  8411.     // Copy all pixels and build colormap
  8412.     for y := 0 to Height-1 do
  8413.     begin
  8414.       if ((y AND $1F) = 0) then
  8415.         Image.Progress(Self, psRunning, MulDiv(y, 100, Height), False, Rect(0,0,0,0), sProgressConverting);
  8416.       ScanLine := DIBSource.Scanline[y];
  8417.       for x := 0 to Width-1 do
  8418.       begin
  8419.         Pixel := 0;
  8420.         RGBTriple := Scanline^;
  8421.         // Scan cache for color from most recently processed color to last
  8422.         // recently processed. This is done because TColorMap.AddUnique is very slow.
  8423.         i := LastEntry;
  8424.         repeat
  8425.           if (Cache[i].Index = -1) then
  8426.             break;
  8427.           if (Cache[i].Color = Pixel) then
  8428.           begin
  8429. // 2008.10.19 ->
  8430. //            Dest^ := chr(Cache[i].Index);
  8431.             Dest^ := AnsiChar(Cache[i].Index);
  8432. // 2008.10.19 <-
  8433.             LastEntry := i;
  8434.             goto NextPixel;
  8435.           end;
  8436.           if (i = 0) then
  8437.             i := CacheSize-1
  8438.           else
  8439.             dec(i);
  8440.         until (i = LastEntry);
  8441.         // Color not found in cache, do it the slow way instead
  8442. // 2008.10.19 ->
  8443. //        Dest^ := chr(FColorMap.AddUnique(Pixel));
  8444.         Dest^ := AnsiChar(FColorMap.AddUnique(Pixel));
  8445. // 2008.10.19 <-
  8446.         // Add color and index to cache
  8447.         LastEntry := (LastEntry + 1) AND (CacheSize-1);
  8448.         Cache[LastEntry].Color := Pixel;
  8449.         Cache[LastEntry].Index := ord(Dest^);
  8450.  
  8451.         NextPixel:
  8452.         Inc(Dest);
  8453.         Inc(Scanline);
  8454.       end;
  8455.     end;
  8456.     // Convert colors in colormap from BGR to RGB
  8457.     ColorMap := FColorMap.Data;
  8458.     i := FColorMap.Count;
  8459.     while (i > 0) do
  8460.     begin
  8461.       t := ColorMap^[0].Red;
  8462.       ColorMap^[0].Red := ColorMap^[0].Blue;
  8463.       ColorMap^[0].Blue := t;
  8464.       inc(integer(ColorMap), sizeof(TGIFColor));
  8465.       dec(i);
  8466.     end;
  8467.   end;
  8468.  
  8469.   procedure ImportViaDraw(ABitmap: TBitmap; Graphic: TGraphic);
  8470.   begin
  8471.     ABitmap.Height := Graphic.Height;
  8472.     ABitmap.Width := Graphic.Width;
  8473.  
  8474.     // Note: Disable the call to SafeSetPixelFormat below to import
  8475.     // in max number of colors with the risk of having to use
  8476.     // TCanvas.Pixels to do it (very slow).
  8477.  
  8478.     // Make things a little easier for TGIFSubImage.Assign by converting
  8479.     // pfDevice to a more import friendly format
  8480. {$ifdef SLOW_BUT_SAFE}
  8481.     SafeSetPixelFormat(ABitmap, pf8bit);
  8482. {$else}
  8483. {$ifndef VER9x}
  8484.     SetPixelFormat(ABitmap, pf24bit);
  8485. {$endif}
  8486. {$endif}
  8487.     ABitmap.Canvas.Draw(0, 0, Graphic);
  8488.   end;
  8489.  
  8490.   procedure AddMask(Mask: TBitmap);
  8491.   var
  8492.     DIBReader       : TDIBReader;
  8493.     TransparentIndex    : integer;
  8494.     i           ,
  8495.     j           : integer;
  8496.     GIFPixel        ,
  8497.     MaskPixel       : PAnsiChar;
  8498.     WasTransparent  : boolean;
  8499.     GCE         : TGIFGraphicControlExtension;
  8500.   begin
  8501.     // Optimize colormap to make room for transparent color
  8502.     ColorMap.Optimize;
  8503.     // Can't make transparent if no color or colormap full
  8504.     if (ColorMap.Count = 0) or (ColorMap.Count = 256) then
  8505.       exit;
  8506.  
  8507.     // Add the transparent color to the color map
  8508.     TransparentIndex := ColorMap.Add(TColor(0));
  8509.     WasTransparent := False;
  8510.  
  8511.     DIBReader := TDIBReader.Create(Mask, pf8bit);
  8512.     try
  8513.       for i := 0 to Height-1 do
  8514.       begin
  8515.         MaskPixel := DIBReader.Scanline[i];
  8516.         GIFPixel := Scanline[i];
  8517.         for j := 0 to Width-1 do
  8518.         begin
  8519.           // Change all unmasked pixels to transparent
  8520.           if (MaskPixel^ <> #0) then
  8521.           begin
  8522. // 2008.10.19 ->
  8523. //            GIFPixel^ := chr(TransparentIndex);
  8524.             GIFPixel^ := AnsiChar(TransparentIndex);
  8525. // 2008.10.19 <-
  8526.             WasTransparent := True;
  8527.           end;
  8528.           inc(MaskPixel);
  8529.           inc(GIFPixel);
  8530.         end;
  8531.       end;
  8532.     finally
  8533.       DIBReader.Free;
  8534.     end;
  8535.  
  8536.     // Add a Graphic Control Extension if any part of the mask was transparent
  8537.     if (WasTransparent) then
  8538.     begin
  8539.       GCE := TGIFGraphicControlExtension.Create(self);
  8540.       GCE.Transparent := True;
  8541.       GCE.TransparentColorIndex := TransparentIndex;
  8542.       Extensions.Add(GCE);
  8543.     end else
  8544.       // Otherwise removed the transparency color since it wasn't used
  8545.       ColorMap.Delete(TransparentIndex);
  8546.   end;
  8547.  
  8548.   procedure AddMaskOnly(hMask: hBitmap);
  8549.   var
  8550.     Mask        : TBitmap;
  8551.   begin
  8552.     if (hMask = 0) then
  8553.       exit;
  8554.  
  8555.     // Encapsulate the mask
  8556.     Mask := TBitmap.Create;
  8557.     try
  8558. //      Mask.Handle := hMask;  // 2003.08.04
  8559.       Mask.Handle := Windows.CopyImage(hMask, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG);  // 2003.08.04
  8560.       AddMask(Mask);
  8561.     finally
  8562. //      Mask.ReleaseHandle;  // 2003.08.04
  8563.       Mask.Free;
  8564.     end;
  8565.   end;
  8566.  
  8567.   procedure AddIconMask(Icon: TIcon);
  8568.   var
  8569.     IconInfo        : TIconInfo;
  8570.   begin
  8571.     if (not GetIconInfo(Icon.Handle, IconInfo)) then
  8572.       exit;
  8573.  
  8574.     // Extract the icon mask
  8575.     AddMaskOnly(IconInfo.hbmMask);
  8576.   end;
  8577.  
  8578.   procedure AddMetafileMask(Metafile: TMetaFile);
  8579.   var
  8580.     Mask1       ,
  8581.     Mask2       : TBitmap;
  8582.  
  8583.     procedure DrawMetafile(ABitmap: TBitmap; Background: TColor);
  8584.     begin
  8585.       ABitmap.Width := Metafile.Width;
  8586.       ABitmap.Height := Metafile.Height;
  8587. {$ifndef VER9x}
  8588.       SetPixelFormat(ABitmap, pf24bit);
  8589. {$endif}
  8590.       ABitmap.Canvas.Brush.Color := Background;
  8591.       ABitmap.Canvas.Brush.Style := bsSolid;
  8592.       ABitmap.Canvas.FillRect(ABitmap.Canvas.ClipRect);
  8593.       ABitmap.Canvas.Draw(0,0, Metafile);
  8594.     end;
  8595.  
  8596.   begin
  8597.     // Create the metafile mask
  8598.     Mask1 := TBitmap.Create;
  8599.     try
  8600.       Mask2 := TBitmap.Create;
  8601.       try
  8602.         DrawMetafile(Mask1, clWhite);
  8603.         DrawMetafile(Mask2, clBlack);
  8604.         Mask1.Canvas.CopyMode := cmSrcInvert;
  8605.         Mask1.Canvas.Draw(0,0, Mask2);
  8606.         AddMask(Mask1);
  8607.       finally
  8608.         Mask2.Free;
  8609.       end;
  8610.     finally
  8611.       Mask1.Free;
  8612.     end;
  8613.   end;
  8614.  
  8615. begin
  8616.   if (Source = self) then
  8617.     exit;
  8618.   if (Source = nil) then
  8619.   begin
  8620.     Clear;
  8621.   end else
  8622.   //
  8623.   // TGIFSubImage import
  8624.   //
  8625.   if (Source is TGIFSubImage) then
  8626.   begin
  8627.     // Zap existing colormap, extensions and bitmap
  8628.     Clear;
  8629.     if (TGIFSubImage(Source).Empty) then
  8630.       exit;
  8631.     // Copy source data
  8632.     FImageDescriptor := TGIFSubImage(Source).FImageDescriptor;
  8633.     FTransparent := TGIFSubImage(Source).Transparent;
  8634.     // Copy image data
  8635.     NewImage;
  8636.     if (FData <> nil) and (TGIFSubImage(Source).Data <> nil) then
  8637.       Move(TGIFSubImage(Source).Data^, FData^, FDataSize);
  8638.     // Copy palette
  8639.     FColorMap.Assign(TGIFSubImage(Source).ColorMap);
  8640.     // Copy extensions
  8641.     if (TGIFSubImage(Source).Extensions.Count > 0) then
  8642.     begin
  8643.       MemoryStream := TMemoryStream.Create;
  8644.       try
  8645.         TGIFSubImage(Source).Extensions.SaveToStream(MemoryStream);
  8646.         MemoryStream.Seek(0, soFromBeginning);
  8647.         Extensions.LoadFromStream(MemoryStream, Self);
  8648.       finally
  8649.         MemoryStream.Free;
  8650.       end;
  8651.     end;
  8652.  
  8653.     // Copy bitmap representation
  8654.     // (Not really nescessary but improves performance if the bitmap is needed
  8655.     // later on)
  8656.     if (TGIFSubImage(Source).HasBitmap) then
  8657.     begin
  8658.       NewBitmap;
  8659.       FBitmap.Assign(TGIFSubImage(Source).Bitmap);
  8660.     end;
  8661.   end else
  8662.   //
  8663.   // Bitmap import
  8664.   //
  8665.   if (Source is TBitmap) then
  8666.   begin
  8667.     // Zap existing colormap, extensions and bitmap
  8668.     Clear;
  8669.     if (TBitmap(Source).Empty) then
  8670.       exit;
  8671.  
  8672.     Width := TBitmap(Source).Width;
  8673.     Height := TBitmap(Source).Height;
  8674.  
  8675.     PixelFormat := GetPixelFormat(TBitmap(Source));
  8676. {$ifdef VER9x}
  8677.     // Delphi 2 TBitmaps are always DDBs. This means that if a 24 bit
  8678.     // bitmap is loaded in 8 bit device mode, TBitmap.PixelFormat will
  8679.     // be pf8bit, but TBitmap.Palette will be 0!
  8680.     if (TBitmap(Source).Palette = 0) then
  8681.       PixelFormat := pfDevice;
  8682. {$endif}
  8683.     if (PixelFormat > pf8bit) or (PixelFormat = pfDevice) then
  8684.     begin
  8685.       // Convert image to 8 bits/pixel or less
  8686.       FBitmap := ReduceColors(TBitmap(Source), Image.ColorReduction,
  8687.         Image.DitherMode, Image.ReductionBits, 0);
  8688.       PixelFormat := GetPixelFormat(FBitmap);
  8689.     end else
  8690.     begin
  8691.       // Create new bitmap and copy
  8692.       NewBitmap;
  8693.       FBitmap.Assign(TBitmap(Source));
  8694.     end;
  8695.  
  8696.     // Allocate new buffer
  8697.     NewImage;
  8698.  
  8699.     Image.Progress(Self, psStarting, 0, False, Rect(0,0,0,0), sProgressConverting);
  8700.     try
  8701. {$ifdef VER9x}
  8702.       // This shouldn't happen, but better safe...
  8703.       if (FBitmap.Palette = 0) then
  8704.         PixelFormat := pf24bit;
  8705. {$endif}
  8706.       if (not(PixelFormat in [pf1bit, pf4bit, pf8bit, pf24bit])) then
  8707.         PixelFormat := pf24bit;
  8708.       DIBSource := TDIBReader.Create(FBitmap, PixelFormat);
  8709.       try
  8710.         // Copy pixels
  8711.         case (PixelFormat) of
  8712.           pf8bit: Import8Bit(Fdata);
  8713.           pf4bit: Import4Bit(Fdata);
  8714.           pf1bit: Import1Bit(Fdata);
  8715.         else
  8716. //        Error(sUnsupportedBitmap);
  8717.           Import24Bit(Fdata);
  8718.         end;
  8719.  
  8720.       finally
  8721.         DIBSource.Free;
  8722.       end;
  8723.  
  8724. {$ifdef VER10_PLUS}
  8725.       // Add mask for transparent bitmaps
  8726.       if (TBitmap(Source).Transparent) then
  8727.         AddMaskOnly(TBitmap(Source).MaskHandle);
  8728. {$endif}
  8729.  
  8730.     finally
  8731.       if ExceptObject = nil then
  8732.         i := 100
  8733.       else
  8734.         i := 0;
  8735.       Image.Progress(Self, psEnding, i, Image.PaletteModified, Rect(0,0,0,0), sProgressConverting);
  8736.     end;
  8737.   end else
  8738.   //
  8739.   // TGraphic import
  8740.   //
  8741.   if (Source is TGraphic) then
  8742.   begin
  8743.     // Zap existing colormap, extensions and bitmap
  8744.     Clear;
  8745.     if (TGraphic(Source).Empty) then
  8746.       exit;
  8747.  
  8748.     ABitmap := TBitmap.Create;
  8749.     try
  8750.       // Import TIcon and TMetafile by drawing them onto a bitmap...
  8751.       // ...and then importing the bitmap recursively
  8752.       if (Source is TIcon) or (Source is TMetafile) then
  8753.       begin
  8754.         try
  8755.           ImportViaDraw(ABitmap, TGraphic(Source))
  8756.         except
  8757.           // If import via TCanvas.Draw fails (which it shouldn't), we try the
  8758.           // Assign mechanism instead
  8759.           ABitmap.Assign(Source);
  8760.         end;
  8761.       end else
  8762.         try
  8763.           ABitmap.Assign(Source);
  8764.         except
  8765.           // If automatic conversion to bitmap fails, we try and draw the
  8766.           // graphic on the bitmap instead
  8767.           ImportViaDraw(ABitmap, TGraphic(Source));
  8768.         end;
  8769.       // Convert the bitmap to a GIF frame recursively
  8770.       Assign(ABitmap);
  8771.     finally
  8772.       ABitmap.Free;
  8773.     end;
  8774.  
  8775.     // Import transparency mask
  8776.     if (Source is TIcon) then
  8777.       AddIconMask(TIcon(Source));
  8778.     if (Source is TMetaFile) then
  8779.       AddMetafileMask(TMetaFile(Source));
  8780.  
  8781.   end else
  8782.   //
  8783.   // TPicture import
  8784.   //
  8785.   if (Source is TPicture) then
  8786.   begin
  8787.     // Recursively import TGraphic
  8788.     Assign(TPicture(Source).Graphic);
  8789.   end else
  8790.     // Unsupported format - fall back to Source.AssignTo
  8791.     inherited Assign(Source);
  8792. end;
  8793.  
  8794. // Copied from D3 graphics.pas
  8795. // Fixed by Brian Lowe of Acro Technology Inc. 30Jan98
  8796. function TransparentStretchBlt(DstDC: HDC; DstX, DstY, DstW, DstH: Integer;
  8797.   SrcDC: HDC; SrcX, SrcY, SrcW, SrcH: Integer; MaskDC: HDC; MaskX,
  8798.   MaskY: Integer): Boolean;
  8799. const
  8800.   ROP_DstCopy       = $00AA0029;
  8801. var
  8802.   MemDC         ,
  8803.   OrMaskDC      : HDC;
  8804.   MemBmp        ,
  8805.   OrMaskBmp     : HBITMAP;
  8806.   Save          ,
  8807.   OrMaskSave        : THandle;
  8808.   crText, crBack    : TColorRef;
  8809.   SavePal       : HPALETTE;
  8810.  
  8811. begin
  8812.   Result := True;
  8813.   if (Win32Platform = VER_PLATFORM_WIN32_NT) and (SrcW = DstW) and (SrcH = DstH) then
  8814.   begin
  8815.     MemBmp := GDICheck(CreateCompatibleBitmap(SrcDC, 1, 1));
  8816.     MemBmp := SelectObject(MaskDC, MemBmp);
  8817.     try
  8818.       MaskBlt(DstDC, DstX, DstY, DstW, DstH, SrcDC, SrcX, SrcY, MemBmp, MaskX,
  8819.         MaskY, MakeRop4(ROP_DstCopy, SrcCopy));
  8820.     finally
  8821.       MemBmp := SelectObject(MaskDC, MemBmp);
  8822.       DeleteObject(MemBmp);
  8823.     end;
  8824.     Exit;
  8825.   end;
  8826.  
  8827.   SavePal := 0;
  8828.   MemDC := GDICheck(CreateCompatibleDC(DstDC));
  8829.   try
  8830.     { Color bitmap for combining OR mask with source bitmap }
  8831.     MemBmp := GDICheck(CreateCompatibleBitmap(DstDC, SrcW, SrcH));
  8832.     try
  8833.       Save := SelectObject(MemDC, MemBmp);
  8834.       try
  8835.         { This bitmap needs the size of the source but DC of the dest }
  8836.         OrMaskDC := GDICheck(CreateCompatibleDC(DstDC));
  8837.         try
  8838.           { Need a monochrome bitmap for OR mask!! }
  8839.           OrMaskBmp := GDICheck(CreateBitmap(SrcW, SrcH, 1, 1, nil));
  8840.           try
  8841.             OrMaskSave := SelectObject(OrMaskDC, OrMaskBmp);
  8842.             try
  8843.  
  8844.               // OrMask := 1
  8845.               // Original: BitBlt(OrMaskDC, SrcX, SrcY, SrcW, SrcH, OrMaskDC, SrcX, SrcY, WHITENESS);
  8846.               // Replacement, but not needed: PatBlt(OrMaskDC, SrcX, SrcY, SrcW, SrcH, WHITENESS);
  8847.               // OrMask := OrMask XOR Mask
  8848.               // Not needed: BitBlt(OrMaskDC, SrcX, SrcY, SrcW, SrcH, MaskDC, SrcX, SrcY, SrcInvert);
  8849.               // OrMask := NOT Mask
  8850.               BitBlt(OrMaskDC, SrcX, SrcY, SrcW, SrcH, MaskDC, SrcX, SrcY, NotSrcCopy);
  8851.  
  8852.               // Retrieve source palette (with dummy select)
  8853.               SavePal := SelectPalette(SrcDC, SystemPalette16, False);
  8854.               // Restore source palette
  8855.               SelectPalette(SrcDC, SavePal, False);
  8856.               // Select source palette into memory buffer
  8857.               if SavePal <> 0 then
  8858.                 SavePal := SelectPalette(MemDC, SavePal, True)
  8859.               else
  8860.                 SavePal := SelectPalette(MemDC, SystemPalette16, True);
  8861.               RealizePalette(MemDC);
  8862.  
  8863.               // Mem := OrMask
  8864.               BitBlt(MemDC, SrcX, SrcY, SrcW, SrcH, OrMaskDC, SrcX, SrcY, SrcCopy);
  8865.               // Mem := Mem AND Src
  8866. {$IFNDEF GIF_TESTMASK} // Define GIF_TESTMASK if you want to know what it does...
  8867.               BitBlt(MemDC, SrcX, SrcY, SrcW, SrcH, SrcDC, SrcX, SrcY, SrcAnd);
  8868. {$ELSE}
  8869.               StretchBlt(DstDC, DstX, DstY, DstW DIV 2, DstH, MemDC, SrcX, SrcY, SrcW, SrcH, SrcCopy);
  8870.               StretchBlt(DstDC, DstX+DstW DIV 2, DstY, DstW DIV 2, DstH, SrcDC, SrcX, SrcY, SrcW, SrcH, SrcCopy);
  8871.               exit;
  8872. {$ENDIF}
  8873.             finally
  8874.               if (OrMaskSave <> 0) then
  8875.                 SelectObject(OrMaskDC, OrMaskSave);
  8876.             end;
  8877.           finally
  8878.             DeleteObject(OrMaskBmp);
  8879.           end;
  8880.         finally
  8881.           DeleteDC(OrMaskDC);
  8882.         end;
  8883.  
  8884.         crText := SetTextColor(DstDC, $00000000);
  8885.         crBack := SetBkColor(DstDC, $00FFFFFF);
  8886.  
  8887.         { All color rendering is done at 1X (no stretching),
  8888.           then final 2 masks are stretched to dest DC }
  8889.         // Neat trick!
  8890.         // Dst := Dst AND Mask
  8891.         StretchBlt(DstDC, DstX, DstY, DstW, DstH, MaskDC, SrcX, SrcY, SrcW, SrcH, SrcAnd);
  8892.         // Dst := Dst OR Mem
  8893.         StretchBlt(DstDC, DstX, DstY, DstW, DstH, MemDC, SrcX, SrcY, SrcW, SrcH, SrcPaint);
  8894.  
  8895.         SetTextColor(DstDC, crText);
  8896.         SetTextColor(DstDC, crBack);
  8897.  
  8898.       finally
  8899.         if (Save <> 0) then
  8900.           SelectObject(MemDC, Save);
  8901.       end;
  8902.     finally
  8903.       DeleteObject(MemBmp);
  8904.     end;
  8905.   finally
  8906.     if (SavePal <> 0) then
  8907.       SelectPalette(MemDC, SavePal, False);
  8908.     DeleteDC(MemDC);
  8909.   end;
  8910. end;
  8911.  
  8912. procedure TGIFSubImage.Draw(ACanvas: TCanvas; const Rect: TRect;
  8913.   DoTransparent, DoTile: boolean);
  8914. begin
  8915.   if (DoTile) then
  8916.     StretchDraw(ACanvas, Rect, DoTransparent, DoTile)
  8917.   else
  8918.     StretchDraw(ACanvas, ScaleRect(Rect), DoTransparent, DoTile);
  8919. end;
  8920.  
  8921. type
  8922.   // Dummy class used to gain access to protected method TCanvas.Changed
  8923.   TChangableCanvas = class(TCanvas)
  8924.   end;
  8925.  
  8926. procedure TGIFSubImage.StretchDraw(ACanvas: TCanvas; const Rect: TRect;
  8927.   DoTransparent, DoTile: boolean);
  8928. var
  8929.   MaskDC        : HDC;
  8930.   Save          : THandle;
  8931.   Tile          : TRect;
  8932. {$ifdef DEBUG_DRAWPERFORMANCE}
  8933.   ImageCount        ,
  8934.   TimeStart     ,
  8935.   TimeStop      : DWORD;
  8936. {$endif}
  8937.  
  8938. begin
  8939. {$ifdef DEBUG_DRAWPERFORMANCE}
  8940.   TimeStart := timeGetTime;
  8941.   ImageCount := 0;
  8942. {$endif}
  8943.   if (DoTransparent) and (Transparent) and (HasMask) then
  8944.   begin
  8945.     // Draw transparent using mask
  8946.     Save := 0;
  8947.     MaskDC := 0;
  8948.     try
  8949.       MaskDC := GDICheck(CreateCompatibleDC(0));
  8950.       Save := SelectObject(MaskDC, FMask);
  8951.  
  8952.       if (DoTile) then
  8953.       begin
  8954.         Tile.Left := Rect.Left+Left;
  8955.         Tile.Right := Tile.Left + Width;
  8956.         while (Tile.Left < Rect.Right) do
  8957.         begin
  8958.           Tile.Top := Rect.Top+Top;
  8959.           Tile.Bottom := Tile.Top + Height;
  8960.           while (Tile.Top < Rect.Bottom) do
  8961.           begin
  8962.             TransparentStretchBlt(ACanvas.Handle, Tile.Left, Tile.Top, Width, Height,
  8963.               Bitmap.Canvas.Handle, 0, 0, Width, Height, MaskDC, 0, 0);
  8964.             Tile.Top := Tile.Top + Image.Height;
  8965.             Tile.Bottom := Tile.Bottom + Image.Height;
  8966. {$ifdef DEBUG_DRAWPERFORMANCE}
  8967.             inc(ImageCount);
  8968. {$endif}
  8969.           end;
  8970.           Tile.Left := Tile.Left + Image.Width;
  8971.           Tile.Right := Tile.Right + Image.Width;
  8972.         end;
  8973.       end else
  8974.         TransparentStretchBlt(ACanvas.Handle, Rect.Left, Rect.Top,
  8975.           Rect.Right - Rect.Left, Rect.Bottom - Rect.Top,
  8976.           Bitmap.Canvas.Handle, 0, 0, Width, Height, MaskDC, 0, 0);
  8977.  
  8978.       // Since we are not using any of the TCanvas functions (only handle)
  8979.       // we need to fire the TCanvas.Changed method "manually".
  8980.       TChangableCanvas(ACanvas).Changed;
  8981.  
  8982.     finally
  8983.       if (Save <> 0) then
  8984.         SelectObject(MaskDC, Save);
  8985.       if (MaskDC <> 0) then
  8986.         DeleteDC(MaskDC);
  8987.     end;
  8988.   end else
  8989.   begin
  8990.     if (DoTile) then
  8991.     begin
  8992.       Tile.Left := Rect.Left+Left;
  8993.       Tile.Right := Tile.Left + Width;
  8994.       while (Tile.Left < Rect.Right) do
  8995.       begin
  8996.         Tile.Top := Rect.Top+Top;
  8997.         Tile.Bottom := Tile.Top + Height;
  8998.         while (Tile.Top < Rect.Bottom) do
  8999.         begin
  9000.           ACanvas.StretchDraw(Tile, Bitmap);
  9001.           Tile.Top := Tile.Top + Image.Height;
  9002.           Tile.Bottom := Tile.Bottom + Image.Height;
  9003. {$ifdef DEBUG_DRAWPERFORMANCE}
  9004.           inc(ImageCount);
  9005. {$endif}
  9006.         end;
  9007.         Tile.Left := Tile.Left + Image.Width;
  9008.         Tile.Right := Tile.Right + Image.Width;
  9009.       end;
  9010.     end else
  9011.       ACanvas.StretchDraw(Rect, Bitmap);
  9012.   end;
  9013. {$ifdef DEBUG_DRAWPERFORMANCE}
  9014.   if (GetAsyncKeyState(VK_CONTROL) <> 0) then
  9015.   begin
  9016.     TimeStop := timeGetTime;
  9017.     ShowMessage(format('Draw %d images in %d mS, Rate %d images/mS (%d images/S)',
  9018.       [ImageCount, TimeStop-TimeStart,
  9019.       ImageCount DIV (TimeStop-TimeStart+1),
  9020.       MulDiv(ImageCount, 1000, TimeStop-TimeStart+1)]));
  9021.   end;
  9022. {$endif}
  9023. end;
  9024.  
  9025. // Given a destination rect (DestRect) calculates the
  9026. // area covered by this sub image
  9027. function TGIFSubImage.ScaleRect(DestRect: TRect): TRect;
  9028. var
  9029.   HeightMul     ,
  9030.   HeightDiv     : integer;
  9031.   WidthMul      ,
  9032.   WidthDiv      : integer;
  9033. begin
  9034.   HeightDiv := Image.Height;
  9035.   HeightMul := DestRect.Bottom-DestRect.Top;
  9036.   WidthDiv := Image.Width;
  9037.   WidthMul := DestRect.Right-DestRect.Left;
  9038.  
  9039.   Result.Left := DestRect.Left + muldiv(Left, WidthMul, WidthDiv);
  9040.   Result.Top := DestRect.Top + muldiv(Top, HeightMul, HeightDiv);
  9041.   Result.Right := DestRect.Left + muldiv(Left+Width, WidthMul, WidthDiv);
  9042.   Result.Bottom := DestRect.Top + muldiv(Top+Height, HeightMul, HeightDiv);
  9043. end;
  9044.  
  9045. procedure TGIFSubImage.Crop;
  9046. var
  9047.   TransparentColorIndex : byte;
  9048.   CropLeft      ,
  9049.   CropTop       ,
  9050.   CropRight     ,
  9051.   CropBottom        : integer;
  9052.   WasTransparent    : boolean;
  9053.   i         : integer;
  9054.   NewSize       : integer;
  9055.   NewData       : PAnsiChar;
  9056.   NewWidth      ,
  9057.   NewHeight     : integer;
  9058.   pSource       ,
  9059.   pDest         : PAnsiChar;
  9060. begin
  9061.   if (Empty) or (not Transparent) then
  9062.     exit;
  9063.   TransparentColorIndex := GraphicControlExtension.TransparentColorIndex;
  9064.   CropLeft := 0;
  9065.   CropRight := Width - 1;
  9066.   CropTop := 0;
  9067.   CropBottom := Height - 1;
  9068.   // Find left edge
  9069.   WasTransparent := True;
  9070.   while (CropLeft <= CropRight) and (WasTransparent) do
  9071.   begin
  9072.     for i := CropTop to CropBottom do
  9073.       if (Pixels[CropLeft, i] <> TransparentColorIndex) then
  9074.       begin
  9075.         WasTransparent := False;
  9076.         break;
  9077.       end;
  9078.     if (WasTransparent) then
  9079.       inc(CropLeft);
  9080.   end;
  9081.   // Find right edge
  9082.   WasTransparent := True;
  9083.   while (CropLeft <= CropRight) and (WasTransparent) do
  9084.   begin
  9085.     for i := CropTop to CropBottom do
  9086.       if (pixels[CropRight, i] <> TransparentColorIndex) then
  9087.       begin
  9088.         WasTransparent := False;
  9089.         break;
  9090.       end;
  9091.     if (WasTransparent) then
  9092.       dec(CropRight);
  9093.   end;
  9094.   if (CropLeft <= CropRight) then
  9095.   begin
  9096.     // Find top edge
  9097.     WasTransparent := True;
  9098.     while (CropTop <= CropBottom) and (WasTransparent) do
  9099.     begin
  9100.       for i := CropLeft to CropRight do
  9101.         if (pixels[i, CropTop] <> TransparentColorIndex) then
  9102.         begin
  9103.           WasTransparent := False;
  9104.           break;
  9105.         end;
  9106.       if (WasTransparent) then
  9107.         inc(CropTop);
  9108.     end;
  9109.     // Find bottom edge
  9110.     WasTransparent := True;
  9111.     while (CropTop <= CropBottom) and (WasTransparent) do
  9112.     begin
  9113.       for i := CropLeft to CropRight do
  9114.         if (pixels[i, CropBottom] <> TransparentColorIndex) then
  9115.         begin
  9116.           WasTransparent := False;
  9117.           break;
  9118.         end;
  9119.       if (WasTransparent) then
  9120.         dec(CropBottom);
  9121.     end;
  9122.   end;
  9123.  
  9124.   if (CropLeft > CropRight) or (CropTop > CropBottom) then
  9125.   begin
  9126.     // Cropped to nothing - frame is invisible
  9127.     Clear;
  9128.   end else
  9129.   begin
  9130.     // Crop frame - move data
  9131.     NewWidth := CropRight - CropLeft + 1;
  9132.     Newheight := CropBottom - CropTop + 1;
  9133.     NewSize := NewWidth * NewHeight;
  9134.     GetMem(NewData, NewSize);
  9135.     pSource := PAnsiChar(integer(FData) + CropTop * Width + CropLeft);
  9136.     pDest := NewData;
  9137.     for i := 0 to NewHeight-1 do
  9138.     begin
  9139.       Move(pSource^, pDest^, NewWidth);
  9140.       inc(pSource, Width);
  9141.       inc(pDest, NewWidth);
  9142.     end;
  9143.     FreeImage;
  9144.     FData := NewData;
  9145.     FDataSize := NewSize;
  9146.     inc(FImageDescriptor.Left, CropLeft);
  9147.     inc(FImageDescriptor.Top, CropTop);
  9148.     FImageDescriptor.Width := NewWidth;
  9149.     FImageDescriptor.Height := NewHeight;
  9150.     FreeBitmap;
  9151.     FreeMask
  9152.   end;
  9153. end;
  9154.  
  9155. procedure TGIFSubImage.Merge(Previous: TGIFSubImage);
  9156. var
  9157.   SourceIndex       ,
  9158.   DestIndex     : byte;
  9159.   SourceTransparent : boolean;
  9160.   NeedTransparentColorIndex: boolean;
  9161.   PreviousRect      ,
  9162.   ThisRect      ,
  9163.   MergeRect     : TRect;
  9164.   PreviousY     ,
  9165.   X         ,
  9166.   Y         : integer;
  9167.   pSource       ,
  9168.   pDest         : PAnsiChar;
  9169.   pSourceMap        ,
  9170.   pDestMap      : PColorMap;
  9171.   GCE           : TGIFGraphicControlExtension;
  9172.  
  9173.   function CanMakeTransparent: boolean;
  9174.   begin
  9175.     // Is there a local color map...
  9176.     if (ColorMap.Count > 0) then
  9177.       // ...and is there room in it?
  9178.       Result := (ColorMap.Count < 256)
  9179.     // Is there a global color map...
  9180.     else if (Image.GlobalColorMap.Count > 0) then
  9181.       // ...and is there room in it?
  9182.       Result := (Image.GlobalColorMap.Count < 256)
  9183.     else
  9184.       Result := False;
  9185.   end;
  9186.  
  9187.   function GetTransparentColorIndex: byte;
  9188.   var
  9189.     i           : integer;
  9190.   begin
  9191.     if (ColorMap.Count > 0) then
  9192.     begin
  9193.       // Get the transparent color from the local color map
  9194.       Result := ColorMap.Add(TColor(0));
  9195.     end else
  9196.     begin
  9197.       // Are any other frames using the global color map for transparency
  9198.       for i := 0 to Image.Images.Count-1 do
  9199.         if (Image.Images[i] <> self) and (Image.Images[i].Transparent) and
  9200.           (Image.Images[i].ColorMap.Count = 0) then
  9201.         begin
  9202.           // Use the same transparency color as the other frame
  9203.           Result := Image.Images[i].GraphicControlExtension.TransparentColorIndex;
  9204.           exit;
  9205.         end;
  9206.       // Get the transparent color from the global color map
  9207.       Result := Image.GlobalColorMap.Add(TColor(0));
  9208.     end;
  9209.   end;
  9210.  
  9211. begin
  9212.   // Determine if it is possible to merge this frame
  9213.   if (Empty) or (Previous = nil) or (Previous.Empty) or
  9214.     ((Previous.GraphicControlExtension <> nil) and
  9215.      (Previous.GraphicControlExtension.Disposal in [dmBackground, dmPrevious])) then
  9216.     exit;
  9217.  
  9218.   PreviousRect := Previous.BoundsRect;
  9219.   ThisRect := BoundsRect;
  9220.  
  9221.   // Cannot merge unless the frames intersect
  9222.   if (not IntersectRect(MergeRect, PreviousRect, ThisRect)) then
  9223.     exit;
  9224.  
  9225.   // If the frame isn't already transparent, determine
  9226.   // if it is possible to make it so
  9227.   if (Transparent) then
  9228.   begin
  9229.     DestIndex := GraphicControlExtension.TransparentColorIndex;
  9230.     NeedTransparentColorIndex := False;
  9231.   end else
  9232.   begin
  9233.     if (not CanMakeTransparent) then
  9234.       exit;
  9235.     DestIndex := 0; // To avoid compiler warning
  9236.     NeedTransparentColorIndex := True;
  9237.   end;
  9238.  
  9239.   SourceTransparent := Previous.Transparent;
  9240.   if (SourceTransparent) then
  9241.     SourceIndex := Previous.GraphicControlExtension.TransparentColorIndex
  9242.   else
  9243.     SourceIndex := 0; // To avoid compiler warning
  9244.  
  9245.   PreviousY := MergeRect.Top - Previous.Top;
  9246.  
  9247.   pSourceMap := Previous.ActiveColorMap.Data;
  9248.   pDestMap := ActiveColorMap.Data;
  9249.  
  9250.   for Y := MergeRect.Top - Top to MergeRect.Bottom - Top-1 do
  9251.   begin
  9252.     pSource := PAnsiChar(integer(Previous.Scanline[PreviousY]) + MergeRect.Left - Previous.Left);
  9253.     pDest := PAnsiChar(integer(Scanline[Y]) + MergeRect.Left - Left);
  9254.  
  9255.     for X := MergeRect.Left to MergeRect.Right-1 do
  9256.     begin
  9257.       // Ignore pixels if either this frame's or the previous frame's pixel is transparent
  9258.       if (
  9259.             not(
  9260.               ((not NeedTransparentColorIndex) and (pDest^ = AnsiChar(DestIndex))) or
  9261.               ((SourceTransparent) and (pSource^ = AnsiChar(SourceIndex)))
  9262.             )
  9263.           ) and (
  9264.             // Replace same colored pixels with transparency
  9265.             ((pDestMap = pSourceMap) and (pDest^ = pSource^)) or
  9266.             (CompareMem(@(pDestMap^[ord(pDest^)]), @(pSourceMap^[ord(pSource^)]), sizeof(TGIFColor)))
  9267.           ) then
  9268.       begin
  9269.         if (NeedTransparentColorIndex) then
  9270.         begin
  9271.           NeedTransparentColorIndex := False;
  9272.           DestIndex := GetTransparentColorIndex;
  9273.         end;
  9274.         pDest^ := AnsiChar(DestIndex);
  9275.       end;
  9276.       inc(pDest);
  9277.       inc(pSource);
  9278.     end;
  9279.     inc(PreviousY);
  9280.   end;
  9281.  
  9282.   (*
  9283.   ** Create a GCE if the frame wasn't already transparent and any
  9284.   ** pixels were made transparent
  9285.   *)
  9286.   if (not Transparent) and (not NeedTransparentColorIndex) then
  9287.   begin
  9288.     if (GraphicControlExtension = nil) then
  9289.     begin
  9290.       GCE := TGIFGraphicControlExtension.Create(self);
  9291.       Extensions.Add(GCE);
  9292.     end else
  9293.       GCE := GraphicControlExtension;
  9294.     GCE.Transparent := True;
  9295.     GCE.TransparentColorIndex := DestIndex;
  9296.   end;
  9297.  
  9298.   FreeBitmap;
  9299.   FreeMask
  9300. end;
  9301.  
  9302. ////////////////////////////////////////////////////////////////////////////////
  9303. //
  9304. //          TGIFTrailer
  9305. //
  9306. ////////////////////////////////////////////////////////////////////////////////
  9307. procedure TGIFTrailer.SaveToStream(Stream: TStream);
  9308. begin
  9309.   WriteByte(Stream, bsTrailer);
  9310. end;
  9311.  
  9312. procedure TGIFTrailer.LoadFromStream(Stream: TStream);
  9313. var
  9314.   b         : BYTE;
  9315. begin
  9316.   if (Stream.Read(b, 1) <> 1) then
  9317.     exit;
  9318.   if (b <> bsTrailer) then
  9319.     Warning(gsWarning, sBadTrailer);
  9320. end;
  9321.  
  9322. ////////////////////////////////////////////////////////////////////////////////
  9323. //
  9324. //      TGIFExtension registration database
  9325. //
  9326. ////////////////////////////////////////////////////////////////////////////////
  9327. type
  9328.   TExtensionLeadIn = packed record
  9329.     Introducer: byte;      { always $21 }
  9330.     ExtensionLabel: byte;
  9331.   end;
  9332.  
  9333.   PExtRec = ^TExtRec;
  9334.   TExtRec = record
  9335.     ExtClass: TGIFExtensionClass;
  9336.     ExtLabel: BYTE;
  9337.   end;
  9338.  
  9339.   TExtensionList = class(TList)
  9340.   public
  9341.     constructor Create;
  9342.     destructor Destroy; override;
  9343.     procedure Add(eLabel: BYTE; eClass: TGIFExtensionClass);
  9344.     function FindExt(eLabel: BYTE): TGIFExtensionClass;
  9345.     procedure Remove(eClass: TGIFExtensionClass);
  9346.   end;
  9347.  
  9348. constructor TExtensionList.Create;
  9349. begin
  9350.   inherited Create;
  9351.   Add(bsPlainTextExtension, TGIFTextExtension);
  9352.   Add(bsGraphicControlExtension, TGIFGraphicControlExtension);
  9353.   Add(bsCommentExtension, TGIFCommentExtension);
  9354.   Add(bsApplicationExtension, TGIFApplicationExtension);
  9355. end;
  9356.  
  9357. destructor TExtensionList.Destroy;
  9358. var
  9359.   I: Integer;
  9360. begin
  9361.   for I := 0 to Count-1 do
  9362.     Dispose(PExtRec(Items[I]));
  9363.   inherited Destroy;
  9364. end;
  9365.  
  9366. procedure TExtensionList.Add(eLabel: BYTE; eClass: TGIFExtensionClass);
  9367. var
  9368.   NewRec: PExtRec;
  9369. begin
  9370.   New(NewRec);
  9371.   with NewRec^ do
  9372.   begin
  9373.     ExtLabel := eLabel;
  9374.     ExtClass := eClass;
  9375.   end;
  9376.   inherited Add(NewRec);
  9377. end;
  9378.  
  9379. function TExtensionList.FindExt(eLabel: BYTE): TGIFExtensionClass;
  9380. var
  9381.   I: Integer;
  9382. begin
  9383.   for I := Count-1 downto 0 do
  9384.     with PExtRec(Items[I])^ do
  9385.       if ExtLabel = eLabel then
  9386.       begin
  9387.         Result := ExtClass;
  9388.         Exit;
  9389.       end;
  9390.   Result := nil;
  9391. end;
  9392.  
  9393. procedure TExtensionList.Remove(eClass: TGIFExtensionClass);
  9394. var
  9395.   I: Integer;
  9396.   P: PExtRec;
  9397. begin
  9398.   for I := Count-1 downto 0 do
  9399.   begin
  9400.     P := PExtRec(Items[I]);
  9401.     if P^.ExtClass.InheritsFrom(eClass) then
  9402.     begin
  9403.       Dispose(P);
  9404.       Delete(I);
  9405.     end;
  9406.   end;
  9407. end;
  9408.  
  9409. var
  9410.   ExtensionList: TExtensionList = nil;
  9411.  
  9412. function GetExtensionList: TExtensionList;
  9413. begin
  9414.   if (ExtensionList = nil) then
  9415.     ExtensionList := TExtensionList.Create;
  9416.   Result := ExtensionList;
  9417. end;
  9418.  
  9419. ////////////////////////////////////////////////////////////////////////////////
  9420. //
  9421. //          TGIFExtension
  9422. //
  9423. ////////////////////////////////////////////////////////////////////////////////
  9424. function TGIFExtension.GetVersion: TGIFVersion;
  9425. begin
  9426.   Result := gv89a;
  9427. end;
  9428.  
  9429. class procedure TGIFExtension.RegisterExtension(eLabel: BYTE; eClass: TGIFExtensionClass);
  9430. begin
  9431.   GetExtensionList.Add(eLabel, eClass);
  9432. end;
  9433.  
  9434. class function TGIFExtension.FindExtension(Stream: TStream): TGIFExtensionClass;
  9435. var
  9436.   eLabel        : BYTE;
  9437.   SubClass      : TGIFExtensionClass;
  9438.   Pos           : LongInt;
  9439. begin
  9440.   Pos := Stream.Position;
  9441.   if (Stream.Read(eLabel, 1) <> 1) then
  9442.   begin
  9443.     Result := nil;
  9444.     exit;
  9445.   end;
  9446.   Result := GetExtensionList.FindExt(eLabel);
  9447.   while (Result <> nil) do
  9448.   begin
  9449.     SubClass := Result.FindSubExtension(Stream);
  9450.     if (SubClass = Result) then
  9451.       break;
  9452.     Result := SubClass;
  9453.   end;
  9454.   Stream.Position := Pos;
  9455. end;
  9456.  
  9457. class function TGIFExtension.FindSubExtension(Stream: TStream): TGIFExtensionClass;
  9458. begin
  9459.   Result := self;
  9460. end;
  9461.  
  9462. constructor TGIFExtension.Create(ASubImage: TGIFSubImage);
  9463. begin
  9464.   inherited Create(ASubImage.Image);
  9465.   FSubImage := ASubImage;
  9466. end;
  9467.  
  9468. destructor TGIFExtension.Destroy;
  9469. begin
  9470.   if (FSubImage <> nil) then
  9471.     FSubImage.Extensions.Remove(self);
  9472.   inherited Destroy;
  9473. end;
  9474.  
  9475. procedure TGIFExtension.SaveToStream(Stream: TStream);
  9476. var
  9477.   ExtensionLeadIn   : TExtensionLeadIn;
  9478. begin
  9479.   ExtensionLeadIn.Introducer := bsExtensionIntroducer;
  9480.   ExtensionLeadIn.ExtensionLabel := ExtensionType;
  9481.   Stream.Write(ExtensionLeadIn, sizeof(ExtensionLeadIn));
  9482. end;
  9483.  
  9484. function TGIFExtension.DoReadFromStream(Stream: TStream): TGIFExtensionType;
  9485. var
  9486.   ExtensionLeadIn   : TExtensionLeadIn;
  9487. begin
  9488.   ReadCheck(Stream, ExtensionLeadIn, sizeof(ExtensionLeadIn));
  9489.   if (ExtensionLeadIn.Introducer <> bsExtensionIntroducer) then
  9490.     Error(sBadExtensionLabel);
  9491.   Result := ExtensionLeadIn.ExtensionLabel;
  9492. end;
  9493.  
  9494. procedure TGIFExtension.LoadFromStream(Stream: TStream);
  9495. begin
  9496.   // Seek past lead-in
  9497.   // Stream.Seek(sizeof(TExtensionLeadIn), soFromCurrent);
  9498.   if (DoReadFromStream(Stream) <> ExtensionType) then
  9499.     Error(sBadExtensionInstance);
  9500. end;
  9501.  
  9502. ////////////////////////////////////////////////////////////////////////////////
  9503. //
  9504. //          TGIFGraphicControlExtension
  9505. //
  9506. ////////////////////////////////////////////////////////////////////////////////
  9507. const
  9508.   { Extension flag bit masks }
  9509.   efInputFlag       = $02;      { 00000010 }
  9510.   efDisposal        = $1C;      { 00011100 }
  9511.   efTransparent     = $01;      { 00000001 }
  9512.   efReserved        = $E0;      { 11100000 }
  9513.  
  9514. constructor TGIFGraphicControlExtension.Create(ASubImage: TGIFSubImage);
  9515. begin
  9516.   inherited Create(ASubImage);
  9517.  
  9518.   FGCExtension.BlockSize := 4;
  9519.   FGCExtension.PackedFields := $00;
  9520.   FGCExtension.DelayTime := 0;
  9521.   FGCExtension.TransparentColorIndex := 0;
  9522.   FGCExtension.Terminator := 0;
  9523.   if (ASubImage.FGCE = nil) then
  9524.     ASubImage.FGCE := self;
  9525. end;
  9526.  
  9527. destructor TGIFGraphicControlExtension.Destroy;
  9528. begin
  9529.   // Clear transparent flag in sub image
  9530.   if (Transparent) then
  9531.     SubImage.FTransparent := False;
  9532.  
  9533.   if (SubImage.FGCE = self) then
  9534.     SubImage.FGCE := nil;
  9535.  
  9536.   inherited Destroy;
  9537. end;
  9538.  
  9539. function TGIFGraphicControlExtension.GetExtensionType: TGIFExtensionType;
  9540. begin
  9541.   Result := bsGraphicControlExtension;
  9542. end;
  9543.  
  9544. function TGIFGraphicControlExtension.GetTransparent: boolean;
  9545. begin
  9546.   Result := (FGCExtension.PackedFields AND efTransparent) <> 0;
  9547. end;
  9548.  
  9549. procedure TGIFGraphicControlExtension.SetTransparent(Value: boolean);
  9550. begin
  9551.   // Set transparent flag in sub image
  9552.   SubImage.FTransparent := Value;
  9553.   if (Value) then
  9554.     FGCExtension.PackedFields := FGCExtension.PackedFields OR efTransparent
  9555.   else
  9556.     FGCExtension.PackedFields := FGCExtension.PackedFields AND NOT(efTransparent);
  9557. end;
  9558.  
  9559. function TGIFGraphicControlExtension.GetTransparentColor: TColor;
  9560. begin
  9561.   Result := SubImage.ActiveColorMap[TransparentColorIndex];
  9562. end;
  9563.  
  9564. procedure TGIFGraphicControlExtension.SetTransparentColor(Color: TColor);
  9565. begin
  9566.   FGCExtension.TransparentColorIndex := Subimage.ActiveColorMap.AddUnique(Color);
  9567. end;
  9568.  
  9569. function TGIFGraphicControlExtension.GetTransparentColorIndex: BYTE;
  9570. begin
  9571.   Result := FGCExtension.TransparentColorIndex;
  9572. end;
  9573.  
  9574. procedure TGIFGraphicControlExtension.SetTransparentColorIndex(Value: BYTE);
  9575. begin
  9576.   if ((Value >= SubImage.ActiveColorMap.Count) and (SubImage.ActiveColorMap.Count > 0)) then
  9577.   begin
  9578.     Warning(gsWarning, sBadColorIndex);
  9579.     Value := 0;
  9580.   end;
  9581.   FGCExtension.TransparentColorIndex := Value;
  9582. end;
  9583.  
  9584. function TGIFGraphicControlExtension.GetDelay: WORD;
  9585. begin
  9586.   Result := FGCExtension.DelayTime;
  9587. end;
  9588. procedure TGIFGraphicControlExtension.SetDelay(Value: WORD);
  9589. begin
  9590.   FGCExtension.DelayTime := Value;
  9591. end;
  9592.  
  9593. function TGIFGraphicControlExtension.GetUserInput: boolean;
  9594. begin
  9595.   Result := (FGCExtension.PackedFields AND efInputFlag) <> 0;
  9596. end;
  9597.  
  9598. procedure TGIFGraphicControlExtension.SetUserInput(Value: boolean);
  9599. begin
  9600.   if (Value) then
  9601.     FGCExtension.PackedFields := FGCExtension.PackedFields OR efInputFlag
  9602.   else
  9603.     FGCExtension.PackedFields := FGCExtension.PackedFields AND NOT(efInputFlag);
  9604. end;
  9605.  
  9606. function TGIFGraphicControlExtension.GetDisposal: TDisposalMethod;
  9607. begin
  9608.   Result := TDisposalMethod((FGCExtension.PackedFields AND efDisposal) SHR 2);
  9609. end;
  9610.  
  9611. procedure TGIFGraphicControlExtension.SetDisposal(Value: TDisposalMethod);
  9612. begin
  9613.   FGCExtension.PackedFields := FGCExtension.PackedFields AND NOT(efDisposal)
  9614.     OR ((ord(Value) SHL 2) AND efDisposal);
  9615. end;
  9616.  
  9617. procedure TGIFGraphicControlExtension.SaveToStream(Stream: TStream);
  9618. begin
  9619.   inherited SaveToStream(Stream);
  9620.   Stream.Write(FGCExtension, sizeof(FGCExtension));
  9621. end;
  9622.  
  9623. procedure TGIFGraphicControlExtension.LoadFromStream(Stream: TStream);
  9624. begin
  9625.   inherited LoadFromStream(Stream);
  9626.   if (Stream.Read(FGCExtension, sizeof(FGCExtension)) <> sizeof(FGCExtension)) then
  9627.   begin
  9628.     Warning(gsWarning, sOutOfData);
  9629.     exit;
  9630.   end;
  9631.   // Set transparent flag in sub image
  9632.   if (Transparent) then
  9633.     SubImage.FTransparent := True;
  9634. end;
  9635.  
  9636. ////////////////////////////////////////////////////////////////////////////////
  9637. //
  9638. //          TGIFTextExtension
  9639. //
  9640. ////////////////////////////////////////////////////////////////////////////////
  9641. constructor TGIFTextExtension.Create(ASubImage: TGIFSubImage);
  9642. begin
  9643.   inherited Create(ASubImage);
  9644.   FText := TStringList.Create;
  9645.   FPlainTextExtension.BlockSize := 12;
  9646.   FPlainTextExtension.Left := 0;
  9647.   FPlainTextExtension.Top := 0;
  9648.   FPlainTextExtension.Width := 0;
  9649.   FPlainTextExtension.Height := 0;
  9650.   FPlainTextExtension.CellWidth := 0;
  9651.   FPlainTextExtension.CellHeight := 0;
  9652.   FPlainTextExtension.TextFGColorIndex := 0;
  9653.   FPlainTextExtension.TextBGColorIndex := 0;
  9654. end;
  9655.  
  9656. destructor TGIFTextExtension.Destroy;
  9657. begin
  9658.   FText.Free;
  9659.   inherited Destroy;
  9660. end;
  9661.  
  9662. function TGIFTextExtension.GetExtensionType: TGIFExtensionType;
  9663. begin
  9664.   Result := bsPlainTextExtension;
  9665. end;
  9666.  
  9667. function TGIFTextExtension.GetForegroundColor: TColor;
  9668. begin
  9669.   Result := SubImage.ColorMap[ForegroundColorIndex];
  9670. end;
  9671.  
  9672. procedure TGIFTextExtension.SetForegroundColor(Color: TColor);
  9673. begin
  9674.   ForegroundColorIndex := SubImage.ActiveColorMap.AddUnique(Color);
  9675. end;
  9676.  
  9677. function TGIFTextExtension.GetBackgroundColor: TColor;
  9678. begin
  9679.   Result := SubImage.ActiveColorMap[BackgroundColorIndex];
  9680. end;
  9681.  
  9682. procedure TGIFTextExtension.SetBackgroundColor(Color: TColor);
  9683. begin
  9684.   BackgroundColorIndex := SubImage.ColorMap.AddUnique(Color);
  9685. end;
  9686.  
  9687. function TGIFTextExtension.GetBounds(Index: integer): WORD;
  9688. begin
  9689.   case (Index) of
  9690.     1: Result := FPlainTextExtension.Left;
  9691.     2: Result := FPlainTextExtension.Top;
  9692.     3: Result := FPlainTextExtension.Width;
  9693.     4: Result := FPlainTextExtension.Height;
  9694.   else
  9695.     Result := 0; // To avoid compiler warnings
  9696.   end;
  9697. end;
  9698.  
  9699. procedure TGIFTextExtension.SetBounds(Index: integer; Value: WORD);
  9700. begin
  9701.   case (Index) of
  9702.     1: FPlainTextExtension.Left := Value;
  9703.     2: FPlainTextExtension.Top := Value;
  9704.     3: FPlainTextExtension.Width := Value;
  9705.     4: FPlainTextExtension.Height := Value;
  9706.   end;
  9707. end;
  9708.  
  9709. function TGIFTextExtension.GetCharWidthHeight(Index: integer): BYTE;
  9710. begin
  9711.   case (Index) of
  9712.     1: Result := FPlainTextExtension.CellWidth;
  9713.     2: Result := FPlainTextExtension.CellHeight;
  9714.   else
  9715.     Result := 0; // To avoid compiler warnings
  9716.   end;
  9717. end;
  9718.  
  9719. procedure TGIFTextExtension.SetCharWidthHeight(Index: integer; Value: BYTE);
  9720. begin
  9721.   case (Index) of
  9722.     1: FPlainTextExtension.CellWidth := Value;
  9723.     2: FPlainTextExtension.CellHeight := Value;
  9724.   end;
  9725. end;
  9726.  
  9727. function TGIFTextExtension.GetColorIndex(Index: integer): BYTE;
  9728. begin
  9729.   case (Index) of
  9730.     1: Result := FPlainTextExtension.TextFGColorIndex;
  9731.     2: Result := FPlainTextExtension.TextBGColorIndex;
  9732.   else
  9733.     Result := 0; // To avoid compiler warnings
  9734.   end;
  9735. end;
  9736.  
  9737. procedure TGIFTextExtension.SetColorIndex(Index: integer; Value: BYTE);
  9738. begin
  9739.   case (Index) of
  9740.     1: FPlainTextExtension.TextFGColorIndex := Value;
  9741.     2: FPlainTextExtension.TextBGColorIndex := Value;
  9742.   end;
  9743. end;
  9744.  
  9745. procedure TGIFTextExtension.SaveToStream(Stream: TStream);
  9746. begin
  9747.   inherited SaveToStream(Stream);
  9748.   Stream.Write(FPlainTextExtension, sizeof(FPlainTextExtension));
  9749.   WriteStrings(Stream, FText);
  9750. end;
  9751.  
  9752. procedure TGIFTextExtension.LoadFromStream(Stream: TStream);
  9753. begin
  9754.   inherited LoadFromStream(Stream);
  9755.   ReadCheck(Stream, FPlainTextExtension, sizeof(FPlainTextExtension));
  9756.   ReadStrings(Stream, FText);
  9757. end;
  9758.  
  9759. ////////////////////////////////////////////////////////////////////////////////
  9760. //
  9761. //          TGIFCommentExtension
  9762. //
  9763. ////////////////////////////////////////////////////////////////////////////////
  9764. constructor TGIFCommentExtension.Create(ASubImage: TGIFSubImage);
  9765. begin
  9766.   inherited Create(ASubImage);
  9767.   FText := TStringList.Create;
  9768. end;
  9769.  
  9770. destructor TGIFCommentExtension.Destroy;
  9771. begin
  9772.   FText.Free;
  9773.   inherited Destroy;
  9774. end;
  9775.  
  9776. function TGIFCommentExtension.GetExtensionType: TGIFExtensionType;
  9777. begin
  9778.   Result := bsCommentExtension;
  9779. end;
  9780.  
  9781. procedure TGIFCommentExtension.SaveToStream(Stream: TStream);
  9782. begin
  9783.   inherited SaveToStream(Stream);
  9784.   WriteStrings(Stream, FText);
  9785. end;
  9786.  
  9787. procedure TGIFCommentExtension.LoadFromStream(Stream: TStream);
  9788. begin
  9789.   inherited LoadFromStream(Stream);
  9790.   ReadStrings(Stream, FText);
  9791. end;
  9792.  
  9793. ////////////////////////////////////////////////////////////////////////////////
  9794. //
  9795. //      TGIFApplicationExtension registration database
  9796. //
  9797. ////////////////////////////////////////////////////////////////////////////////
  9798. type
  9799.   PAppExtRec = ^TAppExtRec;
  9800.   TAppExtRec = record
  9801.     AppClass: TGIFAppExtensionClass;
  9802.     Ident: TGIFApplicationRec;
  9803.   end;
  9804.  
  9805.   TAppExtensionList = class(TList)
  9806.   public
  9807.     constructor Create;
  9808.     destructor Destroy; override;
  9809.     procedure Add(eIdent: TGIFApplicationRec; eClass: TGIFAppExtensionClass);
  9810.     function FindExt(eIdent: TGIFApplicationRec): TGIFAppExtensionClass;
  9811.     procedure Remove(eClass: TGIFAppExtensionClass);
  9812.   end;
  9813.  
  9814. constructor TAppExtensionList.Create;
  9815. const
  9816.   NSLoopIdent: array[0..1] of TGIFApplicationRec =
  9817.     ((Identifier: 'NETSCAPE'; Authentication: '2.0'),
  9818.      (Identifier: 'ANIMEXTS'; Authentication: '1.0'));
  9819. begin
  9820.   inherited Create;
  9821.   Add(NSLoopIdent[0], TGIFAppExtNSLoop);
  9822.   Add(NSLoopIdent[1], TGIFAppExtNSLoop);
  9823. end;
  9824.  
  9825. destructor TAppExtensionList.Destroy;
  9826. var
  9827.   I: Integer;
  9828. begin
  9829.   for I := 0 to Count-1 do
  9830.     Dispose(PAppExtRec(Items[I]));
  9831.   inherited Destroy;
  9832. end;
  9833.  
  9834. procedure TAppExtensionList.Add(eIdent: TGIFApplicationRec; eClass: TGIFAppExtensionClass);
  9835. var
  9836.   NewRec: PAppExtRec;
  9837. begin
  9838.   New(NewRec);
  9839.   NewRec^.Ident := eIdent;
  9840.   NewRec^.AppClass := eClass;
  9841.   inherited Add(NewRec);
  9842. end;
  9843.  
  9844. function TAppExtensionList.FindExt(eIdent: TGIFApplicationRec): TGIFAppExtensionClass;
  9845. var
  9846.   I: Integer;
  9847. begin
  9848.   for I := Count-1 downto 0 do
  9849.     with PAppExtRec(Items[I])^ do
  9850.       if CompareMem(@Ident, @eIdent, sizeof(TGIFApplicationRec)) then
  9851.       begin
  9852.         Result := AppClass;
  9853.         Exit;
  9854.       end;
  9855.   Result := nil;
  9856. end;
  9857.  
  9858. procedure TAppExtensionList.Remove(eClass: TGIFAppExtensionClass);
  9859. var
  9860.   I: Integer;
  9861.   P: PAppExtRec;
  9862. begin
  9863.   for I := Count-1 downto 0 do
  9864.   begin
  9865.     P := PAppExtRec(Items[I]);
  9866.     if P^.AppClass.InheritsFrom(eClass) then
  9867.     begin
  9868.       Dispose(P);
  9869.       Delete(I);
  9870.     end;
  9871.   end;
  9872. end;
  9873.  
  9874. var
  9875.   AppExtensionList: TAppExtensionList = nil;
  9876.  
  9877. function GetAppExtensionList: TAppExtensionList;
  9878. begin
  9879.   if (AppExtensionList = nil) then
  9880.     AppExtensionList := TAppExtensionList.Create;
  9881.   Result := AppExtensionList;
  9882. end;
  9883.  
  9884. class procedure TGIFApplicationExtension.RegisterExtension(eIdent: TGIFApplicationRec;
  9885.   eClass: TGIFAppExtensionClass);
  9886. begin
  9887.   GetAppExtensionList.Add(eIdent, eClass);
  9888. end;
  9889.  
  9890. class function TGIFApplicationExtension.FindSubExtension(Stream: TStream): TGIFExtensionClass;
  9891. var
  9892.   eIdent        : TGIFApplicationRec;
  9893.   OldPos        : longInt;
  9894.   Size          : BYTE;
  9895. begin
  9896.   OldPos := Stream.Position;
  9897.   Result := nil;
  9898.   if (Stream.Read(Size, 1) <> 1) then
  9899.     exit;
  9900.  
  9901.   // Some old Adobe export filters mistakenly uses a value of 10
  9902.   if (Size = 10) then
  9903.   begin
  9904.     { TODO -oanme -cImprovement : replace with seek or read and check contents = 'Adobe' }
  9905.     if (Stream.Read(eIdent, 10) <> 10) then
  9906.       exit;
  9907.     Result := TGIFUnknownAppExtension;
  9908.     exit;
  9909.   end else
  9910.   if (Size <> sizeof(TGIFApplicationRec)) or
  9911.     (Stream.Read(eIdent, sizeof(eIdent)) <> sizeof(eIdent)) then
  9912.   begin
  9913.     Stream.Position := OldPos;
  9914.     Result := inherited FindSubExtension(Stream);
  9915.   end else
  9916.   begin
  9917.     Result := GetAppExtensionList.FindExt(eIdent);
  9918.     if (Result = nil) then
  9919.       Result := TGIFUnknownAppExtension;
  9920.   end;
  9921. end;
  9922.  
  9923. ////////////////////////////////////////////////////////////////////////////////
  9924. //
  9925. //          TGIFApplicationExtension
  9926. //
  9927. ////////////////////////////////////////////////////////////////////////////////
  9928. constructor TGIFApplicationExtension.Create(ASubImage: TGIFSubImage);
  9929. begin
  9930.   inherited Create(ASubImage);
  9931.   FillChar(FIdent, sizeof(FIdent), 0);
  9932. end;
  9933.  
  9934. destructor TGIFApplicationExtension.Destroy;
  9935. begin
  9936.   inherited Destroy;
  9937. end;
  9938.  
  9939. function TGIFApplicationExtension.GetExtensionType: TGIFExtensionType;
  9940. begin
  9941.   Result := bsApplicationExtension;
  9942. end;
  9943.  
  9944. function TGIFApplicationExtension.GetAuthentication: AnsiString;
  9945. begin
  9946.   Result := FIdent.Authentication;
  9947. end;
  9948.  
  9949. procedure TGIFApplicationExtension.SetAuthentication(const Value: AnsiString);
  9950. begin
  9951.   if (Length(Value) < sizeof(TGIFAuthenticationCode)) then
  9952.     FillChar(FIdent.Authentication, sizeof(TGIFAuthenticationCode), 32);
  9953.   StrLCopy(@(FIdent.Authentication[0]), PAnsiChar(Value), sizeof(TGIFAuthenticationCode));
  9954. end;
  9955.  
  9956. function TGIFApplicationExtension.GetIdentifier: AnsiString;
  9957. begin
  9958.   Result := FIdent.Identifier;
  9959. end;
  9960.  
  9961. procedure TGIFApplicationExtension.SetIdentifier(const Value: AnsiString);
  9962. begin
  9963.   if (Length(Value) < sizeof(TGIFIdentifierCode)) then
  9964.     FillChar(FIdent.Identifier, sizeof(TGIFIdentifierCode), 32);
  9965.   StrLCopy(@(FIdent.Identifier[0]), PAnsiChar(Value), sizeof(TGIFIdentifierCode));
  9966. end;
  9967.  
  9968. procedure TGIFApplicationExtension.SaveToStream(Stream: TStream);
  9969. begin
  9970.   inherited SaveToStream(Stream);
  9971.   WriteByte(Stream, sizeof(FIdent)); // Block size
  9972.   Stream.Write(FIdent, sizeof(FIdent));
  9973.   SaveData(Stream);
  9974. end;
  9975.  
  9976. procedure TGIFApplicationExtension.LoadFromStream(Stream: TStream);
  9977. var
  9978.   i         : integer;
  9979. begin
  9980.   inherited LoadFromStream(Stream);
  9981.   i := ReadByte(Stream);
  9982.   // Some old Adobe export filters mistakenly uses a value of 10
  9983.   if (i = 10) then
  9984.     FillChar(FIdent, sizeOf(FIdent), 0)
  9985.   else
  9986.     if (i < 11) then
  9987.       Error(sBadBlockSize);
  9988.  
  9989.   ReadCheck(Stream, FIdent, sizeof(FIdent));
  9990.  
  9991.   Dec(i, sizeof(FIdent));
  9992.   // Ignore extra data
  9993.   Stream.Seek(i, soFromCurrent);
  9994.  
  9995.   // ***FIXME***
  9996.   // If self class is TGIFApplicationExtension, this will cause an "abstract
  9997.   // error".
  9998.   // TGIFApplicationExtension.LoadData should read and ignore rest of block.
  9999.   LoadData(Stream);
  10000. end;
  10001.  
  10002. ////////////////////////////////////////////////////////////////////////////////
  10003. //
  10004. //          TGIFUnknownAppExtension
  10005. //
  10006. ////////////////////////////////////////////////////////////////////////////////
  10007. constructor TGIFBlock.Create(ASize: integer);
  10008. begin
  10009.   inherited Create;
  10010.   FSize := ASize;
  10011.   GetMem(FData, FSize);
  10012.   FillChar(FData^, FSize, 0);
  10013. end;
  10014.  
  10015. destructor TGIFBlock.Destroy;
  10016. begin
  10017.   FreeMem(FData);
  10018.   inherited Destroy;
  10019. end;
  10020.  
  10021. procedure TGIFBlock.SaveToStream(Stream: TStream);
  10022. begin
  10023.   Stream.Write(FSize, 1);
  10024.   Stream.Write(FData^, FSize);
  10025. end;
  10026.  
  10027. procedure TGIFBlock.LoadFromStream(Stream: TStream);
  10028. begin
  10029.   ReadCheck(Stream, FData^, FSize);
  10030. end;
  10031.  
  10032. constructor TGIFUnknownAppExtension.Create(ASubImage: TGIFSubImage);
  10033. begin
  10034.   inherited Create(ASubImage);
  10035.   FBlocks := TList.Create;
  10036. end;
  10037.  
  10038. destructor TGIFUnknownAppExtension.Destroy;
  10039. var
  10040.   i         : integer;
  10041. begin
  10042.   for i := 0 to FBlocks.Count-1 do
  10043.     TGIFBlock(FBlocks[i]).Free;
  10044.   FBlocks.Free;
  10045.   inherited Destroy;
  10046. end;
  10047.  
  10048.  
  10049. procedure TGIFUnknownAppExtension.SaveData(Stream: TStream);
  10050. var
  10051.   i         : integer;
  10052. begin
  10053.   for i := 0 to FBlocks.Count-1 do
  10054.     TGIFBlock(FBlocks[i]).SaveToStream(Stream);
  10055.   // Terminating zero
  10056.   WriteByte(Stream, 0);
  10057. end;
  10058.  
  10059. procedure TGIFUnknownAppExtension.LoadData(Stream: TStream);
  10060. var
  10061.   b         : BYTE;
  10062.   Block         : TGIFBlock;
  10063.   i         : integer;
  10064. begin
  10065.   // Zap old blocks
  10066.   for i := 0 to FBlocks.Count-1 do
  10067.     TGIFBlock(FBlocks[i]).Free;
  10068.   FBlocks.Clear;
  10069.  
  10070.   // Read blocks
  10071.   if (Stream.Read(b, 1) <> 1) then
  10072.     exit;
  10073.   while (b <> 0) do
  10074.   begin
  10075.     Block := TGIFBlock.Create(b);
  10076.     try
  10077.       Block.LoadFromStream(Stream);
  10078.     except
  10079.       Block.Free;
  10080.       raise;
  10081.     end;
  10082.     FBlocks.Add(Block);
  10083.     if (Stream.Read(b, 1) <> 1) then
  10084.       exit;
  10085.   end;
  10086. end;
  10087.  
  10088. ////////////////////////////////////////////////////////////////////////////////
  10089. //
  10090. //                      TGIFAppExtNSLoop
  10091. //
  10092. ////////////////////////////////////////////////////////////////////////////////
  10093. const
  10094.   // Netscape sub block types
  10095.   nbLoopExtension   = 1;
  10096.   nbBufferExtension = 2;
  10097.  
  10098. constructor TGIFAppExtNSLoop.Create(ASubImage: TGIFSubImage);
  10099. const
  10100.   NSLoopIdent: TGIFApplicationRec = (Identifier: 'NETSCAPE'; Authentication: '2.0');
  10101. begin
  10102.   inherited Create(ASubImage);
  10103.   FIdent := NSLoopIdent;
  10104. end;
  10105.  
  10106. procedure TGIFAppExtNSLoop.SaveData(Stream: TStream);
  10107. begin
  10108.   // Write loop count
  10109.   WriteByte(Stream, 1 + sizeof(FLoops)); // Size of block
  10110.   WriteByte(Stream, nbLoopExtension); // Identify sub block as looping extension data
  10111.   Stream.Write(FLoops, sizeof(FLoops)); // Loop count
  10112.  
  10113.   // Write buffer size if specified
  10114.   if (FBufferSize > 0) then
  10115.   begin
  10116.     WriteByte(Stream, 1 + sizeof(FBufferSize)); // Size of block
  10117.     WriteByte(Stream, nbBufferExtension); // Identify sub block as buffer size data
  10118.     Stream.Write(FBufferSize, sizeof(FBufferSize)); // Buffer size
  10119.   end;
  10120.  
  10121.   WriteByte(Stream, 0); // Terminating zero
  10122. end;
  10123.  
  10124. procedure TGIFAppExtNSLoop.LoadData(Stream: TStream);
  10125. var
  10126.   BlockSize     : integer;
  10127.   BlockType     : integer;
  10128. begin
  10129.   // Read size of first block or terminating zero
  10130.   BlockSize := ReadByte(Stream);
  10131.   while (BlockSize <> 0) do
  10132.   begin
  10133.     BlockType := ReadByte(Stream);
  10134.     dec(BlockSize);
  10135.  
  10136.     case (BlockType AND $07) of
  10137.       nbLoopExtension:
  10138.         begin
  10139.           if (BlockSize < sizeof(FLoops)) then
  10140.             Error(sInvalidData);
  10141.           // Read loop count
  10142.           ReadCheck(Stream, FLoops, sizeof(FLoops));
  10143.           dec(BlockSize, sizeof(FLoops));
  10144.         end;
  10145.       nbBufferExtension:
  10146.         begin
  10147.           if (BlockSize < sizeof(FBufferSize)) then
  10148.             Error(sInvalidData);
  10149.           // Read buffer size
  10150.           ReadCheck(Stream, FBufferSize, sizeof(FBufferSize));
  10151.           dec(BlockSize, sizeof(FBufferSize));
  10152.         end;
  10153.     end;
  10154.  
  10155.     // Skip/ignore unread data
  10156.     if (BlockSize > 0) then
  10157.       Stream.Seek(BlockSize, soFromCurrent);
  10158.  
  10159.     // Read size of next block or terminating zero
  10160.     BlockSize := ReadByte(Stream);
  10161.   end;
  10162. end;
  10163.  
  10164.  
  10165. ////////////////////////////////////////////////////////////////////////////////
  10166. //
  10167. //          TGIFImageList
  10168. //
  10169. ////////////////////////////////////////////////////////////////////////////////
  10170. function TGIFImageList.GetImage(Index: Integer): TGIFSubImage;
  10171. begin
  10172.   Result := TGIFSubImage(Items[Index]);
  10173. end;
  10174.  
  10175. procedure TGIFImageList.SetImage(Index: Integer; SubImage: TGIFSubImage);
  10176. begin
  10177.   Items[Index] := SubImage;
  10178. end;
  10179.  
  10180. procedure TGIFImageList.LoadFromStream(Stream: TStream; Parent: TObject);
  10181. var
  10182.   b         : BYTE;
  10183.   SubImage      : TGIFSubImage;
  10184. begin
  10185.   // Peek ahead to determine block type
  10186.   repeat
  10187.     if (Stream.Read(b, 1) <> 1) then
  10188.       exit;
  10189.   until (b <> 0); // Ignore 0 padding (non-compliant)
  10190.  
  10191.   while (b <> bsTrailer) do
  10192.   begin
  10193.     Stream.Seek(-1, soFromCurrent);
  10194.     if (b in [bsExtensionIntroducer, bsImageDescriptor]) then
  10195.     begin
  10196.       SubImage := TGIFSubImage.Create(Parent as TGIFImage);
  10197.       try
  10198.         SubImage.LoadFromStream(Stream);
  10199.         Add(SubImage);
  10200.         Image.Progress(Self, psRunning, MulDiv(Stream.Position, 100, Stream.Size),
  10201.           GIFImageRenderOnLoad, Rect(0,0,0,0), sProgressLoading);
  10202.       except
  10203.         SubImage.Free;
  10204.         raise;
  10205.       end;
  10206.     end else
  10207.     begin
  10208.       Warning(gsWarning, sBadBlock);
  10209.       break;
  10210.     end;
  10211.     repeat
  10212.       if (Stream.Read(b, 1) <> 1) then
  10213.         exit;
  10214.     until (b <> 0); // Ignore 0 padding (non-compliant)
  10215.   end;
  10216.   Stream.Seek(-1, soFromCurrent);
  10217. end;
  10218.  
  10219. procedure TGIFImageList.SaveToStream(Stream: TStream);
  10220. var
  10221.   i         : integer;
  10222. begin
  10223.   for i := 0 to Count-1 do
  10224.   begin
  10225.     TGIFItem(Items[i]).SaveToStream(Stream);
  10226.     Image.Progress(Self, psRunning, MulDiv((i+1), 100, Count), False, Rect(0,0,0,0), sProgressSaving);
  10227.   end;
  10228. end;
  10229.  
  10230. ////////////////////////////////////////////////////////////////////////////////
  10231. //
  10232. //          TGIFPainter
  10233. //
  10234. ////////////////////////////////////////////////////////////////////////////////
  10235. constructor TGIFPainter.CreateRef(Painter: PGIFPainter; AImage: TGIFImage;
  10236.   ACanvas: TCanvas; ARect: TRect; Options: TGIFDrawOptions);
  10237. begin
  10238.   Create(AImage, ACanvas, ARect, Options);
  10239.   PainterRef := Painter;
  10240.   if (PainterRef <> nil) then
  10241.     PainterRef^ := self;
  10242. end;
  10243.  
  10244. constructor TGIFPainter.Create(AImage: TGIFImage; ACanvas: TCanvas; ARect: TRect;
  10245.   Options: TGIFDrawOptions);
  10246. var
  10247.   i         : integer;
  10248.   BackgroundColor   : TColor;
  10249.   Disposals     : set of TDisposalMethod;
  10250. begin
  10251.   inherited Create(True);
  10252.   FreeOnTerminate := True;
  10253.   Onterminate := DoOnTerminate;
  10254.   FImage := AImage;
  10255.   FCanvas := ACanvas;
  10256.   FRect := ARect;
  10257.   FActiveImage := -1;
  10258.   FDrawOptions := Options;
  10259.   FStarted := False;
  10260.   BackupBuffer := nil;
  10261.   FrameBuffer := nil;
  10262.   Background := nil;
  10263.   FEventHandle := 0;
  10264.   // This should be a parameter, but I think I've got enough of them already...
  10265.   FAnimationSpeed := FImage.AnimationSpeed;
  10266.  
  10267.   // An event handle is used for animation delays
  10268.   if (FDrawOptions >= [goAnimate, goAsync]) and (FImage.Images.Count > 1) and
  10269.     (FAnimationSpeed >= 0) then
  10270.     FEventHandle := CreateEvent(nil, False, False, nil);
  10271.  
  10272.   // Preprocessing of extensions to determine if we need frame buffers
  10273.   Disposals := [];
  10274.   if (FImage.DrawBackgroundColor = clNone) then
  10275.   begin
  10276.     if (FImage.GlobalColorMap.Count > 0) then
  10277.       BackgroundColor := FImage.BackgroundColor
  10278.     else
  10279.       BackgroundColor := ColorToRGB(clWindow);
  10280.   end else
  10281.     BackgroundColor := ColorToRGB(FImage.DrawBackgroundColor);
  10282.  
  10283.   // Need background buffer to clear on loop
  10284.   if (goClearOnLoop in FDrawOptions) then
  10285.     Include(Disposals, dmBackground);
  10286.  
  10287.   for i := 0 to FImage.Images.Count-1 do
  10288.     if (FImage.Images[i].GraphicControlExtension <> nil) then
  10289.       with (FImage.Images[i].GraphicControlExtension) do
  10290.         Include(Disposals, Disposal);
  10291.  
  10292.   // Need background buffer to draw transparent on background
  10293.   if (dmBackground in Disposals) and (goTransparent in FDrawOptions) then
  10294.   begin
  10295.     Background := TBitmap.Create;
  10296.     Background.Height := FRect.Bottom-FRect.Top;
  10297.     Background.Width := FRect.Right-FRect.Left;
  10298.     // Copy background immediately
  10299.     Background.Canvas.CopyMode := cmSrcCopy;
  10300.     Background.Canvas.CopyRect(Background.Canvas.ClipRect, FCanvas, FRect);
  10301.   end;
  10302.   // Need frame- and backup buffer to restore to previous and background
  10303.   if ((Disposals * [dmPrevious, dmBackground]) <> []) then
  10304.   begin
  10305.     BackupBuffer := TBitmap.Create;
  10306.     BackupBuffer.Height := FRect.Bottom-FRect.Top;
  10307.     BackupBuffer.Width := FRect.Right-FRect.Left;
  10308.     BackupBuffer.Canvas.CopyMode := cmSrcCopy;
  10309.     BackupBuffer.Canvas.Brush.Color := BackgroundColor;
  10310.     BackupBuffer.Canvas.Brush.Style := bsSolid;
  10311. {$IFDEF DEBUG}
  10312.     BackupBuffer.Canvas.Brush.Color := clBlack;
  10313.     BackupBuffer.Canvas.Brush.Style := bsDiagCross;
  10314. {$ENDIF}
  10315.     // Step 1: Copy destination to backup buffer
  10316.     //         Always executed before first frame and only once.
  10317.     BackupBuffer.Canvas.CopyRect(BackupBuffer.Canvas.ClipRect, FCanvas, FRect);
  10318.     FrameBuffer := TBitmap.Create;
  10319.     FrameBuffer.Height := FRect.Bottom-FRect.Top;
  10320.     FrameBuffer.Width := FRect.Right-FRect.Left;
  10321.     FrameBuffer.Canvas.CopyMode := cmSrcCopy;
  10322.     FrameBuffer.Canvas.Brush.Color := BackgroundColor;
  10323.     FrameBuffer.Canvas.Brush.Style := bsSolid;
  10324. {$IFDEF DEBUG}
  10325.     FrameBuffer.Canvas.Brush.Color := clBlack;
  10326.     FrameBuffer.Canvas.Brush.Style := bsDiagCross;
  10327. {$ENDIF}
  10328.   end;
  10329. end;
  10330.  
  10331. destructor TGIFPainter.Destroy;
  10332. begin
  10333.   // OnTerminate isn't called if we are running in main thread, so we must call
  10334.   // it manually
  10335.   if not(goAsync in DrawOptions) then
  10336.     DoOnTerminate(self);
  10337.   // Reraise any exptions that were eaten in the Execute method
  10338.   if (ExceptObject <> nil) then
  10339.     raise ExceptObject at ExceptAddress;
  10340.   inherited Destroy;
  10341. end;
  10342.  
  10343. procedure TGIFPainter.SetAnimationSpeed(Value: integer);
  10344. begin
  10345.   if (Value < 0) then
  10346.     Value := 0
  10347.   else if (Value > 1000) then
  10348.     Value := 1000;
  10349.   if (Value <> FAnimationSpeed) then
  10350.   begin
  10351.     FAnimationSpeed := Value;
  10352.     // Signal WaitForSingleObject delay to abort
  10353.     if (FEventHandle <> 0) then
  10354.       SetEvent(FEventHandle)
  10355.     else
  10356.       DoRestart := True;
  10357.   end;
  10358. end;
  10359.  
  10360. procedure TGIFPainter.SetActiveImage(const Value: integer);
  10361. begin
  10362.   if (Value >= 0) and (Value < FImage.Images.Count) then
  10363.     FActiveImage := Value;
  10364. end;
  10365.  
  10366. // Conditional Synchronize
  10367. procedure TGIFPainter.DoSynchronize(Method: TThreadMethod);
  10368. begin
  10369.   if (Terminated) then
  10370.     exit;
  10371.   if (goAsync in FDrawOptions) then
  10372.     // Execute Synchronized if requested...
  10373.     Synchronize(Method)
  10374.   else
  10375.     // ...Otherwise just execute in current thread (probably main thread)
  10376.     Method;
  10377. end;
  10378.  
  10379. // Delete frame buffers - Executed in main thread
  10380. procedure TGIFPainter.DoOnTerminate(Sender: TObject);
  10381. begin
  10382.   // It shouldn't really be nescessary to protect PainterRef in this manner
  10383.   // since we are running in the main thread at this point, but I'm a little
  10384.   // paranoid about the way PainterRef is being used...
  10385.   if Image <> nil then  // 2001.02.23
  10386.   begin  // 2001.02.23
  10387.     with Image.Painters.LockList do
  10388.       try
  10389.         // Zap pointer to self and remove from painter list
  10390.         if (PainterRef <> nil) and (PainterRef^ = self) then
  10391.           PainterRef^ := nil;
  10392.       finally
  10393.         Image.Painters.UnLockList;
  10394.       end;
  10395.     Image.Painters.Remove(self);
  10396.     FImage := nil;
  10397.   end;  // 2001.02.23
  10398.  
  10399.   // Free buffers
  10400.   if (BackupBuffer <> nil) then
  10401.     BackupBuffer.Free;
  10402.   if (FrameBuffer <> nil) then
  10403.     FrameBuffer.Free;
  10404.   if (Background <> nil) then
  10405.     Background.Free;
  10406.  
  10407.   // Delete event handle
  10408.   if (FEventHandle <> 0) then
  10409.     CloseHandle(FEventHandle);
  10410. end;
  10411.  
  10412. // Event "dispatcher" - Executed in main thread
  10413. procedure TGIFPainter.DoEvent;
  10414. begin
  10415.   if (Assigned(FEvent)) then
  10416.     FEvent(self);
  10417. end;
  10418.  
  10419. // Non-buffered paint - Executed in main thread
  10420. procedure TGIFPainter.DoPaint;
  10421. begin
  10422.   FImage.Images[ActiveImage].Draw(FCanvas, FRect, (goTransparent in FDrawOptions),
  10423.     (goTile in FDrawOptions));
  10424.   FStarted := True;
  10425. end;
  10426.  
  10427. // Buffered paint - Executed in main thread
  10428. procedure TGIFPainter.DoPaintFrame;
  10429. var
  10430.   DrawDestination   : TCanvas;
  10431.   DrawRect      : TRect;
  10432.   DoStep2       ,
  10433.   DoStep3       ,
  10434.   DoStep5       ,
  10435.   DoStep6       : boolean;
  10436.   SavePal       ,
  10437.   SourcePal     : HPALETTE;
  10438.  
  10439.   procedure ClearBackup;
  10440.   var
  10441.     r           ,
  10442.     Tile        : TRect;
  10443.     FrameTop        ,
  10444.     FrameHeight     : integer;
  10445.     ImageWidth      ,
  10446.     ImageHeight     : integer;
  10447.   begin
  10448.  
  10449.     if (goTransparent in FDrawOptions) then
  10450.     begin
  10451.       // If the frame is transparent, we must remove it by copying the
  10452.       // background buffer over it
  10453.       if (goTile in FDrawOptions) then
  10454.       begin
  10455.         FrameTop := FImage.Images[ActiveImage].Top;
  10456.         FrameHeight := FImage.Images[ActiveImage].Height;
  10457.         ImageWidth := FImage.Width;
  10458.         ImageHeight := FImage.Height;
  10459.  
  10460.         Tile.Left := FRect.Left + FImage.Images[ActiveImage].Left;
  10461.         Tile.Right := Tile.Left + FImage.Images[ActiveImage].Width;
  10462.         while (Tile.Left < FRect.Right) do
  10463.         begin
  10464.           Tile.Top := FRect.Top + FrameTop;
  10465.           Tile.Bottom := Tile.Top + FrameHeight;
  10466.           while (Tile.Top < FRect.Bottom) do
  10467.           begin
  10468.             BackupBuffer.Canvas.CopyRect(Tile, Background.Canvas, Tile);
  10469.             Tile.Top := Tile.Top + ImageHeight;
  10470.             Tile.Bottom := Tile.Bottom + ImageHeight;
  10471.           end;
  10472.           Tile.Left := Tile.Left + ImageWidth;
  10473.           Tile.Right := Tile.Right + ImageWidth;
  10474.         end;
  10475.       end else
  10476.       begin
  10477.         r := FImage.Images[ActiveImage].ScaleRect(BackupBuffer.Canvas.ClipRect);
  10478.         BackupBuffer.Canvas.CopyRect(r, Background.Canvas, r)
  10479.       end;
  10480.     end else
  10481.     begin
  10482.       // If the frame isn't transparent, we just clear the area covered by
  10483.       // it to the background color.
  10484.       // Tile the background unless the frame covers all of the image
  10485.       if (goTile in FDrawOptions) and
  10486.         ((FImage.Width <> FImage.Images[ActiveImage].Width) and
  10487.          (FImage.height <> FImage.Images[ActiveImage].Height)) then
  10488.       begin
  10489.         FrameTop := FImage.Images[ActiveImage].Top;
  10490.         FrameHeight := FImage.Images[ActiveImage].Height;
  10491.         ImageWidth := FImage.Width;
  10492.         ImageHeight := FImage.Height;
  10493.         // ***FIXME*** I don't think this does any difference
  10494.         BackupBuffer.Canvas.Brush.Color := FImage.DrawBackgroundColor;
  10495.  
  10496.         Tile.Left := FRect.Left + FImage.Images[ActiveImage].Left;
  10497.         Tile.Right := Tile.Left + FImage.Images[ActiveImage].Width;
  10498.         while (Tile.Left < FRect.Right) do
  10499.         begin
  10500.           Tile.Top := FRect.Top + FrameTop;
  10501.           Tile.Bottom := Tile.Top + FrameHeight;
  10502.           while (Tile.Top < FRect.Bottom) do
  10503.           begin
  10504.             BackupBuffer.Canvas.FillRect(Tile);
  10505.  
  10506.             Tile.Top := Tile.Top + ImageHeight;
  10507.             Tile.Bottom := Tile.Bottom + ImageHeight;
  10508.           end;
  10509.           Tile.Left := Tile.Left + ImageWidth;
  10510.           Tile.Right := Tile.Right + ImageWidth;
  10511.         end;
  10512.       end else
  10513.         BackupBuffer.Canvas.FillRect(FImage.Images[ActiveImage].ScaleRect(FRect));
  10514.     end;
  10515.   end;
  10516.  
  10517. begin
  10518.   if (goValidateCanvas in FDrawOptions) then
  10519.     if (GetObjectType(ValidateDC) <> OBJ_DC) then
  10520.     begin
  10521.       Terminate;
  10522.       exit;
  10523.     end;
  10524.  
  10525.   DrawDestination := nil;
  10526.   DoStep2 := (goClearOnLoop in FDrawOptions) and (FActiveImage = 0);
  10527.   DoStep3 := False;
  10528.   DoStep5 := False;
  10529.   DoStep6 := False;
  10530. {
  10531. Disposal mode algorithm:
  10532.  
  10533. Step 1: Copy destination to backup buffer
  10534.         Always executed before first frame and only once.
  10535.         Done in constructor.
  10536. Step 2: Clear previous frame (implementation is same as step 6)
  10537.         Done implicitly by implementation.
  10538.         Only done explicitly on first frame if goClearOnLoop option is set.
  10539. Step 3: Copy backup buffer to frame buffer
  10540. Step 4: Draw frame
  10541. Step 5: Copy buffer to destination
  10542. Step 6: Clear frame from backup buffer
  10543. +------------+------------------+---------------------+------------------------+
  10544. |New  \  Old |  dmNone          |  dmBackground       |  dmPrevious            |
  10545. +------------+------------------+---------------------+------------------------+
  10546. |dmNone      |                  |                     |                        |
  10547. |            |4. Paint on backup|4. Paint on backup   |4. Paint on backup      |
  10548. |            |5. Restore        |5. Restore           |5. Restore              |
  10549. +------------+------------------+---------------------+------------------------+
  10550. |dmBackground|                  |                     |                        |
  10551. |            |4. Paint on backup|4. Paint on backup   |4. Paint on backup      |
  10552. |            |5. Restore        |5. Restore           |5. Restore              |
  10553. |            |6. Clear backup   |6. Clear backup      |6. Clear backup         |
  10554. +------------+------------------+---------------------+------------------------+
  10555. |dmPrevious  |                  |                     |                        |
  10556. |            |                  |3. Copy backup to buf|3. Copy backup to buf   |
  10557. |            |4. Paint on dest  |4. Paint on buf      |4. Paint on buf         |
  10558. |            |                  |5. Copy buf to dest  |5. Copy buf to dest     |
  10559. +------------+------------------+---------------------+------------------------+
  10560. }
  10561.   case (Disposal) of
  10562.     dmNone, dmNoDisposal:
  10563.       begin
  10564.         DrawDestination := BackupBuffer.Canvas;
  10565.         DrawRect := BackupBuffer.Canvas.ClipRect;
  10566.         DoStep5 := True;
  10567.       end;
  10568.     dmBackground:
  10569.       begin
  10570.         DrawDestination := BackupBuffer.Canvas;
  10571.         DrawRect := BackupBuffer.Canvas.ClipRect;
  10572.         DoStep5 := True;
  10573.         DoStep6 := True;
  10574.       end;
  10575.     dmPrevious:
  10576.       case (OldDisposal) of
  10577.         dmNone, dmNoDisposal:
  10578.         begin
  10579.           DrawDestination := FCanvas;
  10580.           DrawRect := FRect;
  10581.         end;
  10582.         dmBackground, dmPrevious:
  10583.         begin
  10584.           DrawDestination := FrameBuffer.Canvas;
  10585.           DrawRect := FrameBuffer.Canvas.ClipRect;
  10586.           DoStep3 := True;
  10587.           DoStep5 := True;
  10588.         end;
  10589.       end;
  10590.   end;
  10591.  
  10592.   // Find source palette
  10593.   SourcePal := FImage.Images[ActiveImage].Palette;
  10594.   if (SourcePal = 0) then
  10595.     SourcePal := SystemPalette16; // This should never happen
  10596.  
  10597.   SavePal := SelectPalette(DrawDestination.Handle, SourcePal, False);
  10598.   RealizePalette(DrawDestination.Handle);
  10599.  
  10600.   // Step 2: Clear previous frame
  10601.   if (DoStep2) then
  10602.    ClearBackup;
  10603.  
  10604.   // Step 3: Copy backup buffer to frame buffer
  10605.   if (DoStep3) then
  10606.     FrameBuffer.Canvas.CopyRect(FrameBuffer.Canvas.ClipRect,
  10607.       BackupBuffer.Canvas, BackupBuffer.Canvas.ClipRect);
  10608.  
  10609.   // Step 4: Draw frame
  10610.   if (DrawDestination <> nil) then
  10611.     FImage.Images[ActiveImage].Draw(DrawDestination, DrawRect,
  10612.       (goTransparent in FDrawOptions), (goTile in FDrawOptions));
  10613.  
  10614.   // Step 5: Copy buffer to destination
  10615.   if (DoStep5) then
  10616.   begin
  10617.     FCanvas.CopyMode := cmSrcCopy;
  10618.     FCanvas.CopyRect(FRect, DrawDestination, DrawRect);
  10619.   end;
  10620.  
  10621.   if (SavePal <> 0) then
  10622.     SelectPalette(DrawDestination.Handle, SavePal, False);
  10623.  
  10624.   // Step 6: Clear frame from backup buffer
  10625.   if (DoStep6) then
  10626.    ClearBackup;
  10627.  
  10628.   FStarted := True;
  10629. end;
  10630.  
  10631. // Prefetch bitmap
  10632. // Used to force the GIF image to be rendered as a bitmap
  10633. {$ifdef SERIALIZE_RENDER}
  10634. procedure TGIFPainter.PrefetchBitmap;
  10635. begin
  10636.   // Touch current bitmap to force bitmap to be rendered
  10637.   if not((FImage.Images[ActiveImage].Empty) or (FImage.Images[ActiveImage].HasBitmap)) then
  10638.     FImage.Images[ActiveImage].Bitmap;
  10639. end;
  10640. {$endif}
  10641.  
  10642. // Main thread execution loop - This is where it all happens...
  10643. procedure TGIFPainter.Execute;
  10644. var
  10645.   i         : integer;
  10646.   LoopCount     ,
  10647.   LoopPoint     : integer;
  10648.   Looping       : boolean;
  10649.   Ext           : TGIFExtension;
  10650.   Msg           : TMsg;
  10651.   Delay         ,
  10652.   OldDelay      ,
  10653.   DelayUsed     : longInt;
  10654.   DelayStart        ,
  10655.   NewDelayStart     : DWORD;
  10656.  
  10657.   procedure FireEvent(Event: TNotifyEvent);
  10658.   begin
  10659.     if not(Assigned(Event)) then
  10660.       exit;
  10661.     FEvent := Event;
  10662.     try
  10663.       DoSynchronize(DoEvent);
  10664.     finally
  10665.       FEvent := nil;
  10666.     end;
  10667.   end;
  10668.  
  10669. begin
  10670. {
  10671.   Disposal:
  10672.     dmNone: Same as dmNodisposal
  10673.     dmNoDisposal: Do not dispose
  10674.     dmBackground: Clear with background color *)
  10675.     dmPrevious: Previous image
  10676.     *) Note: Background color should either be a BROWSER SPECIFIED Background
  10677.        color (DrawBackgroundColor) or the background image if any frames are
  10678.        transparent.
  10679. }
  10680.   try
  10681.     try
  10682.       if (goValidateCanvas in FDrawOptions) then
  10683.         ValidateDC := FCanvas.Handle;
  10684.       DoRestart := True;
  10685.  
  10686.       // Loop to restart paint
  10687.       while (DoRestart) and not(Terminated) do
  10688.       begin
  10689.         FActiveImage := 0;
  10690.         // Fire OnStartPaint event
  10691.         // Note: ActiveImage may be altered by the event handler
  10692.         FireEvent(FOnStartPaint);
  10693.  
  10694.         FStarted := False;
  10695.         DoRestart := False;
  10696.         LoopCount := 1;
  10697.         LoopPoint := FActiveImage;
  10698.         Looping := False;
  10699.         if (goAsync in DrawOptions) then
  10700.           Delay := 0
  10701.         else
  10702.           Delay := 1; // Dummy to process messages
  10703.         OldDisposal := dmNoDisposal;
  10704.         // Fetch delay start time
  10705.         DelayStart := timeGetTime;
  10706.         OldDelay := 0;
  10707.  
  10708.         // Loop to loop - duh!
  10709.         while ((LoopCount <> 0) or (goLoopContinously in DrawOptions)) and
  10710.           not(Terminated or DoRestart) do
  10711.         begin
  10712.           FActiveImage := LoopPoint;
  10713.  
  10714.           // Fire OnLoopPaint event
  10715.           // Note: ActiveImage may be altered by the event handler
  10716.           if (FStarted) then
  10717.             FireEvent(FOnLoop);
  10718.  
  10719.           // Loop to animate
  10720.           while (ActiveImage < FImage.Images.Count) and not(Terminated or DoRestart) do
  10721.           begin
  10722.             // Ignore empty images
  10723.             if (FImage.Images[ActiveImage].Empty) then
  10724.               break;
  10725.             // Delay from previous image
  10726.             if (Delay > 0) then
  10727.             begin
  10728.               // Prefetch frame bitmap
  10729. {$ifdef SERIALIZE_RENDER}
  10730.               DoSynchronize(PrefetchBitmap);
  10731. {$else}
  10732.               FImage.Images[ActiveImage].Bitmap;
  10733. {$endif}
  10734.  
  10735.               // Calculate inter frame delay
  10736.               NewDelayStart := timeGetTime;
  10737.               if (FAnimationSpeed > 0) then
  10738.               begin
  10739.                 // Calculate number of mS used in prefetch and display
  10740.                 try
  10741.                   DelayUsed := integer(NewDelayStart-DelayStart)-OldDelay;
  10742.                   // Prevent feedback oscillations caused by over/undercompensation.
  10743.                   DelayUsed := DelayUsed DIV 2;
  10744.                   // Convert delay value to mS and...
  10745.                   // ...Adjust for time already spent converting GIF to bitmap and...
  10746.                   // ...Adjust for Animation Speed factor.
  10747.                   Delay := MulDiv(Delay * GIFDelayExp - DelayUsed, 100, FAnimationSpeed);
  10748.                   OldDelay := Delay;
  10749.                 except
  10750.                   Delay := GIFMaximumDelay * GIFDelayExp;
  10751.                   OldDelay := 0;
  10752.                 end;
  10753.               end else
  10754.               begin
  10755.                 if (goAsync in DrawOptions) then
  10756.                   Delay := longInt(INFINITE)
  10757.                 else
  10758.                   Delay := GIFMaximumDelay * GIFDelayExp;
  10759.               end;
  10760.               // Fetch delay start time
  10761.               DelayStart := NewDelayStart;
  10762.  
  10763.               // Sleep in one chunk if we are running in a thread
  10764.               if (goAsync in DrawOptions) then
  10765.               begin
  10766.                 // Use of WaitForSingleObject allows TGIFPainter.Stop to wake us up
  10767.                 if (Delay > 0) or (FAnimationSpeed = 0) then
  10768.                 begin
  10769.                   if (WaitForSingleObject(FEventHandle, DWORD(Delay)) <> WAIT_TIMEOUT) then
  10770.                   begin
  10771.                     // Don't use interframe delay feedback adjustment if delay
  10772.                     // were prematurely aborted (e.g. because the animation
  10773.                     // speed were changed)
  10774.                     OldDelay := 0;
  10775.                     DelayStart := longInt(timeGetTime);
  10776.                   end;
  10777.                 end;
  10778.               end else
  10779.               begin
  10780.                 if (Delay <= 0) then
  10781.                   Delay := 1;
  10782.                 // Fetch start time
  10783.                 NewDelayStart := timeGetTime;
  10784.                 // If we are not running in a thread we Sleep in small chunks
  10785.                 // and give the user a chance to abort
  10786.                 while (Delay > 0) and not(Terminated or DoRestart) do
  10787.                 begin
  10788.                   if (Delay < 100) then
  10789.                     Sleep(Delay)
  10790.                   else
  10791.                     Sleep(100);
  10792.                   // Calculate number of mS delayed in this chunk
  10793.                   DelayUsed := integer(timeGetTime - NewDelayStart);
  10794.                   dec(Delay, DelayUsed);
  10795.                   // Reset start time for chunk
  10796.                   NewDelaySTart := timeGetTime;
  10797.                   // Application.ProcessMessages wannabe
  10798.                   while (not(Terminated or DoRestart)) and
  10799.                     (PeekMessage(Msg, 0, 0, 0, PM_REMOVE)) do
  10800.                   begin
  10801.                     if (Msg.Message <> WM_QUIT) then
  10802.                     begin
  10803.                       TranslateMessage(Msg);
  10804.                       DispatchMessage(Msg);
  10805.                     end else
  10806.                     begin
  10807.                       // Put WM_QUIT back in queue and get out of here fast
  10808.                       PostQuitMessage(Msg.WParam);
  10809.                       Terminate;
  10810.                     end;
  10811.                   end;
  10812.                 end;
  10813.               end;
  10814.             end else
  10815.               Sleep(0); // Yield
  10816.             if (Terminated) then
  10817.               break;
  10818.  
  10819.             // Fire OnPaint event
  10820.             // Note: ActiveImage may be altered by the event handler
  10821.             FireEvent(FOnPaint);
  10822.             if (Terminated) then
  10823.               break;
  10824.  
  10825.             // Pre-draw processing of extensions
  10826.             Disposal := dmNoDisposal;
  10827.             for i := 0 to FImage.Images[ActiveImage].Extensions.Count-1 do
  10828.             begin
  10829.               Ext := FImage.Images[ActiveImage].Extensions[i];
  10830.               if (Ext is TGIFAppExtNSLoop) then
  10831.               begin
  10832.                 // Recursive loops not supported (or defined)
  10833.                 if (Looping) then
  10834.                   continue;
  10835.                 Looping := True;
  10836.                 LoopCount := TGIFAppExtNSLoop(Ext).Loops;
  10837.                 if ((LoopCount = 0) or (goLoopContinously in DrawOptions)) and
  10838.                   (goAsync in DrawOptions) then
  10839.                   LoopCount := -1; // Infinite if running in separate thread
  10840. {$IFNDEF STRICT_MOZILLA}
  10841.                 // Loop from this image and on
  10842.                 // Note: This is not standard behavior
  10843.                 LoopPoint := ActiveImage;
  10844. {$ENDIF}
  10845.               end else
  10846.               if (Ext is TGIFGraphicControlExtension) then
  10847.                 Disposal := TGIFGraphicControlExtension(Ext).Disposal;
  10848.             end;
  10849.  
  10850.             // Paint the image
  10851.             if (BackupBuffer <> nil) then
  10852.               DoSynchronize(DoPaintFrame)
  10853.             else
  10854.               DoSynchronize(DoPaint);
  10855.             OldDisposal := Disposal;
  10856.  
  10857.             if (Terminated) then
  10858.               break;
  10859.  
  10860.             Delay := GIFDefaultDelay; // Default delay
  10861.             // Post-draw processing of extensions
  10862.             if (FImage.Images[ActiveImage].GraphicControlExtension <> nil) then
  10863.               if (FImage.Images[ActiveImage].GraphicControlExtension.Delay > 0) then
  10864.               begin
  10865.                 Delay := FImage.Images[ActiveImage].GraphicControlExtension.Delay;
  10866.  
  10867.                 // Enforce minimum animation delay in compliance with Mozilla
  10868.                 if (Delay < GIFMinimumDelay) then
  10869.                   Delay := GIFMinimumDelay;
  10870.  
  10871.                 // Do not delay more than 10 seconds if running in main thread
  10872.                 if (Delay > GIFMaximumDelay) and not(goAsync in DrawOptions) then
  10873.                   Delay := GIFMaximumDelay; // Max 10 seconds
  10874.               end;
  10875.             // Fire OnAfterPaint event
  10876.             // Note: ActiveImage may be altered by the event handler
  10877.             i := FActiveImage;
  10878.             FireEvent(FOnAfterPaint);
  10879.             if (Terminated) then
  10880.               break;
  10881.             // Don't increment frame counter if event handler modified
  10882.             // current frame
  10883.             if (FActiveImage = i) then
  10884.               Inc(FActiveImage);
  10885.             // Nothing more to do unless we are animating
  10886.             if not(goAnimate in DrawOptions) then
  10887.               break;
  10888.           end;
  10889.  
  10890.           if (LoopCount > 0) then
  10891.             Dec(LoopCount);
  10892.           if ([goAnimate, goLoop] * DrawOptions <> [goAnimate, goLoop]) then
  10893.             break;
  10894.         end;
  10895.         if (Terminated) then  // 2001.07.23
  10896.           break;  // 2001.07.23
  10897.       end;
  10898.       FActiveImage := -1;
  10899.       // Fire OnEndPaint event
  10900.       FireEvent(FOnEndPaint);
  10901.     finally
  10902.       // If we are running in the main thread we will have to zap our self
  10903.       if not(goAsync in DrawOptions) then
  10904.         Free;
  10905.     end;
  10906.   except
  10907.     on E: Exception do
  10908.     begin
  10909.       // Eat exception and terminate thread...
  10910.       // If we allow the exception to abort the thread at this point, the
  10911.       // application will hang since the thread destructor will never be called
  10912.       // and the application will wait forever for the thread to die!
  10913.       Terminate;
  10914.       // Clone exception
  10915.       ExceptObject := E.Create(E.Message);
  10916.       ExceptAddress := ExceptAddr;
  10917.     end;
  10918.   end;
  10919. end;
  10920.  
  10921. procedure TGIFPainter.Start;
  10922. begin
  10923.   if (goAsync in FDrawOptions) then
  10924.     Resume;
  10925. end;
  10926.  
  10927. procedure TGIFPainter.Stop;
  10928. begin
  10929.   Terminate;
  10930.   if (goAsync in FDrawOptions) then
  10931.   begin
  10932.     // Signal WaitForSingleObject delay to abort
  10933.     if (FEventHandle <> 0) then
  10934.       SetEvent(FEventHandle);
  10935.     Priority := tpNormal;
  10936.     if (Suspended) then
  10937.       Resume; // Must be running before we can terminate
  10938.   end;
  10939. end;
  10940.  
  10941. procedure TGIFPainter.Restart;
  10942. begin
  10943.   DoRestart := True;
  10944.   if (Suspended) and (goAsync in FDrawOptions) then
  10945.     Resume; // Must be running before we can terminate
  10946. end;
  10947.  
  10948. ////////////////////////////////////////////////////////////////////////////////
  10949. //
  10950. //          TColorMapOptimizer
  10951. //
  10952. ////////////////////////////////////////////////////////////////////////////////
  10953. // Used by TGIFImage to optimize local color maps to a single global color map.
  10954. // The following algorithm is used:
  10955. // 1) Build a histogram for each image
  10956. // 2) Merge histograms
  10957. // 3) Sum equal colors and adjust max # of colors
  10958. // 4) Map entries > max to entries <= 256
  10959. // 5) Build new color map
  10960. // 6) Map images to new color map
  10961. ////////////////////////////////////////////////////////////////////////////////
  10962.  
  10963. type
  10964.  
  10965.   POptimizeEntry    = ^TOptimizeEntry;
  10966.   TColorRec = record
  10967.   case byte of
  10968.     0: (Value: integer);
  10969.     1: (Color: TGIFColor);
  10970.     2: (SameAs: POptimizeEntry); // Used if TOptimizeEntry.Count = 0
  10971.   end;
  10972.  
  10973.   TOptimizeEntry = record
  10974.     Count       : integer;  // Usage count
  10975.     OldIndex        : integer;  // Color OldIndex
  10976.     NewIndex        : integer;  // NewIndex color OldIndex
  10977.     Color       : TColorRec;    // Color value
  10978.   end;
  10979.  
  10980.   TOptimizeEntries  = array[0..255] of TOptimizeEntry;
  10981.   POptimizeEntries  = ^TOptimizeEntries;
  10982.  
  10983.   THistogram = class(TObject)
  10984.   private
  10985.     PHistogram      : POptimizeEntries;
  10986.     FCount      : integer;
  10987.     FColorMap       : TGIFColorMap;
  10988.     FList       : TList;
  10989.     FImages     : TList;
  10990.   public
  10991.     constructor Create(AColorMap: TGIFColorMap);
  10992.     destructor Destroy; override;
  10993.     function ProcessSubImage(Image: TGIFSubImage): boolean;
  10994.     function Prune: integer;
  10995.     procedure MapImages(UseTransparency: boolean; NewTransparentColorIndex: byte);
  10996.     property Count: integer read FCount;
  10997.     property ColorMap: TGIFColorMap read FColorMap;
  10998.     property List: TList read FList;
  10999.   end;
  11000.  
  11001.   TColorMapOptimizer = class(TObject)
  11002.   private
  11003.     FImage      : TGIFImage;
  11004.     FHistogramList  : TList;
  11005.     FHistogram      : TList;
  11006.     FColorMap       : TColorMap;
  11007.     FFinalCount     : integer;
  11008.     FUseTransparency    : boolean;
  11009.     FNewTransparentColorIndex: byte;
  11010.   protected
  11011.     procedure ProcessImage;
  11012.     procedure MergeColors;
  11013.     procedure MapColors;
  11014.     procedure ReplaceColorMaps;
  11015.   public
  11016.     constructor Create(AImage: TGIFImage);
  11017.     destructor Destroy; override;
  11018.     procedure Optimize;
  11019.   end;
  11020.  
  11021. function CompareColor(Item1, Item2: Pointer): integer;
  11022. begin
  11023.   Result := POptimizeEntry(Item2)^.Color.Value - POptimizeEntry(Item1)^.Color.Value;
  11024. end;
  11025.  
  11026. function CompareCount(Item1, Item2: Pointer): integer;
  11027. begin
  11028.   Result := POptimizeEntry(Item2)^.Count - POptimizeEntry(Item1)^.Count;
  11029. end;
  11030.  
  11031. constructor THistogram.Create(AColorMap: TGIFColorMap);
  11032. var
  11033.   i         : integer;
  11034. begin
  11035.   inherited Create;
  11036.  
  11037.   FCount := AColorMap.Count;
  11038.   FColorMap := AColorMap;
  11039.  
  11040.   FImages := TList.Create;
  11041.  
  11042.   // Allocate memory for histogram
  11043.   GetMem(PHistogram, FCount * sizeof(TOptimizeEntry));
  11044.   FList := TList.Create;
  11045.  
  11046.   FList.Capacity := FCount;
  11047.  
  11048.   // Move data to histogram and initialize
  11049.   for i := 0 to FCount-1 do
  11050.     with PHistogram^[i] do
  11051.     begin
  11052.       FList.Add(@PHistogram^[i]);
  11053.       OldIndex := i;
  11054.       Count := 0;
  11055.       Color.Value := 0;
  11056.       Color.Color := AColorMap.Data^[i];
  11057.       NewIndex := 256; // Used to signal unmapped
  11058.     end;
  11059. end;
  11060.  
  11061. destructor THistogram.Destroy;
  11062. begin
  11063.   FImages.Free;
  11064.   FList.Free;
  11065.   FreeMem(PHistogram);
  11066.   inherited Destroy;
  11067. end;
  11068.  
  11069. //: Build a color histogram
  11070. function THistogram.ProcessSubImage(Image: TGIFSubImage): boolean;
  11071. var
  11072.   Size          : integer;
  11073.   Pixel         : PAnsiChar;
  11074.   IsTransparent     ,
  11075.   WasTransparent    : boolean;
  11076.   OldTransparentColorIndex: byte;
  11077. begin
  11078.   Result := False;
  11079.   if (Image.Empty) then
  11080.     exit;
  11081.  
  11082.   FImages.Add(Image);
  11083.  
  11084.   Pixel := Image.data;
  11085.   Size := Image.Width * Image.Height;
  11086.  
  11087.   IsTransparent := Image.Transparent;
  11088.   if (IsTransparent) then
  11089.     OldTransparentColorIndex := Image.GraphicControlExtension.TransparentColorIndex
  11090.   else
  11091.     OldTransparentColorIndex := 0; // To avoid compiler warning
  11092.   WasTransparent := False;
  11093.  
  11094.   (*
  11095.   ** Sum up usage count for each color
  11096.   *)
  11097.   while (Size > 0) do
  11098.   begin
  11099.     // Ignore transparent pixels
  11100.     if (not IsTransparent) or (ord(Pixel^) <> OldTransparentColorIndex) then
  11101.     begin
  11102.       // Check for invalid color index
  11103.       if (ord(Pixel^) >= FCount) then
  11104.       begin
  11105.         Pixel^ := #0; // ***FIXME*** Isn't this an error condition?
  11106.         Image.Warning(gsWarning, sInvalidColor);
  11107.       end;
  11108.  
  11109.       with PHistogram^[ord(Pixel^)] do
  11110.       begin
  11111.         // Stop if any color reaches the max count
  11112.         if (Count = high(integer)) then
  11113.           break;
  11114.         inc(Count);
  11115.       end;
  11116.     end else
  11117.       WasTransparent := WasTransparent or IsTransparent;
  11118.     inc(Pixel);
  11119.     dec(Size);
  11120.   end;
  11121.  
  11122.   (*
  11123.   ** Clear frames transparency flag if the frame claimed to
  11124.   ** be transparent, but wasn't
  11125.   *)
  11126.   if (IsTransparent and not WasTransparent) then
  11127.   begin
  11128.     Image.GraphicControlExtension.TransparentColorIndex := 0;
  11129.     Image.GraphicControlExtension.Transparent := False;
  11130.   end;
  11131.  
  11132.   Result := WasTransparent;
  11133. end;
  11134.  
  11135. //: Removed unused color entries from the histogram
  11136. function THistogram.Prune: integer;
  11137. var
  11138.   i, j          : integer;
  11139. begin
  11140.   (*
  11141.   **  Sort by usage count
  11142.   *)
  11143.   FList.Sort(CompareCount);
  11144.  
  11145.   (*
  11146.   **  Determine number of used colors
  11147.   *)
  11148.   for i := 0 to FCount-1 do
  11149.     // Find first unused color entry
  11150.     if (POptimizeEntry(FList[i])^.Count = 0) then
  11151.     begin
  11152.       // Zap unused colors
  11153.       for j := i to FCount-1 do
  11154.         POptimizeEntry(FList[j])^.Count := -1; // Use -1 to signal unused entry
  11155.       // Remove unused entries
  11156.       FCount := i;
  11157.       FList.Count := FCount;
  11158.       break;
  11159.     end;
  11160.  
  11161.   Result := FCount;
  11162. end;
  11163.  
  11164. //: Convert images from old color map to new color map
  11165. procedure THistogram.MapImages(UseTransparency: boolean; NewTransparentColorIndex: byte);
  11166. var
  11167.   i         : integer;
  11168.   Size          : integer;
  11169.   Pixel         : PAnsiChar;
  11170.   ReverseMap        : array[byte] of byte;
  11171.   IsTransparent     : boolean;
  11172.   OldTransparentColorIndex: byte;
  11173. begin
  11174.   (*
  11175.   ** Build NewIndex map
  11176.   *)
  11177.   for i := 0 to List.Count-1 do
  11178.     ReverseMap[POptimizeEntry(List[i])^.OldIndex] := POptimizeEntry(List[i])^.NewIndex;
  11179.  
  11180.   (*
  11181.   **  Reorder all images using this color map
  11182.   *)
  11183.   for i := 0 to FImages.Count-1 do
  11184.     with TGIFSubImage(FImages[i]) do
  11185.     begin
  11186.       Pixel := Data;
  11187.       Size := Width * Height;
  11188.  
  11189.       // Determine frame transparency
  11190.       IsTransparent := (Transparent) and (UseTransparency);
  11191.       if (IsTransparent) then
  11192.       begin
  11193.         OldTransparentColorIndex := GraphicControlExtension.TransparentColorIndex;
  11194.         // Map transparent color
  11195.         GraphicControlExtension.TransparentColorIndex := NewTransparentColorIndex;
  11196.       end else
  11197.         OldTransparentColorIndex := 0; // To avoid compiler warning
  11198.  
  11199.       // Map all pixels to new color map
  11200.       while (Size > 0) do
  11201.       begin
  11202.         // Map transparent pixels to the new transparent color index and...
  11203.         if (IsTransparent) and (ord(Pixel^) = OldTransparentColorIndex) then
  11204.           Pixel^ := AnsiChar(NewTransparentColorIndex)
  11205.         else
  11206.           // ... all other pixels to their new color index
  11207.           Pixel^ := AnsiChar(ReverseMap[ord(Pixel^)]);
  11208.         dec(size);
  11209.         inc(Pixel);
  11210.       end;
  11211.     end;
  11212. end;
  11213.  
  11214. constructor TColorMapOptimizer.Create(AImage: TGIFImage);
  11215. begin
  11216.   inherited Create;
  11217.   FImage := AImage;
  11218.   FHistogramList := TList.Create;
  11219.   FHistogram := TList.Create;
  11220. end;
  11221.  
  11222. destructor TColorMapOptimizer.Destroy;
  11223. var
  11224.   i         : integer;
  11225. begin
  11226.   FHistogram.Free;
  11227.  
  11228.   for i := FHistogramList.Count-1 downto 0 do
  11229.     THistogram(FHistogramList[i]).Free;
  11230.   FHistogramList.Free;
  11231.  
  11232.   inherited Destroy;
  11233. end;
  11234.  
  11235. procedure TColorMapOptimizer.ProcessImage;
  11236. var
  11237.   Hist          : THistogram;
  11238.   i         : integer;
  11239.   ProcessedImage    : boolean;
  11240. begin
  11241.   FUseTransparency := False;
  11242.   (*
  11243.   ** First process images using global color map
  11244.   *)
  11245.   if (FImage.GlobalColorMap.Count > 0) then
  11246.   begin
  11247.     Hist := THistogram.Create(FImage.GlobalColorMap);
  11248.     ProcessedImage := False;
  11249.     // Process all images that are using the global color map
  11250.     for i := 0 to FImage.Images.Count-1 do
  11251.       if (FImage.Images[i].ColorMap.Count = 0) and (not FImage.Images[i].Empty) then
  11252.       begin
  11253.         ProcessedImage := True;
  11254.       // Note: Do not change order of statements. Shortcircuit evaluation not desired!
  11255.         FUseTransparency := Hist.ProcessSubImage(FImage.Images[i]) or FUseTransparency;
  11256.       end;
  11257.     // Keep the histogram if any images used the global color map...
  11258.     if (ProcessedImage) then
  11259.       FHistogramList.Add(Hist)
  11260.     else // ... otherwise delete it
  11261.       Hist.Free;
  11262.   end;
  11263.  
  11264.   (*
  11265.   ** Next process images that have a local color map
  11266.   *)
  11267.   for i := 0 to FImage.Images.Count-1 do
  11268.     if (FImage.Images[i].ColorMap.Count > 0) and (not FImage.Images[i].Empty) then
  11269.     begin
  11270.       Hist := THistogram.Create(FImage.Images[i].ColorMap);
  11271.       FHistogramList.Add(Hist);
  11272.       // Note: Do not change order of statements. Shortcircuit evaluation not desired!
  11273.       FUseTransparency := Hist.ProcessSubImage(FImage.Images[i]) or FUseTransparency;
  11274.     end;
  11275. end;
  11276.  
  11277. procedure TColorMapOptimizer.MergeColors;
  11278. var
  11279.   Entry, SameEntry  : POptimizeEntry;
  11280.   i         : integer;
  11281. begin
  11282.   (*
  11283.   **  Sort by color value
  11284.   *)
  11285.   FHistogram.Sort(CompareColor);
  11286.  
  11287.   (*
  11288.   **  Merge same colors
  11289.   *)
  11290.   SameEntry := POptimizeEntry(FHistogram[0]);
  11291.   for i := 1 to FHistogram.Count-1 do
  11292.   begin
  11293.     Entry := POptimizeEntry(FHistogram[i]);
  11294.     ASSERT(Entry^.Count > 0, 'Unused entry exported from THistogram');
  11295.     if (Entry^.Color.Value = SameEntry^.Color.Value) then
  11296.     begin
  11297.       // Transfer usage count to first entry
  11298.       inc(SameEntry^.Count, Entry^.Count);
  11299.       Entry^.Count := 0; // Use 0 to signal merged entry
  11300.       Entry^.Color.SameAs := SameEntry; // Point to master
  11301.     end else
  11302.       SameEntry := Entry;
  11303.   end;
  11304. end;
  11305.  
  11306. procedure TColorMapOptimizer.MapColors;
  11307. var
  11308.   i, j          : integer;
  11309.   Delta, BestDelta  : integer;
  11310.   BestIndex     : integer;
  11311.   MaxColors     : integer;
  11312. begin
  11313.   (*
  11314.   **  Sort by usage count
  11315.   *)
  11316.   FHistogram.Sort(CompareCount);
  11317.  
  11318.   (*
  11319.   ** Handle transparency
  11320.   *)
  11321.   if (FUseTransparency) then
  11322.     MaxColors := 255
  11323.   else
  11324.     MaxColors := 256;
  11325.  
  11326.   (*
  11327.   **  Determine number of colors used (max 256)
  11328.   *)
  11329.   FFinalCount := FHistogram.Count;
  11330.   for i := 0 to FFinalCount-1 do
  11331.     if (i >= MaxColors) or (POptimizeEntry(FHistogram[i])^.Count = 0) then
  11332.     begin
  11333.       FFinalCount := i;
  11334.       break;
  11335.     end;
  11336.  
  11337.   (*
  11338.   **  Build color map and reverse map for final entries
  11339.   *)
  11340.   for i := 0 to FFinalCount-1 do
  11341.   begin
  11342.     POptimizeEntry(FHistogram[i])^.NewIndex := i;
  11343.     FColorMap[i] := POptimizeEntry(FHistogram[i])^.Color.Color;
  11344.   end;
  11345.  
  11346.   (*
  11347.   **  Map colors > 256 to colors <= 256 and build NewIndex color map
  11348.   *)
  11349.   for i := FFinalCount to FHistogram.Count-1 do
  11350.     with POptimizeEntry(FHistogram[i])^ do
  11351.     begin
  11352.       // Entries with a usage count of -1 is unused
  11353.       ASSERT(Count <> -1, 'Internal error: Unused entry exported');
  11354.       // Entries with a usage count of 0 has been merged with another entry
  11355.       if (Count = 0) then
  11356.       begin
  11357.         // Use mapping of master entry
  11358.         ASSERT(Color.SameAs.NewIndex < 256, 'Internal error: Mapping to unmapped color');
  11359.         NewIndex := Color.SameAs.NewIndex;
  11360.       end else
  11361.       begin
  11362.         // Search for entry with nearest color value
  11363.         BestIndex := 0;
  11364.         BestDelta := 255*3;
  11365.         for j := 0 to FFinalCount-1 do
  11366.         begin
  11367.           Delta := ABS((POptimizeEntry(FHistogram[j])^.Color.Color.Red - Color.Color.Red) +
  11368.             (POptimizeEntry(FHistogram[j])^.Color.Color.Green - Color.Color.Green) +
  11369.             (POptimizeEntry(FHistogram[j])^.Color.Color.Blue - Color.Color.Blue));
  11370.           if (Delta < BestDelta) then
  11371.           begin
  11372.             BestDelta := Delta;
  11373.             BestIndex := j;
  11374.           end;
  11375.         end;
  11376.         NewIndex := POptimizeEntry(FHistogram[BestIndex])^.NewIndex;;
  11377.       end;
  11378.     end;
  11379.  
  11380.   (*
  11381.   ** Add transparency color to new color map
  11382.   *)
  11383.   if (FUseTransparency) then
  11384.   begin
  11385.     FNewTransparentColorIndex := FFinalCount;
  11386.     FColorMap[FFinalCount].Red := 0;
  11387.     FColorMap[FFinalCount].Green := 0;
  11388.     FColorMap[FFinalCount].Blue := 0;
  11389.     inc(FFinalCount);
  11390.   end;
  11391. end;
  11392.  
  11393. procedure TColorMapOptimizer.ReplaceColorMaps;
  11394. var
  11395.   i         : integer;
  11396. begin
  11397.   // Zap all local color maps
  11398.   for i := 0 to FImage.Images.Count-1 do
  11399.     if (FImage.Images[i].ColorMap <> nil) then
  11400.       FImage.Images[i].ColorMap.Clear;
  11401.   // Store optimized global color map
  11402.   FImage.GlobalColorMap.ImportColorMap(FColorMap, FFinalCount);
  11403.   FImage.GlobalColorMap.Optimized := True;
  11404. end;
  11405.  
  11406. procedure TColorMapOptimizer.Optimize;
  11407. var
  11408.   Total         : integer;
  11409.   i, j          : integer;
  11410. begin
  11411.   // Stop all painters during optimize...
  11412.   FImage.PaintStop;
  11413.   // ...and prevent any new from starting while we are doing our thing
  11414.   FImage.Painters.LockList;
  11415.   try
  11416.  
  11417.     (*
  11418.     **  Process all sub images
  11419.     *)
  11420.     ProcessImage;
  11421.  
  11422.     // Prune histograms and calculate total number of colors
  11423.     Total := 0;
  11424.     for i := 0 to FHistogramList.Count-1 do
  11425.       inc(Total, THistogram(FHistogramList[i]).Prune);
  11426.  
  11427.     // Allocate global histogram
  11428.     FHistogram.Clear;
  11429.     FHistogram.Capacity := Total;
  11430.  
  11431.     // Move data pointers from local histograms to global histogram
  11432.     for i := 0 to FHistogramList.Count-1 do
  11433.       with THistogram(FHistogramList[i]) do
  11434.         for j := 0 to Count-1 do
  11435.         begin
  11436.           ASSERT(POptimizeEntry(List[j])^.Count > 0, 'Unused entry exported from THistogram');
  11437.           FHistogram.Add(List[j]);
  11438.         end;
  11439.  
  11440.     (*
  11441.     **  Merge same colors
  11442.     *)
  11443.     MergeColors;
  11444.  
  11445.     (*
  11446.     **  Build color map and NewIndex map for final entries
  11447.     *)
  11448.     MapColors;
  11449.  
  11450.     (*
  11451.     **  Replace local colormaps with global color map
  11452.     *)
  11453.     ReplaceColorMaps;
  11454.  
  11455.     (*
  11456.     **  Process images for each color map
  11457.     *)
  11458.     for i := 0 to FHistogramList.Count-1 do
  11459.       THistogram(FHistogramList[i]).MapImages(FUseTransparency, FNewTransparentColorIndex);
  11460.  
  11461.     (*
  11462.     **  Delete the frame's old bitmaps and palettes
  11463.     *)
  11464.     for i := 0 to FImage.Images.Count-1 do
  11465.     begin
  11466.       FImage.Images[i].HasBitmap := False;
  11467.       FImage.Images[i].Palette := 0;
  11468.     end;
  11469.  
  11470.   finally
  11471.     FImage.Painters.UnlockList;
  11472.   end;
  11473. end;
  11474.  
  11475. ////////////////////////////////////////////////////////////////////////////////
  11476. //
  11477. //          TGIFImage
  11478. //
  11479. ////////////////////////////////////////////////////////////////////////////////
  11480. constructor TGIFImage.Create;
  11481. begin
  11482.   inherited Create;
  11483.   FImages := TGIFImageList.Create(self);
  11484.   FHeader := TGIFHeader.Create(self);
  11485.   FPainters := TThreadList.Create;
  11486.   FGlobalPalette := 0;
  11487.   // Load defaults
  11488.   FDrawOptions := GIFImageDefaultDrawOptions;
  11489.   ColorReduction := GIFImageDefaultColorReduction;
  11490.   FReductionBits := GIFImageDefaultColorReductionBits;
  11491.   FDitherMode := GIFImageDefaultDitherMode;
  11492.   FCompression := GIFImageDefaultCompression;
  11493.   FThreadPriority := GIFImageDefaultThreadPriority;
  11494.   FAnimationSpeed := GIFImageDefaultAnimationSpeed;
  11495.  
  11496.   FDrawBackgroundColor := clNone;
  11497.   IsDrawing := False;
  11498.   IsInsideGetPalette := False;
  11499.   FForceFrame := -1;  // 2004.03.09
  11500.   NewImage;
  11501. end;
  11502.  
  11503. destructor TGIFImage.Destroy;
  11504. var
  11505.   i         : integer;
  11506. begin
  11507.   PaintStop;
  11508.   with FPainters.LockList do
  11509.     try
  11510.       for i := Count-1 downto 0 do
  11511.         TGIFPainter(Items[i]).FImage := nil;
  11512.     finally
  11513.       FPainters.UnLockList;
  11514.     end;
  11515.  
  11516.   Clear;
  11517.   FPainters.Free;
  11518.   FImages.Free;
  11519.   FHeader.Free;
  11520.   inherited Destroy;
  11521. end;
  11522.  
  11523. procedure TGIFImage.Clear;
  11524. begin
  11525.   PaintStop;
  11526.   FreeBitmap;
  11527.   FImages.Clear;
  11528.   FHeader.ColorMap.Clear;
  11529.   FHeader.Height := 0;
  11530.   FHeader.Width := 0;
  11531.   FHeader.Prepare;
  11532.   Palette := 0;
  11533. end;
  11534.  
  11535. procedure TGIFImage.NewImage;
  11536. begin
  11537.   Clear;
  11538. end;
  11539.  
  11540. function TGIFImage.GetVersion: TGIFVersion;
  11541. var
  11542.   v         : TGIFVersion;
  11543.   i         : integer;
  11544. begin
  11545.   Result := gvUnknown;
  11546.   for i := 0 to FImages.Count-1 do
  11547.   begin
  11548.     v := FImages[i].Version;
  11549.     if (v > Result) then
  11550.       Result := v;
  11551.     if (v >= high(TGIFVersion)) then
  11552.       break;
  11553.   end;
  11554. end;
  11555.  
  11556. function TGIFImage.GetColorResolution: integer;
  11557. var
  11558.   i         : integer;
  11559. begin
  11560.   Result := FHeader.ColorResolution;
  11561.   for i := 0 to FImages.Count-1 do
  11562.     if (FImages[i].ColorResolution > Result) then
  11563.       Result := FImages[i].ColorResolution;
  11564. end;
  11565.  
  11566. function TGIFImage.GetBitsPerPixel: integer;
  11567. var
  11568.   i         : integer;
  11569. begin
  11570.   Result := FHeader.BitsPerPixel;
  11571.   for i := 0 to FImages.Count-1 do
  11572.     if (FImages[i].BitsPerPixel > Result) then
  11573.       Result := FImages[i].BitsPerPixel;
  11574. end;
  11575.  
  11576. function TGIFImage.GetBackgroundColorIndex: BYTE;
  11577. begin
  11578.   Result := FHeader.BackgroundColorIndex;
  11579. end;
  11580.  
  11581. procedure TGIFImage.SetBackgroundColorIndex(const Value: BYTE);
  11582. begin
  11583.   FHeader.BackgroundColorIndex := Value;
  11584. end;
  11585.  
  11586. function TGIFImage.GetBackgroundColor: TColor;
  11587. begin
  11588.   Result := FHeader.BackgroundColor;
  11589. end;
  11590.  
  11591. procedure TGIFImage.SetBackgroundColor(const Value: TColor);
  11592. begin
  11593.   FHeader.BackgroundColor := Value;
  11594. end;
  11595.  
  11596. function TGIFImage.GetAspectRatio: BYTE;
  11597. begin
  11598.   Result := FHeader.AspectRatio;
  11599. end;
  11600.  
  11601. procedure TGIFImage.SetAspectRatio(const Value: BYTE);
  11602. begin
  11603.   FHeader.AspectRatio := Value;
  11604. end;
  11605.  
  11606. procedure TGIFImage.SetDrawOptions(Value: TGIFDrawOptions);
  11607. begin
  11608.   if (FDrawOptions = Value) then
  11609.     exit;
  11610.  
  11611.   if (DrawPainter <> nil) then
  11612.     DrawPainter.Stop;
  11613.  
  11614.   FDrawOptions := Value;
  11615.   // Zap all bitmaps
  11616.   Pack;
  11617.   Changed(self);
  11618. end;
  11619.  
  11620. function TGIFImage.GetAnimate: Boolean;
  11621. begin  // 2002.07.07
  11622.   Result:= goAnimate in DrawOptions;
  11623. end;
  11624.  
  11625. procedure TGIFImage.SetAnimate(const Value: Boolean);
  11626. begin  // 2002.07.07
  11627.   if Value then
  11628.     DrawOptions:= DrawOptions + [goAnimate]
  11629.   else
  11630.     DrawOptions:= DrawOptions - [goAnimate];
  11631. end;
  11632.  
  11633. procedure TGIFImage.SetForceFrame(const Value: Integer);
  11634. begin  // 2004.03.09
  11635.   FForceFrame := Value;
  11636.   Changed(Self);
  11637. end;
  11638.  
  11639. procedure TGIFImage.SetAnimationSpeed(Value: integer);
  11640. begin
  11641.   if (Value < 0) then
  11642.     Value := 0
  11643.   else if (Value > 1000) then
  11644.     Value := 1000;
  11645.   if (Value <> FAnimationSpeed) then
  11646.   begin
  11647.     FAnimationSpeed := Value;
  11648.     // Use the FPainters threadlist to protect FDrawPainter from being modified
  11649.     // by the thread while we mess with it
  11650.     with FPainters.LockList do
  11651.       try
  11652.         if (FDrawPainter <> nil) then
  11653.           FDrawPainter.AnimationSpeed := FAnimationSpeed;
  11654.       finally
  11655.         // Release the lock on FPainters to let paint thread kill itself
  11656.         FPainters.UnLockList;
  11657.       end;
  11658.   end;
  11659. end;
  11660.  
  11661. procedure TGIFImage.SetReductionBits(Value: integer);
  11662. begin
  11663.   if (Value < 3) or (Value > 8) then
  11664.     Error(sInvalidBitSize);
  11665.   FReductionBits := Value;
  11666. end;
  11667.  
  11668. procedure TGIFImage.OptimizeColorMap;
  11669. var
  11670.   ColorMapOptimizer : TColorMapOptimizer;
  11671. begin
  11672.   ColorMapOptimizer := TColorMapOptimizer.Create(self);
  11673.   try
  11674.     ColorMapOptimizer.Optimize;
  11675.   finally
  11676.     ColorMapOptimizer.Free;
  11677.   end;
  11678. end;
  11679.  
  11680. procedure TGIFImage.Optimize(Options: TGIFOptimizeOptions;
  11681.   ColorReduction: TColorReduction; DitherMode: TDitherMode;
  11682.   ReductionBits: integer);
  11683. var
  11684.   i         ,
  11685.   j         : integer;
  11686.   Delay         : integer;
  11687.   GCE           : TGIFGraphicControlExtension;
  11688.   ThisRect      ,
  11689.   NextRect      ,
  11690.   MergeRect     : TRect;
  11691.   Prog          ,
  11692.   MaxProg       : integer;
  11693.  
  11694.   function Scan(Buf: PAnsiChar; Value: Byte; Count: integer): boolean; assembler;
  11695.   asm
  11696.     PUSH    EDI
  11697.     MOV     EDI, Buf
  11698.     MOV     ECX, Count
  11699.     MOV     AL, Value
  11700.     REPNE   SCASB
  11701.     MOV     EAX, False
  11702.     JNE     @@1
  11703.     MOV     EAX, True
  11704. @@1:POP     EDI
  11705.   end;
  11706.  
  11707. begin
  11708.   if (Empty) then
  11709.     exit;
  11710.   // Stop all painters during optimize...
  11711.   PaintStop;
  11712.   // ...and prevent any new from starting while we are doing our thing
  11713.   FPainters.LockList;
  11714.   try
  11715.     Progress(Self, psStarting, 0, False, Rect(0,0,0,0), sProgressOptimizing);
  11716.     try
  11717.  
  11718.       Prog := 0;
  11719.       MaxProg := Images.Count*6;
  11720.  
  11721.       // Sort color map by usage and remove unused entries
  11722.       if (ooColorMap in Options) then
  11723.       begin
  11724.         // Optimize global color map
  11725.         if (GlobalColorMap.Count > 0) then
  11726.           GlobalColorMap.Optimize;
  11727.         // Optimize local color maps
  11728.         for i := 0 to Images.Count-1 do
  11729.         begin
  11730.           inc(Prog);
  11731.           if (Images[i].ColorMap.Count > 0) then
  11732.           begin
  11733.             Images[i].ColorMap.Optimize;
  11734.             Progress(Self, psRunning, MulDiv(Prog, 100, MaxProg), False,
  11735.               Rect(0,0,0,0), sProgressOptimizing);
  11736.           end;
  11737.         end;
  11738.       end;
  11739.  
  11740.       // Remove passive elements, pass 1
  11741.       if (ooCleanup in Options) then
  11742.       begin
  11743.         // Check for transparency flag without any transparent pixels
  11744.         for i := 0 to Images.Count-1 do
  11745.         begin
  11746.           inc(Prog);
  11747.           if (Images[i].Transparent) then
  11748.           begin
  11749.             if not(Scan(Images[i].Data,
  11750.                         Images[i].GraphicControlExtension.TransparentColorIndex,
  11751.                         Images[i].DataSize)) then
  11752.             begin
  11753.               Images[i].GraphicControlExtension.Transparent := False;
  11754.               Progress(Self, psRunning, MulDiv(Prog, 100, MaxProg), False,
  11755.                 Rect(0,0,0,0), sProgressOptimizing);
  11756.             end;
  11757.           end;
  11758.         end;
  11759.  
  11760.         // Change redundant disposal modes
  11761.         for i := 0 to Images.Count-2 do
  11762.         begin
  11763.           inc(Prog);
  11764.           if (Images[i].GraphicControlExtension <> nil) and
  11765.             (Images[i].GraphicControlExtension.Disposal in [dmPrevious, dmBackground]) and
  11766.             (not Images[i+1].Transparent) then
  11767.           begin
  11768.             ThisRect := Images[i].BoundsRect;
  11769.             NextRect := Images[i+1].BoundsRect;
  11770.             if (not IntersectRect(MergeRect, ThisRect, NextRect)) then
  11771.               continue;
  11772.             // If the next frame completely covers the current frame,
  11773.             // change the disposal mode to dmNone
  11774.             if (EqualRect(MergeRect, NextRect)) then
  11775.               Images[i].GraphicControlExtension.Disposal := dmNone;
  11776.             Progress(Self, psRunning, MulDiv(Prog, 100, MaxProg), False,
  11777.               Rect(0,0,0,0), sProgressOptimizing);
  11778.           end;
  11779.         end;
  11780.       end else
  11781.         inc(Prog, 2*Images.Count);
  11782.  
  11783.       // Merge layers of equal pixels (remove redundant pixels)
  11784.       if (ooMerge in Options) then
  11785.       begin
  11786.         // Merge from last to first to avoid intefering with merge
  11787.         for i := Images.Count-1 downto 1 do
  11788.         begin
  11789.           inc(Prog);
  11790.           j := i-1;
  11791.           // If the "previous" frames uses dmPrevious disposal mode, we must
  11792.           // instead merge with the frame before the previous
  11793.           while (j > 0) and
  11794.             ((Images[j].GraphicControlExtension <> nil) and
  11795.              (Images[j].GraphicControlExtension.Disposal = dmPrevious)) do
  11796.             dec(j);
  11797.           // Merge
  11798.           Images[i].Merge(Images[j]);
  11799.           Progress(Self, psRunning, MulDiv(Prog, 100, MaxProg), False,
  11800.             Rect(0,0,0,0), sProgressOptimizing);
  11801.         end;
  11802.       end else
  11803.         inc(Prog, Images.Count);
  11804.  
  11805.       // Crop transparent areas
  11806.       if (ooCrop in Options) then
  11807.       begin
  11808.         for i := Images.Count-1 downto 0 do
  11809.         begin
  11810.           inc(Prog);
  11811.           if (not Images[i].Empty) and (Images[i].Transparent) then
  11812.           begin
  11813.             // Remember frames delay in case frame is deleted
  11814.             Delay := Images[i].GraphicControlExtension.Delay;
  11815.             // Crop
  11816.             Images[i].Crop;
  11817.             // If the frame was completely transparent we remove it
  11818.             if (Images[i].Empty) then
  11819.             begin
  11820.               // Transfer delay to previous frame in case frame was deleted
  11821.               if (i > 0) and (Images[i-1].Transparent) then
  11822.                 Images[i-1].GraphicControlExtension.Delay :=
  11823.                   Images[i-1].GraphicControlExtension.Delay + Delay;
  11824.               Images.Delete(i);
  11825.             end;
  11826.             Progress(Self, psRunning, MulDiv(Prog, 100, MaxProg), False,
  11827.               Rect(0,0,0,0), sProgressOptimizing);
  11828.           end;
  11829.         end;
  11830.       end else
  11831.         inc(Prog, Images.Count);
  11832.  
  11833.       // Remove passive elements, pass 2
  11834.       inc(Prog, Images.Count);
  11835.       if (ooCleanup in Options) then
  11836.       begin
  11837.         for i := Images.Count-1 downto 0 do
  11838.         begin
  11839.           // Remove comments and application extensions
  11840.           for j := Images[i].Extensions.Count-1 downto 0 do
  11841.             if (Images[i].Extensions[j] is TGIFCommentExtension) or
  11842.               (Images[i].Extensions[j] is TGIFTextExtension) or
  11843.               (Images[i].Extensions[j] is TGIFUnknownAppExtension) or
  11844.               ((Images[i].Extensions[j] is TGIFAppExtNSLoop) and
  11845.                ((i > 0) or (Images.Count = 1))) then
  11846.               Images[i].Extensions.Delete(j);
  11847.           if (Images[i].GraphicControlExtension <> nil) then
  11848.           begin
  11849.             GCE := Images[i].GraphicControlExtension;
  11850.             // Zap GCE if all of the following are true:
  11851.             // * No delay or only one image
  11852.             // * Not transparent
  11853.             // * No prompt
  11854.             // * No disposal or only one image
  11855.             if ((GCE.Delay = 0) or (Images.Count = 1)) and
  11856.               (not GCE.Transparent) and
  11857.               (not GCE.UserInput) and
  11858.               ((GCE.Disposal in [dmNone, dmNoDisposal]) or (Images.Count = 1)) then
  11859.             begin
  11860.               GCE.Free;
  11861.             end;
  11862.           end;
  11863.           // Zap frame if it has become empty
  11864.           if (Images[i].Empty) and (Images[i].Extensions.Count = 0) then
  11865.             Images[i].Free;
  11866.         end;
  11867.         Progress(Self, psRunning, MulDiv(Prog, 100, MaxProg), False,
  11868.           Rect(0,0,0,0), sProgressOptimizing);
  11869.       end else
  11870.  
  11871.       // Reduce color depth
  11872.       if (ooReduceColors in Options) then
  11873.       begin
  11874.         if (ColorReduction = rmPalette) then
  11875.           Error(sInvalidReduction);
  11876.         { TODO -oanme -cFeature : Implement ooReduceColors option. }
  11877.         // Not implemented!
  11878.       end;
  11879.     finally
  11880.       if ExceptObject = nil then
  11881.         i := 100
  11882.       else
  11883.         i := 0;
  11884.       Progress(Self, psEnding, i, False, Rect(0,0,0,0), sProgressOptimizing);
  11885.     end;
  11886.   finally
  11887.     FPainters.UnlockList;
  11888.   end;
  11889. end;
  11890.  
  11891. procedure TGIFImage.Pack;
  11892. var
  11893.   i         : integer;
  11894. begin
  11895.   // Zap bitmaps and palettes
  11896.   FreeBitmap;
  11897.   Palette := 0;
  11898.   for i := 0 to FImages.Count-1 do
  11899.   begin
  11900.     FImages[i].Bitmap := nil;
  11901.     FImages[i].Palette := 0;
  11902.   end;
  11903.  
  11904.   // Only pack if no global colormap and a single image
  11905.   if (FHeader.ColorMap.Count > 0) or (FImages.Count <> 1) then
  11906.     exit;
  11907.  
  11908.   // Copy local colormap to global
  11909.   FHeader.ColorMap.Assign(FImages[0].ColorMap);
  11910.   // Zap local colormap
  11911.   FImages[0].ColorMap.Clear;
  11912. end;
  11913.  
  11914. procedure TGIFImage.SaveToStream(Stream: TStream);
  11915. var
  11916.   n         : Integer;
  11917. begin
  11918.   Progress(Self, psStarting, 0, False, Rect(0,0,0,0), sProgressSaving);
  11919.   try
  11920.     // Write header
  11921.     FHeader.SaveToStream(Stream);
  11922.     // Write images
  11923.     FImages.SaveToStream(Stream);
  11924.     // Write trailer
  11925.     with TGIFTrailer.Create(self) do
  11926.       try
  11927.         SaveToStream(Stream);
  11928.       finally
  11929.         Free;
  11930.       end;
  11931.   finally
  11932.     if ExceptObject = nil then
  11933.       n := 100
  11934.     else
  11935.       n := 0;
  11936.     Progress(Self, psEnding, n, True, Rect(0,0,0,0), sProgressSaving);
  11937.   end;
  11938. end;
  11939.  
  11940. // 2006.07.09 ->
  11941. {$IFDEF FIXHEADER_WIDTHHEIGHT_SILENT}
  11942. procedure TGIFImage.FixHeaderWidthHeight;
  11943. var
  11944.   i, w, h: Integer;
  11945. begin
  11946.   for i := 0 to Images.Count - 1 do
  11947.   begin
  11948.     w := Images.SubImages[i].Left + Images.SubImages[i].Width;
  11949.     h := Images.SubImages[i].Top + Images.SubImages[i].Height;
  11950.     if w > Header.Width then
  11951.       Header.Width := w;
  11952.     if h > Header.Height then
  11953.       Header.Height := h;
  11954.   end;
  11955. end;
  11956. {$ENDIF}
  11957. // 2006.07.09 <-
  11958.  
  11959. procedure TGIFImage.LoadFromStream(Stream: TStream);
  11960. var
  11961.   n         : Integer;
  11962.   Position      : integer;
  11963. begin
  11964.   Progress(Self, psStarting, 0, False, Rect(0,0,0,0), sProgressLoading);
  11965.   try
  11966.     // Zap old image
  11967.     Clear;
  11968.     Position := Stream.Position;
  11969.     try
  11970.       // Read header
  11971.       FHeader.LoadFromStream(Stream);
  11972.       // Read images
  11973.       FImages.LoadFromStream(Stream, self);
  11974.       {$IFDEF FIXHEADER_WIDTHHEIGHT_SILENT}
  11975.       FixHeaderWidthHeight;  // 2006.07.09
  11976.       {$ENDIF}
  11977.       // Read trailer
  11978.       with TGIFTrailer.Create(self) do
  11979.         try
  11980.           LoadFromStream(Stream);
  11981.         finally
  11982.           Free;
  11983.         end;
  11984.     except
  11985.       // Restore stream position in case of error.
  11986.       // Not required, but "a nice thing to do"
  11987.       Stream.Position := Position;
  11988.       raise;
  11989.     end;
  11990.   finally
  11991.     if ExceptObject = nil then
  11992.       n := 100
  11993.     else
  11994.       n := 0;
  11995.     Progress(Self, psEnding, n, True, Rect(0,0,0,0), sProgressLoading);
  11996.   end;
  11997. end;
  11998.  
  11999. procedure TGIFImage.LoadFromResourceName(Instance: THandle; const ResName: String);
  12000. // 2002.07.07
  12001. var
  12002.   Stream: TCustomMemoryStream;
  12003. begin
  12004.   Stream := TResourceStream.Create(Instance, ResName, RT_RCDATA);
  12005.   try
  12006.     LoadFromStream(Stream);
  12007.   finally
  12008.     Stream.Free;
  12009.   end;
  12010. end;
  12011.  
  12012. function TGIFImage.GetBitmap: TBitmap;
  12013. begin
  12014.   if not(Empty) then
  12015.   begin
  12016.     Result := FBitmap;
  12017.     if (Result <> nil) then
  12018.       exit;
  12019.     FBitmap := TBitmap.Create;
  12020.     Result := FBitmap;
  12021.     FBitmap.OnChange := Changed;
  12022.     // Use first image as default
  12023.     if (Images.Count > 0) then
  12024.     begin
  12025.       if (Images[0].Width = Width) and (Images[0].Height = Height) then
  12026.       begin
  12027.         // Use first image as it has same dimensions
  12028.         FBitmap.Assign(Images[0].Bitmap);
  12029.       end else
  12030.       begin
  12031.         // Draw first image on bitmap
  12032.         FBitmap.Palette := CopyPalette(Palette);
  12033.         FBitmap.Height := Height;
  12034.         FBitmap.Width := Width;
  12035.         Images[0].Draw(FBitmap.Canvas, FBitmap.Canvas.ClipRect, False, False);
  12036.       end;
  12037.     end;
  12038.   end else
  12039.     Result := nil
  12040. end;
  12041.  
  12042. // Create a new (empty) bitmap
  12043. function TGIFImage.NewBitmap: TBitmap;
  12044. begin
  12045.   Result := FBitmap;
  12046.   if (Result <> nil) then
  12047.     exit;
  12048.   FBitmap := TBitmap.Create;
  12049.   Result := FBitmap;
  12050.   FBitmap.OnChange := Changed;
  12051.   // Draw first image on bitmap
  12052.   FBitmap.Palette := CopyPalette(Palette);
  12053.   FBitmap.Height := Height;
  12054.   FBitmap.Width := Width;
  12055. end;
  12056.  
  12057. procedure TGIFImage.FreeBitmap;
  12058. begin
  12059.   if (DrawPainter <> nil) then
  12060.     DrawPainter.Stop;
  12061.  
  12062.   if (FBitmap <> nil) then
  12063.   begin
  12064.     FBitmap.Free;
  12065.     FBitmap := nil;
  12066.   end;
  12067. end;
  12068.  
  12069. function TGIFImage.Add(Source: TPersistent): integer;
  12070. var
  12071.   Image         : TGIFSubImage;
  12072. begin
  12073.   Image := nil; // To avoid compiler warning - not needed.
  12074.   if (Source is TGraphic) then
  12075.   begin
  12076.     Image := TGIFSubImage.Create(self);
  12077.     try
  12078.       Image.Assign(Source);
  12079.       // ***FIXME*** Documentation should explain the inconsistency here:
  12080.       // TGIFimage does not take ownership of Source after TGIFImage.Add() and
  12081.       // therefore does not delete Source.
  12082.     except
  12083.       Image.Free;
  12084.       raise;
  12085.     end;
  12086.   end else
  12087.   if (Source is TGIFSubImage) then
  12088.     Image := TGIFSubImage(Source)
  12089.   else
  12090.     Error(sUnsupportedClass);
  12091.  
  12092.   Result := FImages.Add(Image);
  12093.  
  12094.   FreeBitmap;
  12095.   Changed(self);
  12096. end;
  12097.  
  12098. function TGIFImage.GetEmpty: Boolean;
  12099. begin
  12100.   Result := (FImages.Count = 0);
  12101. end;
  12102.  
  12103. function TGIFImage.GetHeight: Integer;
  12104. begin
  12105.   Result := FHeader.Height;
  12106. end;
  12107.  
  12108. function TGIFImage.GetWidth: Integer;
  12109. begin
  12110.   Result := FHeader.Width;
  12111. end;
  12112.  
  12113. function TGIFImage.GetIsTransparent: Boolean;
  12114. var
  12115.   i         : integer;
  12116. begin
  12117.   Result := False;
  12118.   for i := 0 to Images.Count-1 do
  12119.     if (Images[i].GraphicControlExtension <> nil) and
  12120.       (Images[i].GraphicControlExtension.Transparent) then
  12121.     begin
  12122.       Result := True;
  12123.       exit;
  12124.     end;
  12125. end;
  12126.  
  12127. function TGIFImage.Equals(Graphic: TGraphic): Boolean;
  12128. begin
  12129.   Result := (Graphic = self);
  12130. end;
  12131.  
  12132. function TGIFImage.GetPalette: HPALETTE;
  12133. begin
  12134.   // Check for recursion
  12135.   // (TGIFImage.GetPalette->TGIFSubImage.GetPalette->TGIFImage.GetPalette etc...)
  12136.   if (IsInsideGetPalette) then
  12137.     Error(sNoColorTable);
  12138.   IsInsideGetPalette := True;
  12139.   try
  12140.     Result := 0;
  12141.     if (FBitmap <> nil) and (FBitmap.Palette <> 0) then
  12142.       // Use bitmaps own palette if possible
  12143.       Result := FBitmap.Palette
  12144.     else if (FGlobalPalette <> 0) then
  12145.       // Or a previously exported global palette
  12146.       Result := FGlobalPalette
  12147.     else if (DoDither) then
  12148.     begin
  12149.       // or create a new dither palette
  12150.       FGlobalPalette := WebPalette;
  12151.       Result := FGlobalPalette;
  12152.     end else
  12153.     if (FHeader.ColorMap.Count > 0) then
  12154.     begin
  12155.       // or create a new if first time
  12156.       FGlobalPalette := FHeader.ColorMap.ExportPalette;
  12157.       Result := FGlobalPalette;
  12158.     end else
  12159.     if (FImages.Count > 0) then
  12160.       // This can cause a recursion if no global palette exist and image[0]
  12161.       // hasn't got one either. Checked by the IsInsideGetPalette semaphor.
  12162.       Result := FImages[0].Palette;
  12163.   finally
  12164.     IsInsideGetPalette := False;
  12165.   end;
  12166. end;
  12167.  
  12168. procedure TGIFImage.SetPalette(Value: HPalette);
  12169. var
  12170.   NeedNewBitmap     : boolean;
  12171. begin
  12172.   if (Value <> FGlobalPalette) then
  12173.   begin
  12174.     // Zap old palette
  12175.     if (FGlobalPalette <> 0) then
  12176.       DeleteObject(FGlobalPalette);
  12177.  
  12178.     // Zap bitmap unless new palette is same as bitmaps own
  12179.     NeedNewBitmap := (FBitmap <> nil) and (Value <> FBitmap.Palette);
  12180.  
  12181.     // Use new palette
  12182.     FGlobalPalette := Value;
  12183.  
  12184.     if (NeedNewBitmap) then
  12185.     begin
  12186.       // Need to create new bitmap and repaint
  12187.       FreeBitmap;
  12188.       PaletteModified := True;
  12189.       Changed(Self);
  12190.     end;
  12191.   end;
  12192. end;
  12193.  
  12194. // Obsolete
  12195. // procedure TGIFImage.Changed(Sender: TObject);
  12196. // begin
  12197. //  inherited Changed(Sender);
  12198. // end;
  12199.  
  12200. procedure TGIFImage.SetHeight(Value: Integer);
  12201. var
  12202.   i         : integer;
  12203. begin
  12204.   for i := 0 to Images.Count-1 do
  12205.     if (Images[i].Top + Images[i].Height > Value) then
  12206.       Error(sBadHeight);
  12207.   if (Value <> Header.Height) then
  12208.   begin
  12209.     Header.Height := Value;
  12210.     FreeBitmap;
  12211.     Changed(self);
  12212.   end;
  12213. end;
  12214.  
  12215. procedure TGIFImage.SetWidth(Value: Integer);
  12216. var
  12217.   i         : integer;
  12218. begin
  12219.   for i := 0 to Images.Count-1 do
  12220.     if (Images[i].Left + Images[i].Width > Value) then
  12221.       Error(sBadWidth);
  12222.   if (Value <> Header.Width) then
  12223.   begin
  12224.     Header.Width := Value;
  12225.     FreeBitmap;
  12226.     Changed(self);
  12227.   end;
  12228. end;
  12229.  
  12230. procedure TGIFImage.WriteData(Stream: TStream);
  12231. begin
  12232.   if (GIFImageOptimizeOnStream) then
  12233.     Optimize([ooCrop, ooMerge, ooCleanup, ooColorMap, ooReduceColors], rmNone, dmNearest, 8);
  12234.  
  12235.   inherited WriteData(Stream);
  12236. end;
  12237.  
  12238. procedure TGIFImage.AssignTo(Dest: TPersistent);
  12239. begin
  12240.   if (Dest is TBitmap) then
  12241.     Dest.Assign(Bitmap)
  12242.   else
  12243.     inherited AssignTo(Dest);
  12244. end;
  12245.  
  12246. { TODO 1 -oanme -cImprovement : Better handling of TGIFImage.Assign(Empty TBitmap). }
  12247. procedure TGIFImage.Assign(Source: TPersistent);
  12248. var
  12249.   i         : integer;
  12250.   Image         : TGIFSubImage;
  12251. begin
  12252.   if (Source = self) then
  12253.     exit;
  12254.   if (Source = nil) then
  12255.   begin
  12256.     Clear;
  12257.   end else
  12258.   //
  12259.   // TGIFImage import
  12260.   //
  12261.   if (Source is TGIFImage) then
  12262.   begin
  12263.     Clear;
  12264.     // Temporarily copy event handlers to be able to generate progress events
  12265.     // during the copy and handle copy errors
  12266.     OnProgress := TGIFImage(Source).OnProgress;
  12267.     try
  12268.       FOnWarning := TGIFImage(Source).OnWarning;
  12269.       Progress(Self, psStarting, 0, False, Rect(0,0,0,0), sProgressCopying);
  12270.       try
  12271.         FHeader.Assign(TGIFImage(Source).Header);
  12272.         FThreadPriority := TGIFImage(Source).ThreadPriority;
  12273.         FDrawBackgroundColor := TGIFImage(Source).DrawBackgroundColor;
  12274.         FDrawOptions := TGIFImage(Source).DrawOptions;
  12275.         FColorReduction := TGIFImage(Source).ColorReduction;
  12276.         FDitherMode := TGIFImage(Source).DitherMode;
  12277.         FForceFrame := TGIFImage(Source).ForceFrame;  // 2004.03.09
  12278. // 2002.07.07 ->
  12279.         FOnWarning:= TGIFImage(Source).FOnWarning;
  12280.         FOnStartPaint:= TGIFImage(Source).FOnStartPaint;
  12281.         FOnPaint:= TGIFImage(Source).FOnPaint;
  12282.         FOnEndPaint:= TGIFImage(Source).FOnEndPaint;
  12283.         FOnAfterPaint:= TGIFImage(Source).FOnAfterPaint;
  12284.         FOnLoop:= TGIFImage(Source).FOnLoop;
  12285. // 2002.07.07 <-
  12286.         for i := 0 to TGIFImage(Source).Images.Count-1 do
  12287.         begin
  12288.           Image := TGIFSubImage.Create(self);
  12289.           Image.Assign(TGIFImage(Source).Images[i]);
  12290.           Add(Image);
  12291.           Progress(Self, psRunning, MulDiv((i+1), 100, TGIFImage(Source).Images.Count),
  12292.             False, Rect(0,0,0,0), sProgressCopying);
  12293.         end;
  12294.         {$IFDEF FIXHEADER_WIDTHHEIGHT_SILENT}
  12295.         FixHeaderWidthHeight;  // 2006.07.09
  12296.         {$ENDIF}
  12297.       finally
  12298.         if ExceptObject = nil then
  12299.           i := 100
  12300.         else
  12301.           i := 0;
  12302.         Progress(Self, psEnding, i, False, Rect(0,0,0,0), sProgressCopying);
  12303.       end;
  12304.     finally
  12305.       // Reset event handlers
  12306.       FOnWarning := nil;
  12307.       OnProgress := nil;
  12308.     end;
  12309.   end else
  12310.   //
  12311.   // Import via TGIFSubImage.Assign
  12312.   //
  12313.   begin
  12314.     Clear;
  12315.     Image := TGIFSubImage.Create(self);
  12316.     try
  12317.       Image.Assign(Source);
  12318.       Add(Image);
  12319.     except
  12320.       on E: EConvertError do
  12321.       begin
  12322.         Image.Free;
  12323.         // Unsupported format - fall back to Source.AssignTo
  12324.         inherited Assign(Source);
  12325.       end;
  12326.     else
  12327.       // Unknown conversion error
  12328.       Image.Free;
  12329.       raise;
  12330.     end;
  12331.   end;
  12332. end;
  12333.  
  12334. procedure TGIFImage.LoadFromClipboardFormat(AFormat: Word; AData: THandle;
  12335.   APalette: HPALETTE);
  12336. {$IFDEF REGISTER_TGIFIMAGE}
  12337. var
  12338.   Size          : Longint;
  12339.   Buffer        : Pointer;
  12340.   Stream        : TMemoryStream;
  12341.   Bmp           : TBitmap;
  12342. {$ENDIF}  // 2002.07.07
  12343. begin  // 2002.07.07
  12344. {$IFDEF REGISTER_TGIFIMAGE}  // 2002.07.07
  12345.   if (AData = 0) then
  12346.     AData := GetClipboardData(AFormat);
  12347.   if (AData <> 0) and (AFormat = CF_GIF) then
  12348.   begin
  12349.     // Get size and pointer to data
  12350.     Size := GlobalSize(AData);
  12351.     Buffer := GlobalLock(AData);
  12352.     try
  12353.       Stream := TMemoryStream.Create;
  12354.       try
  12355.         // Copy data to a stream
  12356.         Stream.SetSize(Size);
  12357.         Move(Buffer^, Stream.Memory^, Size);
  12358.         // Load GIF from stream
  12359.         LoadFromStream(Stream);
  12360.       finally
  12361.         Stream.Free;
  12362.       end;
  12363.     finally
  12364.       GlobalUnlock(AData);
  12365.     end;
  12366.   end else
  12367.   if (AData <> 0) and (AFormat = CF_BITMAP) then
  12368.   begin
  12369.     // No GIF on clipboard - try loading a bitmap instead
  12370.     Bmp := TBitmap.Create;
  12371.     try
  12372.       Bmp.LoadFromClipboardFormat(AFormat, AData, APalette);
  12373.       Assign(Bmp);
  12374.     finally
  12375.       Bmp.Free;
  12376.     end;
  12377.   end else
  12378.     Error(sUnknownClipboardFormat);
  12379. {$ELSE}  // 2002.07.07
  12380.   Error(sGIFToClipboard);  // 2002.07.07
  12381. {$ENDIF}  // 2002.07.07
  12382. end;
  12383.  
  12384. procedure TGIFImage.SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
  12385.   var APalette: HPALETTE);
  12386. {$IFDEF REGISTER_TGIFIMAGE}
  12387. var
  12388.   Stream        : TMemoryStream;
  12389.   Data          : THandle;
  12390.   Buffer        : Pointer;
  12391. {$ENDIF}  // 2002.07.07
  12392. begin  // 2002.07.07
  12393. {$IFDEF REGISTER_TGIFIMAGE}  // 2002.07.07
  12394.   if (Empty) then
  12395.     exit;
  12396.   // First store a bitmap version on the clipboard...
  12397.   Bitmap.SaveToClipboardFormat(AFormat, AData, APalette);
  12398.   // ...then store a GIF
  12399.   Stream := TMemoryStream.Create;
  12400.   try
  12401.     // Save the GIF to a memory stream
  12402.     SaveToStream(Stream);
  12403.     Stream.Position := 0;
  12404.     // Allocate some memory for the GIF data
  12405.     Data := GlobalAlloc(HeapAllocFlags, Stream.Size);
  12406.     try
  12407.       if (Data <> 0) then
  12408.       begin
  12409.         Buffer := GlobalLock(Data);
  12410.         try
  12411.           // Copy GIF data from stream memory to clipboard memory
  12412.           Move(Stream.Memory^, Buffer^, Stream.Size);
  12413.         finally
  12414.           GlobalUnlock(Data);
  12415.         end;
  12416.         // Transfer data to clipboard
  12417.         if (SetClipboardData(CF_GIF, Data) = 0) then
  12418.           Error(sFailedPaste);
  12419.       end;
  12420.     except
  12421.       GlobalFree(Data);
  12422.       raise;
  12423.     end;
  12424.   finally
  12425.     Stream.Free;
  12426.   end;
  12427. {$ELSE}  // 2002.07.07
  12428.   Error(sGIFToClipboard);  // 2002.07.07
  12429. {$ENDIF}  // 2002.07.07
  12430. end;
  12431.  
  12432. function TGIFImage.GetColorMap: TGIFColorMap;
  12433. begin
  12434.   Result := FHeader.ColorMap;
  12435. end;
  12436.  
  12437. function TGIFImage.GetDoDither: boolean;
  12438. begin
  12439.   Result := (goDither in DrawOptions) and
  12440.     (((goAutoDither in DrawOptions) and DoAutoDither) or
  12441.       not(goAutoDither in DrawOptions));
  12442. end;
  12443.  
  12444. {$IFDEF VER9x}
  12445. procedure TGIFImage.Progress(Sender: TObject; Stage: TProgressStage;
  12446.   PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string);
  12447. begin
  12448.   if Assigned(FOnProgress) then
  12449.     FOnProgress(Sender, Stage, PercentDone, RedrawNow, R, Msg);
  12450. end;
  12451. {$ENDIF}
  12452.  
  12453. procedure TGIFImage.StopDraw;
  12454. {$IFNDEF VER14_PLUS}  // 2001.07.23
  12455. var
  12456.   Msg           : TMsg;
  12457.   ThreadWindow      : HWND;
  12458. {$ENDIF}  // 2001.07.23
  12459. begin
  12460.   repeat
  12461.     // Use the FPainters threadlist to protect FDrawPainter from being modified
  12462.     // by the thread while we mess with it
  12463.     with FPainters.LockList do
  12464.       try
  12465.         if (FDrawPainter = nil) then
  12466.           break;
  12467.  
  12468.         // Tell thread to terminate
  12469.         FDrawPainter.Stop;
  12470.  
  12471.         // No need to wait for "thread" to terminate if running in main thread
  12472.         if not(goAsync in FDrawPainter.DrawOptions) then
  12473.           break;
  12474.  
  12475.       finally
  12476.         // Release the lock on FPainters to let paint thread kill itself
  12477.         FPainters.UnLockList;
  12478.       end;
  12479.  
  12480. {$IFDEF VER14_PLUS}
  12481. // 2002.07.07
  12482.     if (GetCurrentThreadID = MainThreadID) then
  12483.       while CheckSynchronize do {loop};
  12484. {$ELSE}
  12485.     // Process Messages to make Synchronize work
  12486.     // (Instead of Application.ProcessMessages)
  12487. //{$IFDEF VER14_PLUS}  // 2001.07.23
  12488. //    Break;  // 2001.07.23
  12489. //    Sleep(0); // Yield  // 2001.07.23
  12490. //{$ELSE}  // 2001.07.23
  12491.     ThreadWindow := FindWindow('TThreadWindow', nil);
  12492.     while PeekMessage(Msg, ThreadWindow, CM_DESTROYWINDOW, CM_EXECPROC, PM_REMOVE) do
  12493.     begin
  12494.       if (Msg.Message <> WM_QUIT) then
  12495.       begin
  12496.         TranslateMessage(Msg);
  12497.         DispatchMessage(Msg);
  12498.       end else
  12499.       begin
  12500.         PostQuitMessage(Msg.WParam);
  12501.         exit;
  12502.       end;
  12503.     end;
  12504. {$ENDIF}  // 2001.07.23
  12505.     Sleep(0); // Yield
  12506.  
  12507.   until (False);
  12508.   FreeBitmap;
  12509. end;
  12510.  
  12511. procedure TGIFImage.Draw(ACanvas: TCanvas; const Rect: TRect);
  12512. var
  12513.   Canvas        : TCanvas;
  12514.   DestRect      : TRect;
  12515. {$IFNDEF VER14_PLUS}  // 2001.07.23
  12516.   Msg           : TMsg;
  12517.   ThreadWindow      : HWND;
  12518. {$ENDIF}  // 2001.07.23
  12519.  
  12520.   procedure DrawTile(Rect: TRect; Bitmap: TBitmap);
  12521.   var
  12522.     Tile        : TRect;
  12523.   begin
  12524.     if (goTile in FDrawOptions) then
  12525.     begin
  12526.       // Note: This design does not handle transparency correctly!
  12527.       Tile.Left := Rect.Left;
  12528.       Tile.Right := Tile.Left + Width;
  12529.       while (Tile.Left < Rect.Right) do
  12530.       begin
  12531.         Tile.Top := Rect.Top;
  12532.         Tile.Bottom := Tile.Top + Height;
  12533.         while (Tile.Top < Rect.Bottom) do
  12534.         begin
  12535.           ACanvas.StretchDraw(Tile, Bitmap);
  12536.           Tile.Top := Tile.Top + Height;
  12537.           Tile.Bottom := Tile.Top + Height;
  12538.         end;
  12539.         Tile.Left := Tile.Left + Width;
  12540.         Tile.Right := Tile.Left + Width;
  12541.       end;
  12542.     end else
  12543.       ACanvas.StretchDraw(Rect, Bitmap);
  12544.   end;
  12545.  
  12546. begin
  12547.   // Prevent recursion(s(s(s)))
  12548.   if (IsDrawing) or (FImages.Count = 0) then
  12549.     exit;
  12550.  
  12551.   IsDrawing := True;
  12552.   try
  12553.     // Copy bitmap to canvas if we are already drawing
  12554.     // (or have drawn but are finished)
  12555.     if (FImages.Count = 1) or // Only one image
  12556.       (not (goAnimate in FDrawOptions)) then // Don't animate
  12557.     begin
  12558.       // 2004.03.09 ->
  12559.       if (FForceFrame >= 0) and (FForceFrame < FImages.Count) then
  12560.         FImages[FForceFrame].Draw(ACanvas, Rect, (goTransparent in FDrawOptions), (goTile in FDrawOptions))
  12561.       else
  12562.       // 2004.03.09 <-
  12563.         FImages[0].Draw(ACanvas, Rect, (goTransparent in FDrawOptions), (goTile in FDrawOptions));
  12564.       exit;
  12565.     end else
  12566.     if (FBitmap <> nil) and not(goDirectDraw in FDrawOptions) then
  12567.     begin
  12568.       DrawTile(Rect, Bitmap);
  12569.       exit;
  12570.     end;
  12571.  
  12572.     // Use the FPainters threadlist to protect FDrawPainter from being modified
  12573.     // by the thread while we mess with it
  12574.     with FPainters.LockList do
  12575.       try
  12576.       // If we are already painting on the canvas in goDirectDraw mode
  12577.       // and at the same location, just exit and let the painter do
  12578.       // its thing when it's ready
  12579.       if (FDrawPainter <> nil) and (FDrawPainter.Canvas = ACanvas) and
  12580.         EqualRect(FDrawPainter.Rect, Rect) then
  12581.         exit;
  12582.  
  12583.       // Kill the current paint thread
  12584.       StopDraw;
  12585.  
  12586.       if not(goDirectDraw in FDrawOptions) then
  12587.       begin
  12588.         // Create a bitmap to draw on
  12589.         NewBitmap;
  12590.         Canvas := FBitmap.Canvas;
  12591.         DestRect := Canvas.ClipRect;
  12592.         // Initialize bitmap canvas with background image
  12593.         Canvas.CopyRect(DestRect, ACanvas, Rect);
  12594.       end else
  12595.       begin
  12596.         Canvas := ACanvas;
  12597.         DestRect := Rect;
  12598.       end;
  12599.  
  12600.       // Create new paint thread
  12601.       InternalPaint(@FDrawPainter, Canvas, DestRect, FDrawOptions);
  12602.  
  12603.       if (FDrawPainter <> nil) then
  12604.       begin
  12605.         // Launch thread
  12606.         FDrawPainter.Start;
  12607.  
  12608.         if not(goDirectDraw in FDrawOptions) then
  12609.         begin
  12610. {$IFDEF VER14_PLUS}
  12611. // 2002.07.07
  12612.           while (FDrawPainter <> nil) and (not FDrawPainter.Terminated) and
  12613.             (not FDrawPainter.Started) do
  12614.           begin
  12615.             if not CheckSynchronize then
  12616.               Sleep(0); // Yield
  12617.           end;
  12618. {$ELSE}
  12619. //{$IFNDEF VER14_PLUS}  // 2001.07.23
  12620.           ThreadWindow := FindWindow('TThreadWindow', nil);
  12621.           // Wait for thread to render first frame
  12622.           while (FDrawPainter <> nil) and (not FDrawPainter.Terminated) and
  12623.             (not FDrawPainter.Started) do
  12624.             // Process Messages to make Synchronize work
  12625.             // (Instead of Application.ProcessMessages)
  12626.             if PeekMessage(Msg, ThreadWindow, CM_DESTROYWINDOW, CM_EXECPROC, PM_REMOVE) then
  12627.             begin
  12628.               if (Msg.Message <> WM_QUIT) then
  12629.               begin
  12630.                 TranslateMessage(Msg);
  12631.                 DispatchMessage(Msg);
  12632.               end else
  12633.               begin
  12634.                 PostQuitMessage(Msg.WParam);
  12635.                 exit;
  12636.               end;
  12637.             end else
  12638.               Sleep(0); // Yield
  12639. {$ENDIF}  // 2001.07.23
  12640.           // Draw frame to destination
  12641.           DrawTile(Rect, Bitmap);
  12642.         end;
  12643.       end;
  12644.     finally
  12645.       FPainters.UnLockList;
  12646.     end;
  12647.  
  12648.   finally
  12649.     IsDrawing := False;
  12650.   end;
  12651. end;
  12652.  
  12653. // Internal pain(t) routine used by Draw()
  12654. function TGIFImage.InternalPaint(Painter: PGifPainter; ACanvas: TCanvas;
  12655.   const Rect: TRect; Options: TGIFDrawOptions): TGIFPainter;
  12656. begin
  12657.   if (Empty) or (Rect.Left >= Rect.Right) or (Rect.Top >= Rect.Bottom) then
  12658.   begin
  12659.     Result := nil;
  12660.     if (Painter <> nil) then
  12661.       Painter^ := Result;
  12662.     exit;
  12663.   end;
  12664.  
  12665.   // Draw in main thread if only one image
  12666.   if (Images.Count = 1) then
  12667.     Options := Options - [goAsync, goAnimate];
  12668.  
  12669.   Result := TGIFPainter.CreateRef(Painter, self, ACanvas, Rect, Options);
  12670.   FPainters.Add(Result);
  12671.   Result.OnStartPaint := FOnStartPaint;
  12672.   Result.OnPaint := FOnPaint;
  12673.   Result.OnAfterPaint := FOnAfterPaint;
  12674.   Result.OnLoop := FOnLoop;
  12675.   Result.OnEndPaint := FOnEndPaint;
  12676.  
  12677.   if not(goAsync in Options) then
  12678.   begin
  12679.     // Run in main thread
  12680.     Result.Execute;
  12681.     // Note: Painter threads executing in the main thread are freed upon exit
  12682.     // from the Execute method, so no need to do it here.
  12683.     Result := nil;
  12684.     if (Painter <> nil) then
  12685.       Painter^ := Result;
  12686.   end else
  12687.     Result.Priority := FThreadPriority;
  12688. end;
  12689.  
  12690. function TGIFImage.Paint(ACanvas: TCanvas; const Rect: TRect;
  12691.   Options: TGIFDrawOptions): TGIFPainter;
  12692. begin
  12693.   Result := InternalPaint(nil, ACanvas, Rect, Options);
  12694.   if (Result <> nil) then
  12695.     // Run in separate thread
  12696.     Result.Start;
  12697. end;
  12698.  
  12699. procedure TGIFImage.PaintStart;
  12700. var
  12701.   i         : integer;
  12702. begin
  12703.   with FPainters.LockList do
  12704.     try
  12705.       for i := 0 to Count-1 do
  12706.         TGIFPainter(Items[i]).Start;
  12707.     finally
  12708.       FPainters.UnLockList;
  12709.     end;
  12710. end;
  12711.  
  12712. procedure TGIFImage.PaintStop;
  12713. var
  12714.   Ghosts        : integer;
  12715.   i         : integer;
  12716. {$IFNDEF VER14_PLUS}  // 2001.07.23
  12717.   Msg           : TMsg;
  12718.   ThreadWindow      : HWND;
  12719. {$ENDIF}  // 2001.07.23
  12720.  
  12721. {$IFNDEF VER14_PLUS}  // 2001.07.23
  12722.   procedure KillThreads;
  12723.   var
  12724.     i           : integer;
  12725.   begin
  12726.     with FPainters.LockList do
  12727.       try
  12728.         for i := Count-1 downto 0 do
  12729.           if (goAsync in TGIFPainter(Items[i]).DrawOptions) then
  12730.           begin
  12731.             TerminateThread(TGIFPainter(Items[i]).Handle, 0);
  12732.             Delete(i);
  12733.           end;
  12734.       finally
  12735.         FPainters.UnLockList;
  12736.       end;
  12737.   end;
  12738. {$ENDIF}  // 2001.07.23
  12739.  
  12740. begin
  12741.   try
  12742.     // Loop until all have died
  12743.     repeat
  12744.       with FPainters.LockList do
  12745.         try
  12746.           if (Count = 0) then
  12747.             exit;
  12748.  
  12749.           // Signal painters to terminate
  12750.           // Painters will attempt to remove them self from the
  12751.           // painter list when they die
  12752.           Ghosts := Count;
  12753.           for i := Ghosts-1 downto 0 do
  12754.           begin
  12755.             if not(goAsync in TGIFPainter(Items[i]).DrawOptions) then
  12756.               dec(Ghosts);
  12757.             TGIFPainter(Items[i]).Stop;
  12758.           end;
  12759.         finally
  12760.           FPainters.UnLockList;
  12761.         end;
  12762.  
  12763.       // If all painters were synchronous, there's no purpose waiting for them
  12764.       // to terminate, because they are running in the main thread.
  12765.       if (Ghosts = 0) then
  12766.         exit;
  12767. {$IFDEF VER14_PLUS}
  12768. // 2002.07.07
  12769.       if (GetCurrentThreadID = MainThreadID) then
  12770.         while CheckSynchronize do {loop};
  12771. {$ELSE}
  12772.       // Process Messages to make TThread.Synchronize work
  12773.       // (Instead of Application.ProcessMessages)
  12774. //{$IFDEF VER14_PLUS}  // 2001.07.23
  12775. //      Exit;  // 2001.07.23
  12776. //{$ELSE}  // 2001.07.23
  12777.       ThreadWindow := FindWindow('TThreadWindow', nil);
  12778.       if (ThreadWindow = 0) then
  12779.       begin
  12780.         KillThreads;
  12781.         Exit;
  12782.       end;
  12783.       while PeekMessage(Msg, ThreadWindow, CM_DESTROYWINDOW, CM_EXECPROC, PM_REMOVE) do
  12784.       begin
  12785.         if (Msg.Message <> WM_QUIT) then
  12786.         begin
  12787.           TranslateMessage(Msg);
  12788.           DispatchMessage(Msg);
  12789.         end else
  12790.         begin
  12791.           KillThreads;
  12792.           Exit;
  12793.         end;
  12794.       end;
  12795. {$ENDIF}  // 2001.07.23
  12796.       Sleep(0);
  12797.     until (False);
  12798.   finally
  12799.     FreeBitmap;
  12800.   end;
  12801. end;
  12802.  
  12803. procedure TGIFImage.PaintPause;
  12804. var
  12805.   i         : integer;
  12806. begin
  12807.   with FPainters.LockList do
  12808.     try
  12809.       for i := 0 to Count-1 do
  12810.         TGIFPainter(Items[i]).Suspend;
  12811.     finally
  12812.       FPainters.UnLockList;
  12813.     end;
  12814. end;
  12815.  
  12816. procedure TGIFImage.PaintResume;
  12817. var
  12818.   i         : integer;
  12819. begin
  12820.   // Implementation is currently same as PaintStart, but don't call PaintStart
  12821.   // in case its implementation changes
  12822.   with FPainters.LockList do
  12823.     try
  12824.       for i := 0 to Count-1 do
  12825.         TGIFPainter(Items[i]).Start;
  12826.     finally
  12827.       FPainters.UnLockList;
  12828.     end;
  12829. end;
  12830.  
  12831. procedure TGIFImage.PaintRestart;
  12832. var
  12833.   i         : integer;
  12834. begin
  12835.   with FPainters.LockList do
  12836.     try
  12837.       for i := 0 to Count-1 do
  12838.         TGIFPainter(Items[i]).Restart;
  12839.     finally
  12840.       FPainters.UnLockList;
  12841.     end;
  12842. end;
  12843.  
  12844. procedure TGIFImage.Warning(Sender: TObject; Severity: TGIFSeverity; Message: string);
  12845. begin
  12846.   if (Assigned(FOnWarning)) then
  12847.     FOnWarning(Sender, Severity, Message);
  12848. end;
  12849.  
  12850. {$IFDEF VER12_PLUS}
  12851.   {$IFNDEF VER14_PLUS} // not anymore need for Delphi 6 and up  // 2001.07.23
  12852. type
  12853.   TDummyThread = class(TThread)
  12854.   protected
  12855.     procedure Execute; override;
  12856.   end;
  12857. procedure TDummyThread.Execute;
  12858. begin
  12859. end;
  12860.   {$ENDIF}  // 2001.07.23
  12861. {$ENDIF}
  12862.  
  12863. var
  12864.   DesktopDC: HDC;
  12865. {$IFDEF VER12_PLUS}
  12866.   {$IFNDEF VER14_PLUS} // not anymore need for Delphi 6 and up  // 2001.07.23
  12867.   DummyThread: TThread;
  12868.   {$ENDIF}  // 2001.07.23
  12869. {$ENDIF}
  12870.  
  12871. ////////////////////////////////////////////////////////////////////////////////
  12872. //
  12873. //          Initialization
  12874. //
  12875. ////////////////////////////////////////////////////////////////////////////////
  12876.  
  12877. initialization
  12878. {$IFDEF REGISTER_TGIFIMAGE}
  12879.   TPicture.RegisterFileFormat('GIF', sGIFImageFile, TGIFImage);
  12880. // 2008.10.19 ->
  12881. {$IFDEF VER20_PLUS}
  12882.   CF_GIF := RegisterClipboardFormat(PWideChar(sGIFImageFile));
  12883. {$ELSE}
  12884.   CF_GIF := RegisterClipboardFormat(PAnsiChar(sGIFImageFile));
  12885. {$ENDIF}
  12886. // 2008.10.19 <-
  12887.   TPicture.RegisterClipboardFormat(CF_GIF, TGIFImage);
  12888. {$ENDIF}
  12889.   DesktopDC := GetDC(0);
  12890.   try
  12891.     PaletteDevice := (GetDeviceCaps(DesktopDC, BITSPIXEL) * GetDeviceCaps(DesktopDC, PLANES) <= 8);
  12892.     DoAutoDither := PaletteDevice;
  12893.   finally
  12894.     ReleaseDC(0, DesktopDC);
  12895.   end;
  12896.  
  12897. {$IFDEF VER9x}
  12898.   // Note: This doesn't return the same palette as the Delphi 3 system palette
  12899.   // since the true system palette contains 20 entries and the Delphi 3 system
  12900.   // palette only contains 16.
  12901.   // For our purpose this doesn't matter since we do not care about the actual
  12902.   // colors (or their number) in the palette.
  12903.   // Stock objects doesn't have to be deleted.
  12904.   SystemPalette16 := GetStockObject(DEFAULT_PALETTE);
  12905. {$ENDIF}
  12906. {$IFDEF VER12_PLUS}
  12907.   // Make sure that at least one thread always exist.
  12908.   // This is done to circumvent a race condition bug in Delphi 4.x and later:
  12909.   // When threads are deleted and created in rapid succesion, a situation might
  12910.   // arise where the thread window is deleted *after* the threads it controls
  12911.   // has been created. See the Delphi Bug Lists for more information.
  12912.   {$IFNDEF VER14_PLUS} // not anymore need for Delphi 6 and up  // 2001.07.23
  12913.   DummyThread := TDummyThread.Create(True);
  12914.   {$ENDIF}  // 2001.07.23
  12915. {$ENDIF}
  12916.  
  12917. ////////////////////////////////////////////////////////////////////////////////
  12918. //
  12919. //          Finalization
  12920. //
  12921. ////////////////////////////////////////////////////////////////////////////////
  12922. finalization
  12923.   ExtensionList.Free;
  12924.   AppExtensionList.Free;
  12925. {$IFNDEF VER9x}
  12926.   {$IFDEF REGISTER_TGIFIMAGE}
  12927.     TPicture.UnregisterGraphicClass(TGIFImage);
  12928.   {$ENDIF}
  12929.   {$IFDEF VER100}
  12930.   if (pf8BitBitmap <> nil) then
  12931.     pf8BitBitmap.Free;
  12932.   {$ENDIF}
  12933. {$ENDIF}
  12934. {$IFDEF VER12_PLUS}
  12935.   {$IFNDEF VER14_PLUS} // not anymore need for Delphi 6 and up  // 2001.07.23
  12936.   if (DummyThread <> nil) then
  12937. // 2006.10.16 ->
  12938. //    DummyThread.Free;
  12939.   begin
  12940.     DummyThread.Resume;
  12941.     DummyThread.WaitFor;
  12942.     DummyThread.Free;
  12943.   end;
  12944. // 2006.10.16 <-
  12945.   {$ENDIF}  // 2001.07.23
  12946. {$ENDIF}
  12947. end.
Add Comment
Please, Sign In to add comment