home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / wps / utils / scrnsave / hopalong / source / hopalong.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-01-21  |  16.0 KB  |  486 lines

  1. /*
  2.     hopalong.c
  3.     Hopalong saver module C source file version 1.0   21 / 1 / 94
  4.     (C) 1994 Toniolo Emanuele
  5.  
  6. */
  7.                                                                   
  8. #define INCL_DOS
  9. #define INCL_DOSERRORS
  10. #define INCL_WIN
  11. #define INCL_GPI
  12. #define INCL_PM
  13. #include <os2.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <limits.h>
  18. #include <process.h>
  19. #include <math.h>
  20.  
  21. #include "hopalong.h"
  22.  
  23. // ===== preprocessor definitions
  24.  
  25. #define MODULEVERSION            0x00010001
  26. #define STACKSIZE                 32000
  27. #define SAVER_NAME_MAXLEN       32
  28. #define FUNCTION_CONFIGURE       1
  29. #define FUNCTION_STARTSAVER    2
  30. #define FUNCTION_STOPSAVER         3
  31. #define FUNCTION_QUERYNAME         4
  32. #define FUNCTION_QUERYENABLED    5
  33. #define FUNCTION_SETENABLED    6
  34.  
  35. #define CONFIGURATION_MINIMUM_COUNT             1
  36. #define CONFIGURATION_DEFAULT_COUNT             500
  37. #define CONFIGURATION_MAXIMUM_COUNT             5000
  38.  
  39. // ===== prototypes
  40.  
  41. void    EXPENTRY SAVER_PROC(int function, HAB _hab, HWND hwndOwner, char *appname, void *buffer);
  42. static    MRESULT EXPENTRY SaverWindowProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2);
  43. static    MRESULT    EXPENTRY ConfigureDlgProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2);
  44. #if defined(__IBMC__)
  45. static    void    _Optlink draw_thread(void *args);
  46. static    void    _Optlink priority_thread(void *args);
  47. #elif defined(__BORLANDC__)
  48. static    void    _USERENTRY draw_thread(void *args);
  49. static    void    _USERENTRY priority_thread(void *args);
  50. #else
  51. static    void    draw_thread(void *args);
  52. static    void    priority_thread(void *args);
  53. #endif
  54. static    void    load_configuration_data(void);
  55.  
  56.  
  57.  
  58. // ===== global data
  59.  
  60. static    LONG       screenSizeX = 0;             // screen size x
  61. static    LONG       screenSizeY = 0;             // screen size y
  62. static    HWND       hwndSaver = NULLHANDLE;         // saver window handle
  63. static    HMODULE    hmodDLL = NULLHANDLE;        // saver module dll handle
  64. static    char       *application_name;             // name of ScreenSaver app
  65. static    TID       tidDraw;                          // drawing-thread ID
  66. static    HPS       hps;                              // presentation space handle
  67. static    HAB       hab;                              // anchor block handle
  68. static    BOOL       low_priority = TRUE;             // low-priority flag
  69. static    BOOL       configuration_data_loaded = FALSE;  // config data loaded flag
  70. static    volatile BOOL stop_draw_thread;         // stop flag
  71. static    char       modulename[SAVER_NAME_MAXLEN+1];    // module name buffer
  72.  
  73. static    struct    _configuration_data {
  74.     ULONG       version;
  75.     BOOL       enabled;
  76.    int      count;
  77. } configuration_data;
  78.  
  79.  
  80. // ===== code
  81.  
  82. /*
  83.     SAVER_PROC
  84.     This is the entry point into the saver module that is called by
  85.     the ScreenSaver program.
  86.     There should be no reason to alter the code.
  87.     Depending on the requested function, the following tasks
  88.     are performed:
  89.     * call the configuration dialog of the saver module
  90.     * copy the name of the saver module into the supplied buffer
  91.     * tell if the saver module is enabled
  92.     * set the "enabled" state of the saver module
  93.     * start the saver
  94.     * stop the saver
  95.     Note that before any processing is done, module configuration data is
  96.     loaded from the INI-files.
  97. */
  98. void    EXPENTRY SAVER_PROC(int function, HAB _hab, HWND hwndOwner, char *appname, void *buffer)
  99. {
  100. #if defined(__BORLANDC__)
  101.     extern ULONG _os2hmod;
  102.     hmodDLL = _os2hmod;
  103. #endif    
  104.     hab = _hab;
  105.     application_name = appname;
  106.     // load all configuration data from INI-file
  107.     load_configuration_data();
  108.     switch(function){
  109.     case FUNCTION_CONFIGURE:
  110.         // call the configuration dialog
  111.         WinDlgBox(HWND_DESKTOP, hwndOwner, ConfigureDlgProc,
  112.           hmodDLL, IDD_CONFIGURE, application_name);
  113.         return;
  114.     case FUNCTION_STARTSAVER:
  115.         // start the saver
  116.         // get "low priority" state from supplied buffer (BOOL *)
  117.         low_priority = *((BOOL *)buffer);
  118.         // random seed
  119.         srand(WinGetCurrentTime(hab));
  120.         // query size of screen
  121.         screenSizeX = WinQuerySysValue(HWND_DESKTOP, SV_CXSCREEN);
  122.         screenSizeY = WinQuerySysValue(HWND_DESKTOP, SV_CYSCREEN);
  123.         // register window class for the saver window
  124.         WinRegisterClass(hab, modulename,
  125.           (PFNWP)SaverWindowProc, 0, 0);
  126.         // create the saver window
  127.         hwndSaver = WinCreateWindow(HWND_DESKTOP, modulename,
  128.           (PSZ)NULL, WS_VISIBLE, 0, 0, screenSizeX, screenSizeY,
  129.           HWND_DESKTOP, HWND_TOP, 0, NULL, NULL);
  130.         return;
  131.     case FUNCTION_STOPSAVER:
  132.         // stop the saver
  133.         if(hwndSaver != NULLHANDLE){
  134.             // move saver window to front
  135.             WinSetWindowPos(hwndSaver, HWND_TOP,
  136.               0, 0, 0, 0, SWP_ZORDER);
  137.             // destroy saver window
  138.             WinDestroyWindow(hwndSaver);
  139.             hwndSaver = NULLHANDLE;
  140.         }
  141.         return;
  142.     case FUNCTION_QUERYNAME:
  143.         // copy module name to supplied buffer (CHAR *)
  144.         strcpy(buffer, modulename);
  145.         return;
  146.     case FUNCTION_QUERYENABLED:
  147.         // copy "enabled" state to supplied buffer (BOOL *)
  148.         *((BOOL *)buffer) = configuration_data.enabled;
  149.         return;
  150.     case FUNCTION_SETENABLED:
  151.         // get new "enabled" state from supplied buffer (BOOL *)
  152.         configuration_data.enabled = *((BOOL *)buffer);
  153.         PrfWriteProfileData(HINI_USER, (PSZ)application_name, (PSZ)modulename, (PSZ)&configuration_data, sizeof(configuration_data));
  154.         return;
  155.     }
  156.  
  157.     // illegal function request
  158.     WinAlarm(HWND_DESKTOP, WA_ERROR);
  159.     return;
  160. }
  161.  
  162. #if !defined(__BORLANDC__)
  163. /*
  164.     _DLL_InitTerm
  165.     This procedure is called at DLL initialization and termination.
  166.     There should be no reason to alter the code.
  167. */
  168. ULONG    _DLL_InitTerm(HMODULE hmod, ULONG flag)
  169. {
  170.     switch(flag){
  171.     case 0:    // initializing DLL
  172.         hmodDLL = hmod;
  173.         return 1;
  174.     case 1: // terminating DLL
  175.         return 1;
  176.     default:
  177.         // return error
  178.         return 0;
  179.     }
  180. }
  181. #endif
  182.  
  183. /*
  184.     ConfigureDlgProc
  185.     This is the dialog procedure for the module configuration dialog.
  186.     The dialog contains a check box for enabling/disabling the module
  187.     and two push buttons ("OK" and "Cancel") to close/cancel the dialog.
  188.     This is enough for simple saver modules, but can easily be expanded
  189.     for more saver modules that need more settings.
  190. */
  191. MRESULT    EXPENTRY ConfigureDlgProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
  192. {
  193.     char    buf[sizeof(modulename)+20];
  194.     static    HWND    hwndEnabled;
  195.     static    HWND    hwndCount;
  196.  
  197.     switch(msg){
  198.     case WM_INITDLG:
  199.         // set titlebar of the dialog window
  200.         // to "MODULENAME configuration"
  201.         strcpy(buf, modulename);
  202.         strcat(buf, " configuration");
  203.         WinSetWindowText(hwnd, buf);
  204.  
  205.         // get  window handles of the dialog controls
  206.         // and set initial state of the controls
  207.         hwndEnabled = WinWindowFromID(hwnd, IDC_ENABLED);
  208.         WinSendMsg(hwndEnabled, BM_SETCHECK,MPFROMSHORT(configuration_data.enabled), MPVOID);
  209.  
  210.         hwndCount = WinWindowFromID(hwnd, IDC_COUNT);
  211.         WinSendMsg(hwndCount, SPBM_SETLIMITS, (MPARAM)CONFIGURATION_MAXIMUM_COUNT, (MPARAM)CONFIGURATION_MINIMUM_COUNT);
  212.         WinSendMsg(hwndCount, SPBM_SETCURRENTVALUE, MPFROMSHORT(configuration_data.count), MPVOID);
  213.  
  214.         // return FALSE since we did not change the focus        
  215.       return (MRESULT)FALSE;
  216.  
  217.  
  218.     case WM_COMMAND:
  219.         switch(SHORT1FROMMP(mp1)){
  220.         case IDC_OK:
  221.             // OK button was pressed. query the control settings
  222.             configuration_data.enabled = SHORT1FROMMR(WinSendMsg(hwndEnabled, BM_QUERYCHECK, MPVOID, MPVOID));
  223.  
  224.          WinSendMsg(hwndCount, SPBM_QUERYVALUE, MPFROMP(&configuration_data.count), MPFROM2SHORT(0, SPBQ_DONOTUPDATE));
  225.  
  226.             // write all configuration data to INI-file
  227.             PrfWriteProfileData(HINI_USER, (PSZ)application_name, (PSZ)modulename, (PSZ)&configuration_data, sizeof(configuration_data));
  228.             // end dialog
  229.             WinDismissDlg(hwnd, TRUE);
  230.             return (MRESULT)0;
  231.  
  232.         case IDC_CANCEL:
  233.             // dialog was cancelled; end it
  234.             WinDismissDlg(hwnd, FALSE);
  235.             return (MRESULT)0;
  236.  
  237.         default:
  238.             return (MRESULT)0;
  239.         }
  240.     }
  241.     return WinDefDlgProc(hwnd, msg, mp1, mp2);
  242. }
  243.  
  244. /*
  245.     SaverWindowProc
  246.     This is the window procedure of the screen-size window that is
  247.     created when the saver starts.
  248.     There should be no reason to alter the code.
  249.     Note that we do not process WM_PAINT messages. They are forwarded to
  250.     the default window procedure, which just validates the window area
  251.     and does no drawing. All drawing to the window should be done in
  252.     the drawing-thread. Therefore, if you want to blank the screen before
  253.     drawing on it for instance, issue a WinFillRect call at the beginning
  254.     of your drawing-thread.
  255. */
  256. MRESULT EXPENTRY SaverWindowProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
  257. {
  258.     static    TID    tidPriority;
  259.  
  260.     switch(msg){
  261.     case WM_CREATE:
  262.         // reset the "stop" flag
  263.         stop_draw_thread = FALSE;
  264.         // store window handle
  265.         hwndSaver = hwnd;
  266.         // get presentation space
  267.         hps = WinGetPS(hwnd);
  268.         // start the drawing-thread
  269. /*
  270.         $$$$$ note $$$$$
  271.         Some compilers use another parameter ordering for
  272.         _beginthread. The _beginthread call below works with EMX,
  273.         ICC and BCC. Check your compiler docs for other compilers.
  274. */
  275. // !!!!! code for Borland C++ added since version 1.0
  276. #if defined(__BORLANDC__)
  277.         // for Borland C++
  278.         tidDraw = _beginthread(draw_thread, STACKSIZE, NULL);
  279. #elif defined(__EMX__) || defined(__IBMC__)
  280.         // for EMX and ICC
  281.         tidDraw = _beginthread(draw_thread, NULL, STACKSIZE, NULL);
  282. #endif
  283.  
  284.         // !!!!! next 3 lines added since version 1.0, some code deleted
  285.         // create thread to control priority of drawing thread
  286.         if(low_priority)
  287.             DosCreateThread(&tidPriority, (PFNTHREAD)priority_thread, 0, 2L, 1000);
  288.         return (MRESULT)FALSE;
  289.  
  290.     case WM_DESTROY:
  291.         if(low_priority)
  292.             DosKillThread(tidPriority);
  293.         // tell drawing-thread to stop
  294.         stop_draw_thread = TRUE;
  295.         if(DosWaitThread(&tidDraw, DCWW_NOWAIT) == ERROR_THREAD_NOT_TERMINATED){
  296.             // if priority of drawing-thread was set to idle time
  297.             // priority, set it back to normal value
  298.             DosSetPriority(PRTYS_THREAD, PRTYC_REGULAR, PRTYD_MAXIMUM, tidDraw);
  299.             // wait until drawing-thread has ended
  300.             DosWaitThread(&tidDraw, DCWW_WAIT);
  301.         }
  302.         // release the presentation space
  303.         WinReleasePS(hps);
  304.         break;
  305.     case WM_PAINT:
  306.         return WinDefWindowProc(hwnd, msg, mp1, mp2);
  307.         if(0){
  308.             // just validate the update area. all drawing is done
  309.             // in the drawing-thread.
  310.             RECTL    rclUpdate;
  311.             HPS    hps = WinBeginPaint(hwnd, NULLHANDLE, &rclUpdate);
  312.             WinEndPaint(hps);
  313.         }
  314.         return (MRESULT)0;
  315.     }
  316.     return WinDefWindowProc(hwnd, msg, mp1, mp2);
  317. }
  318.  
  319. /*
  320.     priority_thread
  321.     This thread controls the priority of the drawing thread.
  322.     With these changes, if a saver module runs on low priority (this is
  323.     the default setting), it rises to normal priority twice a second
  324.     for 0.1 seconds. This should solve the problem that, when very
  325.     time-consuming processes were running, the module seemed not to become
  326.     active at all (in fact it became active, but did not get enough CPU
  327.     time to do its saver action).
  328.     There should be no reason to alter the code.
  329. */
  330. void    priority_thread(void *args)
  331. {
  332.     DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 0, 0);
  333.     for(;;){
  334.         DosSetPriority(PRTYS_THREAD, PRTYC_REGULAR, 0, tidDraw);
  335.         DosSleep(100);
  336.         DosSetPriority(PRTYS_THREAD, PRTYC_IDLETIME, 0, tidDraw);
  337.         DosSleep(400);
  338.     }
  339. }
  340.  
  341.  
  342. /*
  343.     load_configuration_data
  344.     Load all module configuration data from the INI-file into the
  345.     configuration_data structure, if not done already loaded.
  346. */
  347. void    load_configuration_data()
  348. {
  349.     if(configuration_data_loaded == FALSE){
  350.         // data not loaded yet
  351.         ULONG    size;
  352.         BOOL    fSuccess;
  353.  
  354.         // get name of the saver module (stored as resource string)
  355.         if(WinLoadString(hab, hmodDLL, IDS_MODULENAME,
  356.           SAVER_NAME_MAXLEN, modulename) == 0){
  357.             // resource string not found. indicate error by
  358.             // setting module name to empty string
  359.             strcpy(modulename, "");
  360.             return;
  361.         }
  362.  
  363.         // load data from INI-file. the key name is the name of the
  364.         // saver module
  365.         size = sizeof(configuration_data);
  366.         fSuccess = PrfQueryProfileData(HINI_USER,
  367.           (PSZ)application_name, (PSZ)modulename,
  368.           (PSZ)&configuration_data, &size);
  369.         if(!fSuccess || size != sizeof(configuration_data) || configuration_data.version != MODULEVERSION){
  370.             // if entry is not found or entry has invalid size or
  371.             // entry has wrong version number, create a new entry
  372.             // with default values and write it to the INI-file
  373.             
  374.          configuration_data.version   = MODULEVERSION;
  375.             configuration_data.enabled   = TRUE;
  376.             configuration_data.count     = CONFIGURATION_DEFAULT_COUNT;
  377.  
  378.             PrfWriteProfileData(HINI_USER, (PSZ)application_name, (PSZ)modulename, (PSZ)&configuration_data, sizeof(configuration_data));
  379.         }
  380.         configuration_data_loaded = TRUE;
  381.     }
  382. }
  383.  
  384. /*
  385.     draw_thread
  386.     This is the drawing-thread.
  387.     You have a valid presentation space handle (hps), a valid window
  388.     handle (hwndSaver) and the configuration_data structure is loaded.
  389.     The screen size is store in "screenSizeX" and "screenSizeY".
  390.     IMPORTANT NOTE 1:
  391.     You must check the "stop_draw_thread" flag regularly. If it is set,
  392.     free all resources you have allocated and call DosExit (or just
  393.     return) to end the drawing-thread.
  394.     IMPORTANT NOTE 2:
  395.     If the "low_priority" flag is NOT set (that means you run with
  396.     regular priority, sharing CPU usage with other programs), you should
  397.     call DosSleep(x) with "x" set at least to 1 as often as possible, to
  398.     allow other programs to do their work. A screen saver should not eat
  399.     up other program's CPU time!
  400.     IMPORTANT NOTE 3:
  401.     For some of the PM calls to work properly, your thread needs an
  402.     own HAB and maybe even a message queue. You have to get and release
  403.     both of them here if you use those PM calls.
  404.  
  405.     The following sample code is from the "Pyramids" module that comes
  406.     with the ScreenSaver distribution.
  407.     It selects a random color and a random point on the screen, then
  408.     draws lines in the selected color from each corner of the screen
  409.     to the selected point (looks somewhat like a pyramid).
  410.     It remembers a number of points (this number can be set in the
  411.     configuration dialog). Having filled the point memory, it redraws
  412.     the "oldest" visible pyramid in black. This has the effect that more
  413.     and more pixels on the screen get black, only a few constantly
  414.     changing colored lines remain.
  415. */
  416. void    draw_thread(void *args)
  417. {
  418.    static POINTL     point;
  419.    static double   a,b,c,i,j,oldj;
  420.    static int      k,range,centerx,centery;
  421.    static RECTL    ScreenSize;
  422.    static long     Color,Color_Count = 0;
  423.    HAB       drawingthread_hab = WinInitialize(0);
  424.    HMQ       drawingthread_hmq = WinCreateMsgQueue(drawingthread_hab, 0);
  425.  
  426.    // Settings hopalong parameter.
  427.  
  428.    centerx = screenSizeX / 2;
  429.    centery = screenSizeY / 2;
  430.    range = (int) sqrt((double)centerx*centerx + (double)centery*centery);
  431.    
  432.    WinQueryWindowRect( hwndSaver, &ScreenSize );
  433.   
  434.    while(!stop_draw_thread)
  435.       {
  436.       srand ( rand () );
  437.       a = (rand() % (range * 100)) * ((rand()%2)?-1.0:1.0) / 100.0;
  438.       srand ( rand () );      
  439.       b = (rand() % (range * 100)) * ((rand()%2)?-1.0:1.0) / 100.0;
  440.       srand ( rand () );
  441.       c = (rand() % (range * 100)) * ((rand()%2)?-1.0:1.0) / 100.0;
  442.       
  443.       WinFillRect( hps, &ScreenSize, CLR_BLACK );
  444.      
  445.       // select random color
  446.       Color = ((unsigned)rand()) % 16;      
  447.       if ((Color==CLR_NEUTRAL) || (Color==CLR_BACKGROUND) || (Color==CLR_BLACK))
  448.          Color++;
  449.       GpiSetColor(hps, Color );
  450.  
  451.       k = configuration_data.count * 100;
  452.       i = j = 0.0;
  453.  
  454.       while ( ( k-- ) && (!stop_draw_thread))         
  455.          {       
  456.          oldj = j;
  457.          j = a - i;
  458.          i = oldj + ( i < 0 ? sqrt(fabs(b*i - c)):-sqrt(fabs(b*i - c)));
  459.          point.x = centerx + (int)(i+j);
  460.          point.y = centery - (int)(i-j);
  461.          // Now draw the point.
  462.          GpiMove ( hps , &point );
  463.          GpiLine ( hps , &point );
  464.           
  465.          // sleep a while if necessary
  466.           if(low_priority == FALSE)
  467.               DosSleep(1);
  468.  
  469.          Color_Count++;
  470.          if ( Color_Count == 1000 )
  471.             {
  472.             // select random color
  473.             Color = ((unsigned)rand()) % 16;      
  474.             if ((Color==CLR_NEUTRAL) || (Color==CLR_BACKGROUND) || (Color==CLR_BLACK))
  475.                 Color++;
  476.             Color_Count = 0;
  477.             GpiSetColor(hps, Color );
  478.             }
  479.          }
  480.        }
  481.    WinDestroyMsgQueue(drawingthread_hmq);
  482.    WinTerminate(drawingthread_hab);
  483. }
  484.  
  485.  
  486.