/****************************************************************\
 *  Message Box procedure
 *--------------------------------------------------------------
 *
 *  Name:   MessageBox(hwndOwner, nIdMsg, fsStyle, fBeep)
 *
 *  Purpose: Displays the message box with the message
 *              given in idMsg retrieved from the message table
 *              and using the style flags in fsStyle
 *
 *  Usage:  Called whenever a MessageBox is to be displayed
 *
 *  Method: - Message string is loaded from the process'
 *              message table
 *          - Alarm beep is sounded if desired
 *          - Message box with the message is displayed
 *          - WinMessageBox return value is returned
 *
 *  Returns: return value from WinMessageBox()
 *
\****************************************************************/
ULONG MessageBox(HWND hwndOwner,  /* handle of the message box's owner */
                 ULONG idMsg,     /* id if the message in the message table */
                 ULONG fsStyle,   /* style of the message box */
                 BOOL fBeep)      /* if TRUE, beep before message box is displayed */
{
   CHAR szText[TITLE_LEN];

   if(!WinLoadMessage(hab,
                     NULLHANDLE,
                     idMsg,
                     TITLE_LEN,
                     (PSZ)szText))
   {
      WinAlarm(HWND_DESKTOP, WA_ERROR);
      return MBID_ERROR;
   }

   if(fBeep)  
   {
      WinAlarm(HWND_DESKTOP, WA_ERROR);
   }

   return WinMessageBox(HWND_DESKTOP,
                        hwndOwner,
                        (PSZ)szText,
                        (PSZ)NULL,
                        MSGBOXID,
                        fsStyle);

}   /* MessageBox() */
Beispiel #2
0
MRESULT APIENTRY wpDlg (
    HWND hwnd,
    MSG_TYPE msg,
    MPARAM mp1,
    MPARAM mp2)
{ /* wpDlg Start */
    MRESULT Result = 0;

    switch (msg)
    { /* switch (msg) START */
    case WM_INITDLG:
        { /* WM_INITDLG Start */
            HWND hwndMenu;
            ULONG id;

            /* load the menu, since currently it seems to be impossible
            ** to get the menu otherwise during startup of the dialog
            */
            id = WinQueryWindowUShort (hwnd, (ULONG) QWS_ID);
            hwndMenu = WinLoadMenu (hwnd, (HMODULE) 0, id);
        } /* WM_INITDLG End */
        break;

    case WM_COMMAND:
        { /* WM_COMMAND Start */
            switch (LOUSHORT(mp1))
            {
            case ID_MENU_1:
                {
                    WinAlarm (HWND_DESKTOP, (ULONG) WA_ERROR);
                    WinAlarm (HWND_DESKTOP, (ULONG) WA_NOTE);
                    WinAlarm (HWND_DESKTOP, (ULONG) WA_ERROR);
                    WinAlarm (HWND_DESKTOP, (ULONG) WA_NOTE);
                }
                break;

            case DID_OK:
                { /* do anything... */
                }
                break;

            default:
                Result = WinDefDlgProc ( hwnd, msg, mp1, mp2 );
                break;
            }
        } /* WM_COMMAND End */
        break;

    case WM_CLOSE:
    default:
        /* any other message will be handled here,
        ** also the button problem...
        */
        Result = WinDefDlgProc ( hwnd, msg, mp1, mp2 );
        break;
    } /* switch (msg) END */

    return (Result);
} /* wpDlg End */
VOID AddDigit(
INT    digit )                         /* new digit to add           */
{

  if (digit == BUTTON_SIGN) {          /* negate number              */
    if (!digits ||                     /* first press?               */
                                       /* sign after exponent?       */
        display.strptr[digits-1] == 'E') {
      display.strptr[digits++] = '-';  /* add the minus sign         */
      display.strptr[digits] = '\0';   /* add new string terminator  */
      display.strlength = digits;      /* keep length in check       */
    }
    else                               /* invalid sign press         */
      WinAlarm(HWND_DESKTOP, WA_ERROR);/* beep at the user           */
  }

  else if (digit == BUTTON_PERIOD) {   /* decimal point              */
    if (hadperiod ||                   /* have one already?          */
        hadexponent ||                 /* or an exponent?            */
        digits >= MAX_DIGITS)          /* or too big                 */
      WinAlarm(HWND_DESKTOP, WA_ERROR);/* beep at the user           */
    else {                             /* add a decimal point        */
      if (!digits)                     /* have digits already?       */
        display.strptr[digits++] = '0';/* no, add leading zero       */
      display.strptr[digits++] = '.';  /* add the decimal point      */
      display.strptr[digits] = '\0';   /* add new string terminator  */
      display.strlength = digits;      /* keep length in check       */
      hadperiod = YES;                 /* remember this              */
    }
  }

  else if (digit == BUTTON_EXPONENT) { /* use scientific             */
    if (hadexponent ||                 /* have one already?          */
        digits >= MAX_DIGITS)          /* or too big                 */
      WinAlarm(HWND_DESKTOP, WA_ERROR);/* beep at the user           */
    else {
      if (!digits)                     /* have digits already?       */
        display.strptr[digits++] = '0';/* no, add leading zero       */
      display.strptr[digits++] = 'E';  /* add the exponent           */
      display.strptr[digits] = '\0';   /* add new string terminator  */
      display.strlength = digits;      /* keep length in check       */
      hadexponent = YES;               /* remember this              */
    }
  }

  else {                               /* real digit                 */
    digit -= BUTTON_0;                 /* make base zero             */
    digit += (INT)'0';                 /* convert to character value */
    if (digits >= MAX_DIGITS)          /* or too big                 */
      WinAlarm(HWND_DESKTOP, WA_ERROR);/* beep at the user           */

    else {                             /* if small enough            */
                                       /* add new digit to display   */
      display.strptr[digits++] = (UCHAR)digit;
      display.strptr[digits] = '\0';   /* add new string terminator  */
      display.strlength = digits;      /* keep length in check       */
    }
  }
}
Beispiel #4
0
static MRESULT APIENTRY OK ( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2 ) {

 /***************************************************************************
  * Find the instance data.                                                 *
  ***************************************************************************/

  PPROFILE_PARMS Parms = PPROFILE_PARMS ( WinQueryWindowPtr ( hwnd, QWL_USER ) ) ;

 /***************************************************************************
  * Verify the entered path.                                                *
  ***************************************************************************/

  BYTE Name [256] ;
  WinQueryDlgItemText ( hwnd, Parms->id+ENTRY, sizeof(Name), Name ) ;

  BYTE FullPath [256] ;
  if ( DosQueryPathInfo ( Name, FIL_QUERYFULLNAME, FullPath, sizeof(FullPath) ) ) {
    PSZ Message = PSZ ( "ERROR: Not a valid path." ) ;
    WinSetDlgItemText ( hwnd, Parms->id+ERR, Message ) ;
    WinAlarm ( HWND_DESKTOP, WA_ERROR ) ;
    WinSetFocus ( HWND_DESKTOP, WinWindowFromID ( hwnd, Parms->id+ENTRY ) ) ;
    return ( 0 ) ;
  }

  FILESTATUS3 Status ;
  if ( DosQueryPathInfo ( FullPath, FIL_STANDARD, &Status, sizeof(Status) ) ) {
    PSZ Message = PSZ ( "ERROR: Path does not exist." ) ;
    WinSetDlgItemText ( hwnd, Parms->id+ERR, Message ) ;
    WinAlarm ( HWND_DESKTOP, WA_ERROR ) ;
    WinSetFocus ( HWND_DESKTOP, WinWindowFromID ( hwnd, Parms->id+ENTRY ) ) ;
    return ( 0 ) ;
  }

  if ( ! ( Status.attrFile & FILE_DIRECTORY ) ) {
    PSZ Message = PSZ ( "ERROR: Specified path is not a directory." ) ;
    WinSetDlgItemText ( hwnd, Parms->id+ERR, Message ) ;
    WinAlarm ( HWND_DESKTOP, WA_ERROR ) ;
    WinSetFocus ( HWND_DESKTOP, WinWindowFromID ( hwnd, Parms->id+ENTRY ) ) ;
    return ( 0 ) ;
  }

 /***************************************************************************
  * Return the full path to the caller.                                     *
  ***************************************************************************/

  strncpy ( PCHAR(Parms->Path), PCHAR(FullPath), Parms->PathSize ) ;

 /***************************************************************************
  * Dismiss the dialog with a TRUE status.                                  *
  ***************************************************************************/

  WinDismissDlg ( hwnd, TRUE ) ;

  return ( 0 ) ;
}
VOID lboxMouBtn1dwn(PELBOX pelb, PMSEMSG pmmsg) {
   INT i, idx;
   // trova colonna
   for (i = 0; i < pelb->ccol; ++i) {
      if (pmmsg->x >= pelb->pcol[i].rcl.xLeft &&
          pmmsg->x < pelb->pcol[i].rcl.xRight) {
         // trova indice item
         idx = (SHORT)pelb->lbxwprc(pelb->hlbx, LM_QUERYTOPINDEX,
                                    MPVOID, MPVOID) +
               (pelb->rcltopitem.yTop - pmmsg->y) / pelb->cyitem;
         // notifica owner controllo (se non si clicca su un'area vuota)
         if (idx < pelb->citems) {
            if ((pelb->fl & ELBCS_ITEMCHECKBOXED) &&
                ((pmmsg->x - pelb->pcol[i].rcl.xLeft) < pelb->cyitem))
               WinSendMsg(WinQueryWindow(pelb->hwnd, QW_OWNER), WM_CONTROL,
                          MPFROM2SHORT((USHORT)pelb->id, ELBXN_CHECKED), 
                          MPFROM2SHORT(idx, i));
            else
               WinSendMsg(WinQueryWindow(pelb->hwnd, QW_OWNER), WM_CONTROL,
                          MPFROM2SHORT((USHORT)pelb->id, ELBXN_SELECT), 
                          MPFROM2SHORT(idx, i));
         } else {
            WinAlarm(HWND_DESKTOP, WA_ERROR);
         } // end if
         break;
      } // end if
   } /* endfor */
}
MRESULT EXPENTRY ClientWndProc (HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
     {
     static BOOL fFlipFlop ;
     HPS         hps ;
     RECTL       rcl ;

     switch (msg)
          {
          case WM_TIMER:
               WinAlarm (HWND_DESKTOP, WA_NOTE) ;
               fFlipFlop = !fFlipFlop ;
               WinInvalidateRect (hwnd, NULL, FALSE) ;
               return 0 ;

          case WM_PAINT:
               hps = WinBeginPaint (hwnd, NULLHANDLE, NULL) ;

               WinQueryWindowRect (hwnd, &rcl) ;
               WinFillRect (hps, &rcl, fFlipFlop ? CLR_BLUE : CLR_RED) ;

               WinEndPaint (hps) ;
               return 0 ;
          }
     return WinDefWindowProc (hwnd, msg, mp1, mp2) ;
     }
Beispiel #7
0
/* *************************************************************** */
void _catcher(bundle s)
{
    char    msg[512];
    char   *b[4];
    HMODULE hmod;
    PFNWP   DlgProc;
    int  c  = 0,
         bx = 0;

    if (msgHead != NULL) {
      for (msg[0] = '\0'; *msgHead != NULL; ++msgHead) strcat(msg,*msgHead);
      b[bx++] = msg;
      c = strlen(msg) + 1;
    }
    for (msg[c] = '\0'; *s != NULL; ++s) strcat(&msg[c],*s);
    b[bx++] = &msg[c];
    b[bx++] = "Application will terminate now";
    b[bx]   = NULL;

    if (DosLoadModule(NULL, 0, "GPRTS", &hmod) ||
        DosQueryProcAddr(hmod, 0, "DlgProc", (PFN *)&DlgProc))
      WinMessageBox(HWND_DESKTOP, HWND_DESKTOP,
                    "Unable to load error message","GPM Fatal Error",
                    0, MB_ICONHAND | MB_OK);
    else {
      WinAlarm(HWND_DESKTOP, WA_ERROR);
      WinDlgBox(HWND_DESKTOP, HWND_DESKTOP, DlgProc, hmod, GPRTS_DLG, b);
      DosFreeModule(hmod);
    }
    DosExit(EXIT_PROCESS, 0);
}
Beispiel #8
0
int
main(int argc, char **argv)
{
	ULONG FrameFlags = FCF_TITLEBAR |
			   FCF_SYSMENU |
			   FCF_SIZEBORDER |
			   FCF_HIDEBUTTON |
			   FCF_SHELLPOSITION |
			   FCF_TASKLIST;
	HAB hab;
	HMQ hmq;
	HWND Client;
	QMSG qmsg;
	arglist args;
	int python_tid;

	/* init PM and create message queue */
	hab = WinInitialize(0);
	hmq = WinCreateMsgQueue(hab, 0);

	/* create a (hidden) Window to house the window procedure */
	args.Frame = WinCreateStdWindow(HWND_DESKTOP,
					0,
					&FrameFlags,
					NULL,
					"PythonPM",
					0L,
					0,
					0,
					&Client);

	/* run Python interpreter in a thread */
	args.argc = argc;
	args.argv = argv;
	args.running = 0;
	if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args)))
	{
		/* couldn't start thread */
		WinAlarm(HWND_DESKTOP, WA_ERROR);
		PythonRC = 1;
	}
	else
	{
		/* process PM messages, until Python exits */
		while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0))
			WinDispatchMsg(hab, &qmsg);
		if (args.running > 0)
			DosKillThread(python_tid);
	}
		
	/* destroy window, shutdown message queue and PM */
	WinDestroyWindow(args.Frame);
	WinDestroyMsgQueue(hmq);
	WinTerminate(hab);

	return PythonRC;
}
BOOL lboxEndDrag(PELBOX pelb, PMSEMSG pmmsg) {
   LONG rc;
   if (!(pelb->fl & ELBCS_ITEMDRAGGABLE) || !pelb->is.dragging)
      return FALSE;
   WinSetCapture(HWND_DESKTOP, NULLHANDLE);
   WinStopTimer(pelb->hab, pelb->hlbx, DRAG_TIMERID);
   pelb->is.dragging = 0;
   if (pelb->is.where == ELBOX_DRAGIN) {
      PVOID pitemdata;
      PSZ psz;
      ULONG cb;
      SHORT dropitem = (SHORT)pelb->lbxwprc(pelb->hlbx, LM_QUERYTOPINDEX,
                                            MPVOID, MPVOID) +
                       (pelb->rcltopitem.yTop - pmmsg->y + pelb->cyitem / 2) /
                       pelb->cyitem;
      if (dropitem != pelb->dragitem && dropitem != (pelb->dragitem + 1)) {
         rc = (LONG)WinSendMsg(WinQueryWindow(pelb->hwnd, QW_OWNER),
                               WM_CONTROL,
                               MPFROM2SHORT((USHORT)pelb->id, ELBXN_DROPITEM), 
                               MPFROM2SHORT(pelb->dragitem, dropitem));
         if (rc < 0) goto cancel;
         if (rc > 0) return TRUE;
         // ricava dati item draggato
         cb = (ULONG)pelb->lbxwprc(pelb->hlbx, LM_QUERYITEMTEXTLENGTH,
                                   (MPARAM)pelb->dragitem, MPVOID) + 1;
         if (NULL != (psz = (PSZ)malloc(cb))) {
            pelb->lbxwprc(pelb->hlbx, LM_QUERYITEMTEXT,
                          MPFROM2SHORT(pelb->dragitem, cb), (MPARAM)psz);
            pitemdata = pelb->lbxwprc(pelb->hlbx, LM_QUERYITEMHANDLE,
                                      (MPARAM)pelb->dragitem, MPVOID);
            WinEnableWindowUpdate(pelb->hlbx, FALSE);
            // lo copia nella nuova posizione
            if (dropitem >= pelb->citems) dropitem = LIT_END;
            dropitem = (SHORT)pelb->lbxwprc(pelb->hlbx, LM_INSERTITEM,
                                            (MPARAM)dropitem, (MPARAM)psz);
            pelb->lbxwprc(pelb->hlbx, LM_SETITEMHANDLE, (MPARAM)dropitem,
                          (MPARAM)pitemdata);
            free(psz);
            // se inserzione nuovo item precede vecchio aumenta indice
            if (dropitem < pelb->dragitem) ++pelb->dragitem;
            else --dropitem;
            // cancella item da vecchia posizione
            pelb->lbxwprc(pelb->hlbx, LM_DELETEITEM,
                          (MPARAM)pelb->dragitem, MPVOID);
            // seleziona item riposizionato
            pelb->lbxwprc(pelb->hlbx, LM_SELECTITEM,
                          (MPARAM)dropitem, (MPARAM)TRUE);
            WinEnableWindowUpdate(pelb->hlbx, TRUE);
            return TRUE;
         } /* endif */
      } /* endif */
   } /* endif */
cancel:
   WinAlarm(HWND_DESKTOP, WA_ERROR);
   return TRUE;
} /* endif */
/*******************************************************************************
    Timeout waiting for a thread to terminate. Alarms if unsucessful.
*******************************************************************************/
BOOL TimeoutDlgThread(PTID pTid, ULONG ulNtimeslices)
    {
        APIRET  rc;
        do  {
                rc = DosWaitThread(pTid, DCWW_NOWAIT);
                if(rc == ERROR_THREAD_NOT_TERMINATED)
                    {
                        DosSleep(1);
                        ulNtimeslices--;
                    }
                else if(rc == NO_ERROR) return(TRUE);
                else return(FALSE);
            }   while(ulNtimeslices);
        if(!ulNtimeslices) WinAlarm(HWND_DESKTOP, WA_ERROR);
        return(FALSE);
    }
Beispiel #11
0
static MRESULT EXPENTRY _DirDlgSubclassProc( HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
{
         PDIRDLG        pdd = WinQueryWindowPtr( hwnd, QWL_USER);

switch (msg)
   {
   case WM_COMMAND:
      switch (LONGFROMMP( mp1))
         {
         case DID_CANCEL:
            WinAlarm( HWND_DESKTOP, WA_ERROR);
            break;
         }
      break;
   }

return WtkDefDirDlgProc( hwnd, msg, mp1, mp2);
}
BOOL lboxBeginDrag(PELBOX pelb, PMSEMSG pmmsg) {
   if (pelb->fl & ELBCS_ITEMDRAGGABLE) {
      // in caso di errore cancella operazione
      if (pelb->is.dragging) {
         pelb->is.dragging = 0;
         WinSetCapture(HWND_DESKTOP, NULLHANDLE);
         WinStopTimer(pelb->hab, pelb->hlbx, DRAG_TIMERID);
         return FALSE;
      } // end if
      // trova indice item trascinato
      pelb->dragitem = (SHORT)pelb->lbxwprc(pelb->hlbx, LM_QUERYTOPINDEX,
                                            MPVOID, MPVOID) +
                       (pelb->rcltopitem.yTop - pmmsg->y) / pelb->cyitem;
      // se il mouse Š sopra (all'esterno) al primo item o se Š sotto
      // l'ultimo suona allarme e restituisce true
      if (pmmsg->y >= pelb->rcltopitem.yTop || pelb->dragitem >= pelb->citems)
         goto cancel;
      // se tutto Š a posto sposta il cursore sull'item draggato:
      pelb->lbxwprc(pelb->hlbx, WM_BUTTON1DOWN,
                    MPFROM2SHORT(pmmsg->x, pmmsg->y), MPVOID);
      pelb->lbxwprc(pelb->hlbx, WM_BUTTON1UP,
                    MPFROM2SHORT(pmmsg->x, pmmsg->y), MPVOID);
      // notifica owner window evento inizio drag. Se l'owner restituisce
      // TRUE l'operazione di drag viene cancellata
      if (WinSendMsg(WinQueryWindow(pelb->hwnd, QW_OWNER), WM_CONTROL,
                     MPFROM2SHORT((USHORT)pelb->id, ELBXN_DRAGITEM),
                     MPFROM2SHORT(pelb->dragitem, pelb->citems)))
         goto cancel;
      pelb->is.dragging = 1;
      pelb->is.where = ELBOX_DRAGIN;
      WsetSysMouPtr(SPTR_MOVE);
      WinSetCapture(HWND_DESKTOP, pelb->hlbx);
      WinStartTimer(pelb->hab, pelb->hlbx, DRAG_TIMERID, 70);
      return TRUE;
   } // end if
   return FALSE;

cancel:
   pelb->is.dragging = 0;
   WinAlarm(HWND_DESKTOP, WA_ERROR);
   return TRUE;
}
Beispiel #13
0
static void FileWarning(PSZ pFileName, ULONG MsgID)
{
  PSZ pStrn;

  if (NULL == pFileName)
   return;

  Len = WinLoadString(Hab, hRessourceModule, IDS_WARNING,
                      TITLESTRN_MAXLEN, Title);
  Len = WinLoadString(Hab, hRessourceModule, MsgID,
                      MSGSTRN_MAXLEN, Msg);
  pStrn = (PSZ) malloc((Len+strlen(pFileName)+1)*sizeof(CHAR));
  if (NULL != pStrn)
  {
   sprintf(pStrn, Msg, pFileName);
   WinAlarm(HWND_DESKTOP, WA_WARNING);
   WinMessageBox(HWND_DESKTOP, hwndMainDialog, pStrn, Title, 0, MB_WARNING | MB_OK);
   free(pStrn);
  }
}
BOOL isChanged(HWND hwnd, PATTMAN pam) {
   if (pam->pro.gen.ronly) return FALSE; // se read only restituisce FALSE
   if (DlgMleQueryChanged(hwnd, MLE_KEY) ||
       DlgMleQueryChanged(hwnd, MLE_COMNT) ||
       pam->fsp.subjChanged > 0 ||
       isOrdAttrChanged(hwnd, &pam->fsp)) {  
      WinAlarm(HWND_DESKTOP, WA_NOTE); 
      switch (WinDlgBox(HWND_DESKTOP, hwnd, NULL,
              NULLHANDLE, SAVE_DLG, NULL)) {
         case BTN_2_SAVE :
            WriteNewAttr(hwnd, pam);
            return FALSE;
         case BTN_2_DISCARD :
            pam->fsp.subjChanged = -1;
            return FALSE;
         default :
            return TRUE;
      } // end switch
   } // end if
   return FALSE;
}
Beispiel #15
0
MRESULT EXPENTRY PrefDlgProc (HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
{
 static BOOL DisMiss = FALSE;
 BOOL IsError;

 switch (msg)
      {

       case WM_INITDLG:
        {
         PINICHECK pIsNewStructure = (PINICHECK) mp2;
         memcpy(&TempData, &ProfileData, sizeof(ProfileData));
         UpdateCaption(hwnd, IDS_PREF_TITLE);
         ShortenSysMenu(hwnd);
         CenterWindow(hwnd);
         if (!LoadNoteBookPages(hwnd))
         {
          WinAlarm(HWND_DESKTOP, WA_ERROR);
          WinMessageBox(HWND_DESKTOP, hwnd, "Internal system error!", NULL, 0, MB_ERROR | MB_OK);
          WinPostMsg(hwnd, WM_CLOSE, (MPARAM) 0, (MPARAM) 0);
         }
         else
         {
           DisMiss = FALSE;
           WinPostMsg(hwnd, WM_COMMAND, (MPARAM) WM_CHECK_FILES, (MPARAM) 0);
         }
         LastIconState = TempData.Flags.SmallIcons;
         if (pIsNewStructure->State)
         {
            Len = WinLoadString(Hab, hRessourceModule, IDS_PLEASE_NOTE,
                                TITLESTRN_MAXLEN, Title);
            Len = WinLoadString(Hab, hRessourceModule, IDS_INIFILE_UPDATE_REQUIRED,
                                MSGSTRN_MAXLEN, Msg);
            WinMessageBox(HWND_DESKTOP, hwnd, Msg, Title, 0, MB_ICONEXCLAMATION | MB_OK);
         }
        }
        break;

       case WM_SYSCOMMAND:
         switch(SHORT1FROMMP(mp1))
         {
           case SC_CLOSE:
              WinSendMsg(hwnd, WM_COMMAND, (MPARAM) DID_CANCEL, (MPARAM) 0);
            break;

           default:
            return WinDefDlgProc (hwnd, msg, mp1, mp2);
         }
        break;

       case WM_COMMAND:
         switch(SHORT1FROMMP(mp1))
         {
           case DID_OK:
             DisMiss = TRUE;
             PrefSaveParams(hwnd, &TempData);
             WinSendMsg(hwnd, WM_COMMAND, (MPARAM) WM_CHECK_FILES, (MPARAM) 0);
            break;

           case DID_CANCEL:
             WinDismissDlg(hwnd, (ProfileData.Flags.FirstSetupDone) ? TRUE : FALSE);
            break;

           case WM_CHECK_FILES:
             IsError = FALSE;
             if (!FileExist(TempData.PublicKeyFile) ||
                 (0L == FileSize(NULL, TempData.PublicKeyFile))
                )
             {
               WinSendMsg(WinWindowFromID(hwnd, DID_PREF_NOTEBOOK),
                          BKM_TURNTOPAGE,
                          (MPARAM) ulFilesPageId,
                          NULL);
               FileWarning(TempData.PublicKeyFile, IDS_PUB_KEYFILE_NOT_EXIST);
               IsError = TRUE;
             }
             if (!FileExist(TempData.PrivateKeyFile) ||
                  (0L == FileSize(NULL, TempData.PrivateKeyFile))
                 )
             {
               WinSendMsg(WinWindowFromID(hwnd, DID_PREF_NOTEBOOK),
                          BKM_TURNTOPAGE,
                          (MPARAM) ulFilesPageId,
                          NULL);
               FileWarning(TempData.PrivateKeyFile, IDS_PRIV_KEYFILE_NOT_EXIST);
               IsError = TRUE;
             }

             if (!IsError && DisMiss)
             {
               /* now write profile after successful setup */
               memcpy(&ProfileData, &TempData, sizeof(ProfileData));
               ProfileData.Flags.SuppressHint = SuppressPGPKeysHint;
               ProfileData.Flags.FirstSetupDone = TRUE;
               WriteParams(Hab);
               UpdatePgpCfgFile();
               WinDismissDlg(hwnd, TRUE);
               if (LastIconState != TempData.Flags.SmallIcons)
               {
                  LONG Len;
                  Len = WinLoadString(Hab, hRessourceModule, IDS_PLEASE_NOTE,
                                      TITLESTRN_MAXLEN, Title);
                  Len = WinLoadString(Hab, hRessourceModule, IDS_PLEASE_RESTART,
                                      MSGSTRN_MAXLEN, Msg);
                  WinMessageBox(HWND_DESKTOP, hwnd, Msg, Title, 0, MB_ICONASTERISK | MB_OK);
               }
             }

             if (!ProfileData.Flags.FirstSetupDone)
               WinSendMsg(WinWindowFromID(hwnd, DID_PREF_NOTEBOOK),
                          BKM_TURNTOPAGE,
                          (MPARAM) ulFilesPageId,
                          NULL);
            break; /* WM_CHECK_FILES */
         }
        break;

       case WM_HELP:
         DisplayHelp(IDL_SETTINGS_HELP);
        break;

       case WM_CLOSE:
        if (NULL != pPointerDialog1)
        {
         DosFreeResource(&pPointerDialog1);
         pPointerDialog1 = NULL;
        }
        if (NULL != pPointerDialog2)
        {
         DosFreeResource(&pPointerDialog2);
         pPointerDialog2 = NULL;
        }
        /* no break: fall through to default branch!!! */

       default:
        return WinDefDlgProc (hwnd, msg, mp1, mp2);
      }

 return (MRESULT)FALSE;
}
MRESULT EXPENTRY OpenDlgProc (HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
     {
     static CHAR szCurrentPath [CCHMAXPATH], szBuffer [CCHMAXPATH] ;
     INT         iSelect ;

     switch (msg)
          {
          case WM_INITDLG:
               FillDirListBox (hwnd, szCurrentPath) ;
               FillFileListBox (hwnd) ;

               WinSendDlgItemMsg (hwnd, IDD_FILEEDIT, EM_SETTEXTLIMIT,
                                        MPFROM2SHORT (CCHMAXPATH, 0), NULL) ;
               return 0 ;

          case WM_CONTROL:
               if (SHORT1FROMMP (mp1) == IDD_DIRLIST ||
                   SHORT1FROMMP (mp1) == IDD_FILELIST)
                    {
                    iSelect = (USHORT) WinSendDlgItemMsg (hwnd,
                                                  SHORT1FROMMP (mp1),
                                                  LM_QUERYSELECTION, 0L, 0L) ;

                    WinSendDlgItemMsg (hwnd, SHORT1FROMMP (mp1),
                                       LM_QUERYITEMTEXT,
                                       MPFROM2SHORT (iSelect, sizeof szBuffer),
                                       MPFROMP (szBuffer)) ;
                    }

               switch (SHORT1FROMMP (mp1))             // Control ID
                    {
                    case IDD_DIRLIST:
                         switch (SHORT2FROMMP (mp1))   // notification code
                              {
                              case LN_ENTER:
                                   if (szBuffer [0] == ' ')
                                        DosSetDefaultDisk (szBuffer [1] - '@');
                                   else
                                        DosSetCurrentDir (szBuffer) ;

                                   FillDirListBox (hwnd, szCurrentPath) ;
                                   FillFileListBox (hwnd) ;

                                   WinSetDlgItemText (hwnd, IDD_FILEEDIT, "") ;
                                   return 0 ;
                              }
                         break ;

                    case IDD_FILELIST:
                         switch (SHORT2FROMMP (mp1))   // notification code
                              {
                              case LN_SELECT:
                                   WinSetDlgItemText (hwnd, IDD_FILEEDIT,
                                                      szBuffer) ;
                                   return 0 ;

                              case LN_ENTER:
                                   ParseFileName (szFileName, szBuffer) ;
                                   WinDismissDlg (hwnd, TRUE) ;
                                   return 0 ;
                              }
                         break ;
                    }
               break ;

          case WM_COMMAND:
               switch (COMMANDMSG(&msg)->cmd)
                    {
                    case DID_OK:
                         WinQueryDlgItemText (hwnd, IDD_FILEEDIT,
                                              sizeof szBuffer, szBuffer) ;

                         switch (ParseFileName (szCurrentPath, szBuffer))
                              {
                              case 0:
                                   WinAlarm (HWND_DESKTOP, WA_ERROR) ;
                                   FillDirListBox (hwnd, szCurrentPath) ;
                                   FillFileListBox (hwnd) ;
                                   return 0 ;

                              case 1:
                                   FillDirListBox (hwnd, szCurrentPath) ;
                                   FillFileListBox (hwnd) ;
                                   WinSetDlgItemText (hwnd, IDD_FILEEDIT, "") ;
                                   return 0 ;

                              case 2:
                                   strcpy (szFileName, szCurrentPath) ;
                                   WinDismissDlg (hwnd, TRUE) ;
                                   return 0 ;
                              }
                         break ;

                    case DID_CANCEL:
                         WinDismissDlg (hwnd, FALSE) ;
                         return 0 ;
                    }
               break ;
          }
     return WinDefDlgProc (hwnd, msg, mp1, mp2) ;
     }
MRESULT EXPENTRY Calculator(
  HWND    hwnd,                        /* window handle              */
  ULONG   msg,                         /* dispatched message id      */
  MPARAM  mp1,                         /* first message parameter    */
  MPARAM  mp2 )                        /* second message parameter   */
{
  ULONG   action;                      /* Action to process          */

   switch (msg) {                      /* switch based on the message*/
                                       /* received                   */

      /* The initialization message has been received.  We do some   */
      /* additional fixup of the dialog to make it look a little     */
      /* nicer.                                                      */

      case WM_INITDLG:

                                       /* initialize accumulator     */
         MAKERXSTRING(accumulator, accbuff, 1);
         strcpy(accbuff, "0");         /* fill in a zero             */
         digits = 0;                   /* no digits in number        */
         hadperiod = NO;               /* no period yet              */
         hadexponent = NO;             /* no exponential yet         */
         oldaction = 0;                /* no pending operations      */
         strcpy(precision, "9");       /* set default precision      */
         form = SCIENTIFIC;            /* set default form           */
         SetDisplay(&accumulator);     /* set initial display value  */
                                       /* update the calculator      */
                                       /* display                    */
         WinSetWindowText(WinWindowFromID(hwnd, DISPLAY),
             display.strptr);
                                       /* register our external      */
                                       /* functions                  */
         RexxRegisterFunctionExe("CalcPrecision", (PFN)CalcPrecision);
         RexxRegisterFunctionExe("CalcForm", (PFN)CalcForm);

         return FALSE;                 /* initialization complete    */

      /* We are going away, time to post a quit message to the       */
      /* message loop.                                               */

      case WM_CLOSE:

                                       /* Deregister our defined     */
                                       /* functions                  */
         RexxDeregisterFunction("CalcPrecision");
         RexxDeregisterFunction("CalcForm");
                                       /* Standard Close processing  */
         WinPostMsg(hwnd, WM_QUIT, 0L, 0L);
         return FALSE;                 /* Exit now                   */

      /* We've received a WM_CONTROL message.  This was              */
      /* generated by the "Form" check blox.                         */

      case WM_CONTROL:                 /* change current form        */

         action = SHORT1FROMMP(mp1);   /* Extract message sub-type   */

         switch (action) {             /* process the control        */

           case BUTTON_FORM:           /* form switch button         */

             if (form == SCIENTIFIC) { /* current scientific?        */
               form = ENGINEERING;     /* make it engineering        */
                                       /* update label               */
               WinSetWindowText(WinWindowFromID(hwnd, BUTTON_FORM),
                   "Engineering");
             }
             else {
               form = SCIENTIFIC;      /* otherwise scientfic        */
               WinSetWindowText(WinWindowFromID(hwnd, BUTTON_FORM),
                  "Scientific");
             }
             return FALSE;             /* all done                   */
           default:                    /* Unknown, can't handle this */
             return FALSE;
         }

      /* We've received a WM_COMMAND message.  WM_COMMAND messages   */
      /* are generated by "pressing" buttons on the calculator.  The */
      /* additional parameters in the received message identify the  */
      /* button that was pressed                                     */

      case WM_COMMAND:

         action = SHORT1FROMMP(mp1);   /* Extract message sub-type   */

         switch (action) {

            /* The following buttons will be processed by the actual */
            /* calculator routine                                    */

            case BUTTON_CLEAR:         /* Clear key                  */

                                       /* initialize accumulator     */
              MAKERXSTRING(accumulator, accbuff, 1);
              strcpy(accbuff, "0");    /* fill in a zero             */
                                       /* initialize the display     */
              MAKERXSTRING(display, dispbuff, 1);
              strcpy(dispbuff, "0");   /* fill in a zero display     */
              digits = 0;              /* no digits yet              */
              hadperiod = NO;          /* turn off number processing */
              hadexponent = NO;        /* flags.                     */
              oldaction = 0;           /* and any pending operations */
                                       /* update the calculator      */
                                       /* display                    */
              WinSetWindowText(WinWindowFromID(hwnd, DISPLAY),
                  display.strptr);
              return FALSE;            /* All done                   */

            case BUTTON_DIGITS:        /* set new digits             */
                                       /* not a whole number?        */
              if (!CheckWhole(&display))
                                       /* give an error beep         */
                WinAlarm(HWND_DESKTOP, WA_ERROR);
              else {                   /* process the number         */
                                       /* copy the number            */
                strcpy(precision, display.strptr);
                                       /* redisplay the accumlator   */
                SetDisplay(&accumulator);
                                       /* display                    */
                WinSetWindowText(WinWindowFromID(hwnd, DISPLAY),
                    display.strptr);
              }
              return FALSE;            /* All done                   */

            case BUTTON_0:             /* Numeric keys               */
            case BUTTON_1:
            case BUTTON_2:
            case BUTTON_3:
            case BUTTON_4:
            case BUTTON_5:
            case BUTTON_6:
            case BUTTON_7:
            case BUTTON_8:
            case BUTTON_9:
            case BUTTON_PERIOD:        /* decimal point              */
            case BUTTON_EXPONENT:      /* exponent value             */
            case BUTTON_SIGN:          /* sign change                */

                                       /* Add a digit to display     */
              AddDigit(action);
                                       /* update the accumulator     */
                                       /* display                    */
              WinSetWindowText(WinWindowFromID(hwnd, DISPLAY),
                    display.strptr);
              return FALSE;            /* All done                   */

            /* The arithmetic operation keys all have a deferred     */
            /* execution.  When one of these is pressed, the previous*/
            /* arithmetic operation is processed using the           */
            /* accumulator and the current display.  The new operator*/
            /* is saved for later execution.  If no operator exists, */
            /* then the current display is moved to the accumulator  */
            /* and no arithmetic is done                             */

            case BUTTON_MULTIPLY:      /* Multiply key               */
            case BUTTON_DIVIDE:        /* Division key               */
            case BUTTON_PLUS:          /* Addition key               */
            case BUTTON_MINUS:         /* Subtraction key            */
            case BUTTON_IDIV:          /* integer division           */
            case BUTTON_REMAINDER:     /* remainder division         */
            case BUTTON_POWER:         /* raise a number to power    */
            case BUTTON_ENTER:         /* "Total" key                */
            case BUTTON_PROGRAM1:      /* programmed Rexx function   */
            case BUTTON_PROGRAM2:      /* programmed Rexx function   */

                                       /* Process pending operations */
              ProcessArithmetic(action);
              SetDisplay(&accumulator);/* reset display buffer       */
                                       /* update the calculator      */
                                       /* display                    */
              WinSetWindowText(WinWindowFromID(hwnd, DISPLAY),
                    accumulator.strptr);
              return FALSE;            /* All done                   */

            default:                   /* Unknown, can't handle this */
               return FALSE;
         }

      case WM_ERASEBACKGROUND:         /* disable background erase   */
        return MRFROMLONG(TRUE);       /* don't allow this           */

      /* Message not handled by us.  PM gives us first chance at all */
      /* messages.  Those we don't want to process we pass on to the */
      /* default dialog procedure.                                   */

      default:
         return WinDefWindowProc(hwnd, msg, mp1, mp2);

   }

   return FALSE;                       /* Should never reach here    */
 }
MRESULT EXPENTRY AirTrafficControlDlg (HWND hwnd, ULONG msg,
    MPARAM mp1, MPARAM mp2)
{
    PINST   pinst;

    pinst = (PINST) WinQueryWindowPtr(hwnd,QWL_USER);

    switch (msg)
    {
        case WM_INITDLG:
        {
            /*
             *  INITIALIZE APPLICATION
             */

            CNRINFO     ccinfo;         // Container info structure

            // Initialize instance data
            pinst = (PINST) calloc (1, sizeof *pinst);
            WinSetWindowPtr(hwnd,QWL_USER,pinst);
            pinst->hwndCnr = WinWindowFromID (hwnd, IDCNR_SAMPLE);
            pinst->hab     = WinQueryAnchorBlock (hwnd);
            pinst->hwndAircraftMenu =               // Load aircraft menu
                WinLoadMenu( HWND_OBJECT, 0, IDMENU_AIRCRAFT);
            pinst->hwndContainerMenu =              // Load container menu
                WinLoadMenu( HWND_OBJECT, 0, IDMENU_CONTAINER);
            pinst->CurrentView = IDMVIEW_RADAR;

            // Set container info to request owner background painting
            memset (&ccinfo, 0, sizeof ccinfo);
            ccinfo.cb = sizeof ccinfo;
            ccinfo.flWindowAttr = CA_OWNERPAINTBACKGROUND;
            WinSendMsg (pinst->hwndCnr, CM_SETCNRINFO, &ccinfo,
                MPFROMLONG(CMA_FLWINDOWATTR));

            // Subclass container window to provide background painting
            pfnwpCnr = WinSubclassWindow (pinst->hwndCnr,
                CnrSubclassWndProc);
            assert (pfnwpCnr);

            // Insert the columns into the container
            InsertContainerColumns (pinst);

            // Insert the initial records into the container
            InsertContainerRecords (pinst);

            // Start a timer to control aircraft
            WinStartTimer (pinst->hab, hwnd,
                IDTIMER_ADJUSTAIRCRAFT, AIRCRAFT_ADJUST_FREQUENCY);

            // The container is ready for viewing
            WinShowWindow (pinst->hwndCnr, TRUE);

            SetUpControllerHandoffValueSet (hwnd);

            return 0;
        }

        case WM_TIMER:

            /*
             *  DO TIME-RELATED AIRCRAFT HANDLING
             */

            if (SHORT1FROMMP (mp1) == IDTIMER_ADJUSTAIRCRAFT)
            {
                PAPPCNRREC      pacrTraverse;

                // Loop through all container records
                for (pacrTraverse = FIRST_CNR_ITEM (pinst->hwndCnr);
                    pacrTraverse;
                    pacrTraverse = NEXT_CNR_ITEM(pinst->hwndCnr,pacrTraverse))
                {
                    BOOL        fInvalid = FALSE;

                    if (pinst->CurrentView == IDMVIEW_RADAR)
                    {
                        /* Erase the record from previous location. */
                        WinSendMsg (pinst->hwndCnr, CM_ERASERECORD,
                            MPFROMP(pacrTraverse), NULL);
                    }

                    // Maneuver the aircraft
                    if (ManeuverAircraft (pacrTraverse))
                    {
                        // Update aircraft text if necessary
                        SetRecordText (pacrTraverse);
                        fInvalid = TRUE;
                    }

                    if (fInvalid || pinst->CurrentView == IDMVIEW_RADAR)
                        /* Paint the record in its new position */
                        WinSendMsg (pinst->hwndCnr, CM_INVALIDATERECORD,
                            MPFROMP(&pacrTraverse),
                            MPFROMSHORT(1));
                }
            }
            else
                if (SHORT1FROMMP (mp1) == IDTIMER_DISPLAYTIMEDMSG)
                {
                    WinStopTimer (pinst->hab, hwnd,
                        IDTIMER_DISPLAYTIMEDMSG);
                    WinSetDlgItemText (hwnd, IDST_STATUSMESSAGES, "");
                }


            return 0;


        case WM_CONTROL:
            if (SHORT1FROMMP (mp1) == IDCNR_SAMPLE)
                switch (SHORT2FROMMP (mp1))
                {
                    case CN_CONTEXTMENU:
                    {
                        /*
                         *  MENU HANDLING
                         */

                        POINTL  ptlMouse;
                        HWND    hwndMenu;

                        WinQueryMsgPos (pinst->hab, &ptlMouse);

                        // Save pointer to record mouse is over, if any
                        pinst->pacrSelected = (PAPPCNRREC) mp2;

                        hwndMenu = pinst->pacrSelected ?
                            pinst->hwndAircraftMenu :
                            pinst->hwndContainerMenu;

                        // Display menu
                        WinPopupMenu (HWND_DESKTOP, hwnd, hwndMenu,
                            ptlMouse.x, ptlMouse.y, 0,
                            PU_HCONSTRAIN | PU_VCONSTRAIN |
                            PU_KEYBOARD | PU_MOUSEBUTTON1 |
                            PU_MOUSEBUTTON2 |
                            PU_MOUSEBUTTON3);
                        return 0;
                    }

                    case CN_INITDRAG:
                        ProcessInitDrag (
                            WinWindowFromID (hwnd, SHORT1FROMMP (mp1)),
                            ((PCNRDRAGINIT) (PVOIDFROMMP(mp2))));
                        return 0;

                    case CN_SCROLL:
                        WinInvalidateRect (pinst->hwndCnr, 0, 0);
                        return 0;
                }
            else

/*
 *  HANDLE WM_CONTROL MESSAGES FROM VALUE SET CONTROL
 */

                if (SHORT1FROMMP (mp1) == IDVS_CONTROLLERS)
                    switch (SHORT2FROMMP (mp1))
                    {
                        case VN_SELECT:
                            DisplayTimedMsg (pinst->hab, hwnd,
                                "Drag an airplane to one "
                                "of the controller icons to hand off to "
                                "another controller.", 8);

                            return 0;

                        case VN_DROP:
                        {
                            PVSDRAGINFO pvsdinfo = (PVSDRAGINFO)
                               PVOIDFROMMP (mp2);
                            PDRAGINFO   pdinfo = pvsdinfo->pDragInfo;
                            PDRAGITEM   pditem;
                            INT         iItem;
                            INT         cHandedOffAircraft = 0;
                            CHAR        szHandedOffAircraft [100];

                            *szHandedOffAircraft = 0;

                            assert (DrgAccessDraginfo(pdinfo));

                            for (iItem = 0; iItem < pdinfo->cditem; ++iItem)
                            {
                                PAPPCNRREC      pacr;

                                pditem =  DrgQueryDragitemPtr (pdinfo, iItem);

                                pacr = (PAPPCNRREC) pditem->ulItemID;

                                if (pdinfo->usOperation == DO_MOVE)
                                {
                                    WinSendMsg (pdinfo->hwndSource,
                                        CM_REMOVERECORD,
                                        MPFROMP(&pacr),
                                        MPFROM2SHORT (1, CMA_INVALIDATE));

                                    if (cHandedOffAircraft++)
                                        strcat (szHandedOffAircraft, ", ");

                                    strcat (szHandedOffAircraft,
                                        pacr->pszCallsign);
                                }
                            }

                            if (cHandedOffAircraft)
                            {
                                CHAR    szMsg [200];

                                sprintf (szMsg,
                                    "Aircraft %s %s been handed off "
                                    "to %s Sector controller.",
                                    szHandedOffAircraft,
                                    cHandedOffAircraft > 1 ?
                                        "have" : "has",
                                    pvsdinfo->usColumn == 1 ?
                                        "West" : "East");

                                DisplayTimedMsg (pinst->hab, hwnd,
                                    szMsg, 8);
                            }

                            DrgFreeDraginfo (pdinfo);
                            WinAlarm (HWND_DESKTOP, WA_NOTE);
                            return 0;
                        }
                    }

            return 0;


        case WM_COMMAND:

            /*
             *  COMMAND HANDLING
             */

            switch (SHORT1FROMMP (mp1))
            {
                case IDMAIRCRAFT_CONTROLINSTRUCT:   // Issue instruction
                {
                    // Present "Control Aircraft" dialog
                    WinDlgBox (HWND_DESKTOP, hwnd,
                        ControlInstructionDlg, 0,
                        IDDLG_CONTROLAIRCRAFT, pinst);
                    return 0;
                }

                case IDMVIEW_RADAR:
                case IDMVIEW_NAME:
                case IDMVIEW_TREE:
                case IDMVIEW_DETAILS:
                case IDMVIEW_TEXT:
                {
                    static const ULONG  aViews [] =
                        { CV_ICON, CV_NAME, CV_TREE, CV_DETAIL, CV_TEXT };

                    CNRINFO ccinfo;
                    memset (&ccinfo, 0, sizeof ccinfo);
                    ccinfo.cb = sizeof ccinfo;
                    ccinfo.flWindowAttr = CA_DETAILSVIEWTITLES |
                        CA_TITLESEPARATOR | CA_TREELINE |
                        CA_OWNERPAINTBACKGROUND |
                        aViews [SHORT1FROMMP (mp1) - IDMVIEW_BASE];
                    WinSendMsg (pinst->hwndCnr, CM_SETCNRINFO, &ccinfo,
                        MPFROMLONG(CMA_FLWINDOWATTR));
                    pinst->CurrentView = SHORT1FROMMP (mp1);

                    WinInvalidateRect (pinst->hwndCnr, 0, 0);
                    return 0;
                }
            }

            return WinDefDlgProc (hwnd, msg, mp1, mp2);

        default:
            return WinDefDlgProc (hwnd, msg, mp1, mp2);
    }
}
INT main( INT argc, PCHAR argv[] )
{
 // Сбрасываем свойства приложения.
 bzero( &Enhancer, sizeof( ENHANCER ) );

 // Определяем приложение в системе.
 Enhancer.Application = WinInitialize( 0 );

 // Если это сделать не удалось - выход.
 if( Enhancer.Application == NULLHANDLE )
  {
   // Звук - ошибка.
   WinAlarm( HWND_DESKTOP, WA_ERROR );
   // Выход.
   DosExit( EXIT_PROCESS, 0 );
  }

 // Создаем очередь сообщений.
 HMQ Message_queue = WinCreateMsgQueue( Enhancer.Application, 0 );

 // Если очередь создать не удалось - выход.
 if( Message_queue == NULLHANDLE )
  {
   // Звук - ошибка.
   WinAlarm( HWND_DESKTOP, WA_ERROR );
   // Выход.
   WinTerminate( Enhancer.Application );
   DosExit( EXIT_PROCESS, 0 );
  }

 // Проверяем системные настройки.
 CheckSystemConfig();

 // Запускаем составляющие приложения.
 StdLib_Start();
 Strings_Start();
 Files_Start();

 Environment_Start();
 EnhancerProperties_Start();

 Loader_Start();
 Launcher_Start();

 // Узнаем, что надо сделать.
 if( argc == 2 )
  {
   if( stristr( "hide",    argv[ 1 ] ) ) Enhancer.Launcher_mode = 1;
   if( stristr( "mini",    argv[ 1 ] ) ) Enhancer.Launcher_mode = 1;
   if( stristr( "launch",  argv[ 1 ] ) ) Enhancer.Launcher_mode = 1;
   if( stristr( "enhance", argv[ 1 ] ) ) Enhancer.Enhancer_mode = 1;
  }

 // Возможно, надо вызвать окно настроек.
 if( argc == 2 )
  {
   if( strstr( "ControlCenter", argv[ 1 ] ) )
    {
     CHAR Path_to_ControlCenter[ SIZE_OF_PATH ] = "";
     GetCurrentPath( Path_to_ControlCenter );
     strcat( Path_to_ControlCenter, "\\Nice-eCS.exe" );

     Execute( Path_to_ControlCenter, argv[ 1 ] );

     WinDestroyMsgQueue( Message_queue );
     WinTerminate( Enhancer.Application );
     DosExit( EXIT_PROCESS, 0 );
    }
  }

 // Если действие не распознано - выход.
 if( !Enhancer.Enhancer_mode && !Enhancer.Launcher_mode )
  {
   WinDestroyMsgQueue( Message_queue );
   WinTerminate( Enhancer.Application );
   DosExit( EXIT_PROCESS, 0 );
  }

 // Если окно приложения уже есть - выход.
 {
  CHAR Semaphore_name[] = "\\SEM32\\NICE-OS2!L"; HMTX hmtxAlreadyRunning = NULLHANDLE;
  if( Enhancer.Enhancer_mode ) Semaphore_name[ strlen( Semaphore_name ) - 1 ] = 'E';

  if( DosOpenMutexSem( Semaphore_name, &hmtxAlreadyRunning ) == NO_ERROR )
   {
    WinDestroyMsgQueue( Message_queue );
    WinTerminate( Enhancer.Application );
    DosExit( EXIT_PROCESS, 0 );
   }
  else
   {
    DosCreateMutexSem( Semaphore_name, &hmtxAlreadyRunning, DC_SEM_SHARED, 1 );
   }
 }

 // Загрузчик должен запускаться до расширителя.
 if( Enhancer.Launcher_mode )
  {
   CHAR Semaphore_name[] = "\\SEM32\\NICE-OS2!E"; HMTX hmtxAlreadyRunning = NULLHANDLE;

   if( DosOpenMutexSem( Semaphore_name, &hmtxAlreadyRunning ) == NO_ERROR )
    {
     WinDestroyMsgQueue( Message_queue );
     WinTerminate( Enhancer.Application );
     DosExit( EXIT_PROCESS, 0 );
    }
  }

 // Расширитель должен запускаться после загрузчика
 if( Enhancer.Enhancer_mode )
  {
   CHAR Semaphore_name[] = "\\SEM32\\NICE-OS2!L"; HMTX hmtxAlreadyRunning = NULLHANDLE;

   if( DosOpenMutexSem( Semaphore_name, &hmtxAlreadyRunning ) != NO_ERROR )
    {
     WinDestroyMsgQueue( Message_queue );
     WinTerminate( Enhancer.Application );
     DosExit( EXIT_PROCESS, 0 );
    }
  }

 // Если надо вызвать загрузчик:
 if( Enhancer.Launcher_mode )
  {
   // Создаем поток для запуска расширителя.
   DosCreateThread( &Threads.Launcher, (PFNTHREAD) LauncherThread, 0, 0, STACK_SIZE );
  }

 // Если надо вызвать расширитель:
 if( Enhancer.Enhancer_mode )
  {
   // Пробуем найти окно загрузчика.
   HWND Launcher_window = NULLHANDLE; CHAR Launcher_title[] = "Nice-OS2!L";

   {
    // Перебираем окна в окне рабочего стола.
    HENUM Enumeration = WinBeginEnumWindows( WinQueryDesktopWindow( Enhancer.Application, NULLHANDLE ) ); HWND Window = NULLHANDLE;
    while( ( Window = WinGetNextWindow( Enumeration ) ) != NULLHANDLE )
     {
      // Узнаем заголовок окна.
      CHAR Window_title[ SIZE_OF_TITLE ] = "";
      WinQueryWindowText( WinWindowFromID( Window, FID_TITLEBAR ), SIZE_OF_TITLE, Window_title );

      // Если это окно расширителя - запоминаем его.
      if( strc( Window_title, Launcher_title ) )
       {
        Launcher_window = Window;
        break;
       }
     }
    WinEndEnumWindows( Enumeration );
   }

   // Если загрузчика нет - выход.
   // Вообще-то он должен быть, раз найден семафор, но кто знает...
   if( !Launcher_window )
    {
     WinTerminate( Enhancer.Application );
     DosExit( EXIT_PROCESS, 0 );
    }

   // Создаем потоки, устанавливаем обработчики событий.
   BYTE Success = NiceLoadEnhancer( Enhancer.Application, 0, Launcher_window );

   // Если это сделать не удалось - выход.
   if( !Success )
    {
     WinTerminate( Enhancer.Application );
     DosExit( EXIT_PROCESS, 0 );
    }

   // Читаем настройки и загружаем изображения в расширитель.
   // Этот метод выполняется внутри Nice-os2.dll, но так как DLL использует
   // адресное пространство приложения, все данные остаются в этом приложении.
   NiceReadSettings( 0 );

   // Включаем слежение за сообщениями.
   NiceRunEnhancer();
  }

 // Создаем окно рабочей области.
 CHAR Class_name[] = "NiceOS2WndClass!L";
 if( Enhancer.Enhancer_mode ) Class_name[ strlen( Class_name ) - 1 ] = 'E';
 WinRegisterClass( Enhancer.Application, Class_name, (PFNWP) Enhancer_MainWindowProc, 0, 0 );

 // Создаем окно рамки.
 CHAR MainWindow_title[] = "Nice-OS2!L";
 if( Enhancer.Enhancer_mode ) Class_name[ strlen( Class_name ) - 1 ] = 'E';

 ULONG Creation_flags = FCF_TITLEBAR | FCF_SYSMENU;
 Enhancer.Frame_window = WinCreateStdWindow( HWND_DESKTOP, CS_FRAME, &Creation_flags, Class_name, MainWindow_title, 0, NULLHANDLE, 0, &Enhancer.Client_window );
 WinShowWindow( Enhancer.Frame_window, 0 );

 // Выбираем сообщения из очереди.
 QMSG Message; bzero( &Message, sizeof( QMSG ) );
 while( WinGetMsg( Enhancer.Application, &Message, 0, 0, 0 ) ) WinDispatchMsg( Enhancer.Application, &Message );

 // Закрываем окна.
 WinDestroyWindow( Enhancer.Client_window );
 WinDestroyWindow( Enhancer.Frame_window );

 // Если вызван расширитель:
 if( Enhancer.Enhancer_mode )
  {
   // Отключаем обработчики событий, завершаем работу потоков.
   NiceReleaseEnhancer( Enhancer.Application, 0 );
  }

 // Удаляем файлы отладочной версии.
 DosForceDelete( "_log.txt" ); DosForceDelete( "XTest.exe" );

 // Сбрасываем очередь сообщений.
 WinDestroyMsgQueue( Message_queue );

 // Выход.
 WinTerminate( Enhancer.Application );
 DosExit( EXIT_PROCESS, 0 );
}
/****************************************************************************
 * Initialize                                                               *
 *  - Performs several application initializations.  Reads profile info,    *
 *    modifies client window to match it, seeds random number generator,    *
 *    initializes game data structures, and starts the timer.               *
 *  - No I/O.                                                               *
 ****************************************************************************/
VOID Initialize(VOID)
{
    INT   i;
    ULONG cb;

    /* Read in the profile data if it exists */
    PrfQueryProfileSize(HINI_USERPROFILE, szClientClass, "Data", &cb);
    if (cb == sizeof(PROFILEREC))
	PrfQueryProfileData(HINI_USERPROFILE, szClientClass, "Data",
			    (PVOID)&prfProfile, &cb);

    /* Make frame size & position match profile information (or initialize) */
    if ((prfProfile.ulMINMAX & SWP_MINIMIZE) ||
	(prfProfile.ulMINMAX & SWP_MAXIMIZE))
	WinSetWindowPos(hwndFrame, HWND_TOP,
	    prfProfile.x, prfProfile.y, prfProfile.cx, prfProfile.cy,
	    SWP_ACTIVATE | SWP_SHOW | SWP_SIZE | SWP_MOVE |
	    prfProfile.ulMINMAX);
    else if ((prfProfile.cx != 0) && (prfProfile.cy != 0))
	WinSetWindowPos(hwndFrame,HWND_TOP,
	    prfProfile.x,prfProfile.y,prfProfile.cx,prfProfile.cy,
	    SWP_ACTIVATE | SWP_SHOW | SWP_SIZE | SWP_MOVE);
    /* Profile information is new.  Rely on PM to size/position the client *
     *   window this first time.                                           */
    else
	WinShowWindow(hwndFrame, TRUE);

    /* Hide controls if hidden at last save                               *
     * Normally this if block should occur prior to the previous one, but *
     *   there appears to be a PM v1.2 bug w/hide before WinSetWindowPos: *
     *   the title bar _looks_ inactive when it is later shown.           */
    if (!prfProfile.bCONTROLS)
	HideFrameControls();

    /* Create a help instance */
    hwndHelp = WinCreateHelpInstance(hab, &hinit);
    if (hwndHelp == NULLHANDLE) {
	/* failed to create help instance */
	WinAlarm(HWND_DESKTOP, WA_WARNING);
	WinMessageBox(HWND_DESKTOP, NULLHANDLE,
	    "Please put ASTEROID.HLP in a directory pointed to by the HELP "
	    "environment variable or in the ASTEROID working directory.",
	    "Could not find help file",
	    0, MB_ICONHAND | MB_OK | MB_APPLMODAL);
	}
    else
	WinAssociateHelpInstance(hwndHelp, hwndFrame);

    /* Initialize Menu according to profile info */
    InitMenu();

    /* Seed the random number generator from seed in profile */
    srand((unsigned int) prfProfile.uiSEED);
    prfProfile.uiSEED = (UINT) rand();

    /* Initialize game data structures */
    WinSendMsg(hwndClient, WM_INITGAME, MPFROMSHORT(0), MPVOID);

    /* Startup a timer for screen updates */
    TogglePause(FORCE_UNPAUSE);
    if ((prfProfile.ulMINMAX & SWP_MINIMIZE) && (!prfProfile.bBACKGRND)) {
	/* Set icon */
	WinSendMsg(hwndFrame, WM_SETICON,
	    (MPARAM)WinLoadPointer(HWND_DESKTOP, NULLHANDLE, ID_RESOURCE),
	    MPVOID);

	TogglePause(SUSPEND_ON);
	}
}
/****************************************************************************
 * ClientWndProc                                                            *
 *  - Typical PM client window procedure.  (see below)                      *
 *  - Standard client window I/O                                            *
 ****************************************************************************/
MRESULT EXPENTRY ClientWndProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
{
	   RECTL  rcl;
	   SWP	  swp;
	   HPS	  hpsPaint;

    static HPS	  hps;                      /* Permanent HPS                */
    static INT    cx, cy;		    /* Client window dimensions     */
    static BOOL   bSlowUpdateNow = FALSE;   /* Update toggle for asteroids  *
                                             *   and enemy which are slow.  */
    static POINTL ptlCenter;		    /* Center of client window      */

    switch (msg) {
      /* Recieved from WinCreateStdWindow */
      case WM_CREATE:
	/* Get permanent PS for entire window */
	hps = WinGetPS(hwnd);

	/* Load private Asteroid fonts from ASTEROID.DLL */
	if (GpiLoadFonts(hab, "ASTEROID") != GPI_OK) {
            WinReleasePS(hps);
	    WinAlarm(HWND_DESKTOP, WA_WARNING);
	    WinMessageBox(HWND_DESKTOP,NULLHANDLE,
		"Please put ASTEROID.DLL in a directory in your LIBPATH.",
		"Error reading ASTEROID.DLL",
		0,MB_ICONHAND|MB_OK|MB_APPLMODAL);
	    WinPostMsg(hwnd,WM_QUIT,(MPARAM) 0L,(MPARAM) 0L);
	    return (MRESULT) TRUE;
	    }

        /* Register/create logical fonts for use */
	InitFonts(hps);

	/* Display About dialoge box */
	WinDlgBox(HWND_DESKTOP, hwnd, (PFNWP)AboutDlgProc, NULLHANDLE,
		  IDD_ABOUT, NULL);

	return 0;

      /* Recieved during attract mode when user starts game */
      case WM_STARTGAME:
        /* Determine the number of players */
	cPlayers = (INT)LONGFROMMP(mp1);

        /* Initialize each player */
	for (Player=0;Player<cPlayers;Player++) {
	    Level[Player] = 1;
	    Ships[Player] = prfProfile.iSHIPS;
	    DeletePhotons();
	    InitAsteroids();
	    InitEnemy();
	    }

        /* Start with player 1 */
	Player = 0;
	iGameMode = GAME_MODE_NEXT;
	iGameModeCnt = GAME_PAUSE_TIME-1;

	/* Hide the pointer if mouse controls are enabled */
	ShowMouse(FALSE);
        
        /* Paint everything */
	WinSendMsg(hwnd, WM_PAINT, MPVOID, MPVOID);

	return 0;

      /* Recieved at startup and at the completion of a game */
      case WM_INITGAME:
        /* Make mouse visible if we hid it before */
        ShowMouse(TRUE);
        
	/* Fix menu to reflect attract mode */
	EnableMenuItem(hwndMenu, IDM_START, TRUE);
	EnableMenuItem(hwndMenu, IDM_STOP, FALSE);

	/* Initialize player and enemy data structures */
	cPlayers = 0;
	Level[0] = 1;
	for (Player=0;Player<2;Player++) {
	    Score[Player] = 0L;
	    Ships[Player] = 0;
	    DeletePhotons();
	    }
	Player = 0;

	/* Initialize asteroids (and enemy) for attract mode */
	InitAsteroids();
	InitEnemy();

        /* Depending on whether ASTEROID was just started or a game just  *
         *   completed display the "High Score" or "Press 1 or 2" screen. */
	if (SHORT1FROMMP(mp1) == 0) {
	    iGameMode = GAME_MODE_INIT1;
	    iGameModeCnt = GAME_INIT_TIME;
	    }
	else {
	    iGameMode = GAME_MODE_INIT2;
	    iGameModeCnt = GAME_INIT_TIME;
	    }

        /* Paint everything */
	WinSendMsg(hwnd, WM_PAINT, MPVOID, MPVOID);
	return 0;

      /* Usually recieved from the system, sometime forced by the program to *
       *   ensure the screen is not corrupt.                                 */
      case WM_PAINT:
	/* Clear entire window to insure no "droppings" */
	WinQueryWindowRect(hwnd,&rcl);
        WinFillRect(hps, &rcl, CLR_BLACK);
	WinInvalidateRect(hwnd, &rcl, FALSE);

	/* Get the update region and paint it black */
	hpsPaint = WinBeginPaint(hwnd, (HPS)NULL, &rcl);
	WinFillRect(hpsPaint, &rcl, CLR_BLACK);
	WinEndPaint(hpsPaint);

        /* Only in normal play mode should we draw the ship */
	if ((iGameMode == GAME_MODE_PLAY) &&
	    (iShipMode[Player] != EXPLOSION) &&
	    (iShipMode[Player] != HYPERSPACE))
	    DrawShip(hps, cx, cy, DRAW_INIT);
	else if ((iGameMode == GAME_MODE_PLAY) &&
		 (iShipMode[Player] == EXPLOSION))
	    ExplodeShip(hps, cx, cy);

        /* Draw the enemy if it is on the screen */
	if (iEnemyMode[Player] != NONE)
	    if (iEnemyMode[Player] != EXPLOSION)
		DrawEnemy(hps, cx, cy,DRAW_INIT);
	    else
		ExplodeEnemy(hps, cx, cy);

        /* Draw photons and asteroids in all modes but the "Enter your *
         *   initials" mode, otherwise draw that screen.               */
	if (iGameMode != GAME_MODE_HIGH) {
	    DrawPhotons(hps, cx, cy, DRAW_INIT);
	    DrawAsteroids(hps, cx, cy, DRAW_INIT);
	    }
	else
	    DrawHighScore(hps, cx, cy, DRAW_INIT);

        /* Always draw the score */
	DrawScore(hps, cx, cy, DRAW_INIT);

	return 0;

      /* Left mouse button down.  This simulates the move/track function *
       *   in the system menu.                                           */
      case WM_BUTTON1DOWN:
        if (prfProfile.bMOUSECONTROL &&
            iGameMode != GAME_MODE_INIT1 &&
            iGameMode != GAME_MODE_INIT2 &&
            !TogglePause(CHECK)) {
	    UPDATE_FIRE(iShipMode[Player], TRUE);
            return (MRESULT)TRUE;
        }
	return WinSendMsg(hwndFrame, WM_TRACKFRAME,
			 (MPARAM) (SHORT1FROMMP(mp2) | TF_MOVE), MPVOID);

      case WM_BUTTON1UP:
        if (prfProfile.bMOUSECONTROL) {
	    UPDATE_FIRE(iShipMode[Player], FALSE);
            return (MRESULT)TRUE;
        }
        return 0;
        
      /* Left mouse button double clicked.  Toggle frame control display. */
      case WM_BUTTON1DBLCLK:
        if (!prfProfile.bMOUSECONTROL ||
            iGameMode == GAME_MODE_INIT1 ||
            iGameMode == GAME_MODE_INIT2 ||
            TogglePause(CHECK)) {
            if (prfProfile.bCONTROLS = !prfProfile.bCONTROLS)
	    	ShowFrameControls();
            else
	    	HideFrameControls();
        }
	return 0;

      case WM_BUTTON2DOWN:
        if (prfProfile.bMOUSECONTROL) {
	    UPDATE_SHIELD(iShipMode[Player], iShipShieldCnt[Player]);
            return (MRESULT)TRUE;
        }
        return 0;
        
      case WM_BUTTON2CLICK:
        if (prfProfile.bMOUSECONTROL) {
            UPDATE_HYPERSPACE(iShipMode[Player], iShipModeCnt[Player]);
            return (MRESULT)TRUE;
        }
        return 0;
        
      /* Right mouse button double clicked.  Display the about dialog box. */
      case WM_BUTTON2DBLCLK:
        if (!prfProfile.bMOUSECONTROL ||
            iGameMode == GAME_MODE_INIT1 ||
            iGameMode == GAME_MODE_INIT2 ||
            TogglePause(CHECK)) {
            WinDlgBox(HWND_DESKTOP, hwndClient, (PFNWP)AboutDlgProc,
            	      NULLHANDLE, IDD_ABOUT, NULL);
        }
	return 0;

      /* User typed a key.  Most of this is self explanatory. */
      case WM_CHAR:
	ProcessChar((CHAR) (CHARMSG(&msg)->vkey-1),
		    CHARMSG(&msg)->fs & KC_VIRTUALKEY,
		    (CHAR) (CHARMSG(&msg)->chr),
		    (BOOL) !(CHARMSG(&msg)->fs & KC_KEYUP));
	return 0;

      /* User entered a command via the menu bar. */
      case WM_COMMAND:
	DoCommand(hwnd, msg, mp1, mp2);
	return 0;

      /* Suspend/un-suspend game depending on focus */
      case WM_SETFOCUS:
	if ((BOOL) SHORT1FROMMP(mp2))
	    TogglePause(SUSPEND_OFF);
	else if (!prfProfile.bBACKGRND)
	    TogglePause(SUSPEND_ON);
	return 0;

      /* Keep track of the client window size.  Profile information is not *
       *   updated here because there are better places (i.e. at exit)     */
      case WM_SIZE:
	cx = (INT)SHORT1FROMMP(mp2);
	cy = (INT)SHORT2FROMMP(mp2);

      /* Keep track of client window position.  Also updates profile info. */
      case WM_MOVE:
	WinQueryWindowPos(hwndFrame,&swp);
	if (!(swp.fl & SWP_MAXIMIZE) && !(swp.fl & SWP_MINIMIZE)) {
	    prfProfile.x  = swp.x;prfProfile.y   = swp.y;
	    prfProfile.cx = swp.cx;prfProfile.cy = swp.cy;
	    }

	if (swp.fl & SWP_MINIMIZE)
	    if (!prfProfile.bBACKGRND) {
		/* Set icon */
		WinSendMsg(hwndFrame, WM_SETICON,
		    (MPARAM) WinLoadPointer(HWND_DESKTOP, NULLHANDLE,
					    ID_RESOURCE), MPVOID);

		TogglePause(SUSPEND_ON);
		}
	    else
		WinSendMsg(hwndFrame, WM_SETICON, MPVOID, MPVOID);
	else
	    TogglePause(SUSPEND_OFF);

	ptlCenter.x = swp.cx / 2;
        ptlCenter.y = swp.cy / 2;
        WinMapWindowPoints(hwndClient, HWND_DESKTOP, &ptlCenter, 1L);

	return 0;

      /* Recieved approximately 31 times a second.  This is the longest and *
       *   ugliest of the messages, partly because there are so many cases  *
       *   to keep track of, partly because it must be highly optimized.    */
      case WM_TIMER:
        if (prfProfile.bMOUSECONTROL &&
            iGameMode != GAME_MODE_INIT1 &&
            iGameMode != GAME_MODE_INIT2) {                   POINTL ptl;
            static BOOL   bUp, bLeft, bRight;

            WinQueryPointerPos(HWND_DESKTOP, &ptl);
            if (bUp || (ptl.y - ptlCenter.y > 0))
	       	UPDATE_THRUST(iShipMode[Player],
            		      bUp = (ptl.y - ptlCenter.y > 0));
            if (bLeft || (ptlCenter.x - ptl.x > 0))
                UPDATE_LEFT(iShipMode[Player],
                	    bLeft = (ptlCenter.x - ptl.x > 0));
            if (bRight || (ptlCenter.x - ptl.x < 0))
                UPDATE_RIGHT(iShipMode[Player],
                 	     bRight = (ptlCenter.x - ptl.x < 0));
            WinSetPointerPos(HWND_DESKTOP, ptlCenter.x, ptlCenter.y);
        }
        
        /* Determine the current game mode */
	switch (iGameMode) {

          /* Either initialization/attract mode screen. */
	  case GAME_MODE_INIT1: case GAME_MODE_INIT2:
            /* Switch screens when count expires */
	    if (--iGameModeCnt == 0) {
		if (iGameMode == GAME_MODE_INIT1)
		    iGameMode = GAME_MODE_INIT2;
		else
		    iGameMode = GAME_MODE_INIT1;
		iGameModeCnt = GAME_INIT_TIME;

                /* Score must be redrawn because the attract mode screens *
                 *   draw the score differently.                          */
		DrawScore(hps, cx, cy, DRAW_REINIT);
		}

            /* Update photons, asteroids, enemy, and score */
	    UpdatePhotons(hps, cx, cy);
	    if (uiSpeed == SPEED_OS2 || (bSlowUpdateNow = !bSlowUpdateNow)) {
		UpdateAsteroids(hps, cx, cy);
		UpdateEnemy(hps, cx, cy);
		DrawScore(hps, cx, cy, DRAW_REFRESH);
		}
	    break;

          /* Completion of one player's turn or new game */
	  case GAME_MODE_NEXT:
            /* Initially, erase and redraw everything for new player */
	    if (iGameModeCnt-- == GAME_PAUSE_TIME) {
		if ((cPlayers == MAXPLAYERS) &&
                    (Ships[(Player+1) % MAXPLAYERS])) {
		    DrawAsteroids(hps, cx, cy, DRAW_ERASE);
		    DrawPhotons(hps, cx, cy, DRAW_ERASE);
		    Player = (Player+1) % MAXPLAYERS;
		    }
		DrawScore(hps, cx, cy, DRAW_REINIT);
		DrawAsteroids(hps, cx, cy, DRAW_INIT);
		}
            /* During countdown update score and asteroids */
	    else if (iGameModeCnt > 0) {
		if (uiSpeed == SPEED_OS2 || (bSlowUpdateNow = !bSlowUpdateNow)) {
		    DrawScore(hps, cx, cy, DRAW_REFRESH);
		    UpdateAsteroids(hps, cx, cy);
		    }
		}
            /* At end of countdown start the player */
	    else {
		InitShip();
		InitEnemy();
		iGameMode = GAME_MODE_PLAY;
		DrawScore(hps, cx, cy, DRAW_REINIT);
		}
	    break;

          /* Normal play mode */
	  case GAME_MODE_PLAY:
            /* Update ship, photons, asteroids, enemy, and score */
	    UpdateShip(hps, cx, cy);
	    UpdatePhotons(hps, cx, cy);
	    if (uiSpeed == SPEED_OS2 || (bSlowUpdateNow = !bSlowUpdateNow)) {
		UpdateAsteroids(hps, cx, cy);
		UpdateEnemy(hps, cx, cy);
                /* Erase old and draw new scores if there is a change*/
		if (bChangeScore) {
		    bChangeScore = FALSE;
		    DrawScore(hps, cx, cy, DRAW_REINIT);
		    }
                /* Else just refresh the score */
		else
		    DrawScore(hps, cx, cy, DRAW_REFRESH);
		}
	    break;

          /* Game over mode.  This is the longest and ugliest case because  *
           *   conditions are highly dependent on the number of players,    *
           *   multiplayer game status, and the number and order of high    *
           *   scores.                                                      */
	  case GAME_MODE_OVER:
            /* Initially, just update the score and number of ships */
	    if (iGameModeCnt-- == GAME_PAUSE_TIME)
		DrawScore(hps, cx, cy, DRAW_REINIT);

            /* During countdown refresh the score and update the asteroids */
	    else if (iGameModeCnt > 0) {
		if (uiSpeed == SPEED_OS2 || (bSlowUpdateNow = !bSlowUpdateNow)) {
		    DrawScore(hps, cx, cy, DRAW_REFRESH);
		    UpdateAsteroids(hps, cx, cy);
		    }
		}

            /* At the end of the countdown, if there are any other players, *
             *   continue with them.                                        */
	    else {
                /* Countinue on with any remaining players. */
		if ((cPlayers == MAXPLAYERS) &&
                    (Ships[(Player+1) % MAXPLAYERS])) {
                    /* Erase all of the old asteroids. */
		    DrawAsteroids(hps, cx, cy, DRAW_ERASE);

                    /* Setup everything for the next player */
		    Player = (Player+1) % MAXPLAYERS;
		    InitShip();
		    InitEnemy();
		    iGameMode = GAME_MODE_PLAY;
		    DrawAsteroids(hps, cx, cy, DRAW_INIT);
		    DrawScore(hps, cx, cy, DRAW_REINIT);
		    }

                /* Check for new high scores and update table as necessary. */
		else {
                    /* Erase all of the old asteroids. */
		    DrawAsteroids(hps, cx, cy, DRAW_ERASE);


                /* The following if/else block is admittedly a kludge, it is *
                 *   simple and it does work, however.  Ideally it should    *
                 *   sort the high scores and update the high score table in *
                 *   descending order.                                       */

                    /* If player 1 scored higher than player 2 then check *
                     *   player 1 first for a high score.                 */
       		    if (Score[0] > Score[1])
			for (Player=0;Player<cPlayers;Player++)
                            /* If the player's score is > than the lowest, *
                             *   update the high score table.              */
			    if (Score[Player] > prfProfile.lSCORES[9]) {
				UpdateHighScores();
				iGameMode = GAME_MODE_HIGH;
				}
                            /* Otherwise, make sure he is not asked for his *
                             *   initials.                                  */
			    else
				Score[Player] = 0;

                    /* Otherwise, check player 2 first */
		    else
			for (Player=cPlayers;Player>=0;Player--)
                            /* If the player's score is > than the lowest, *
                             *   update the high score table.              */
			    if (Score[Player] > prfProfile.lSCORES[9]) {
				UpdateHighScores();
				iGameMode = GAME_MODE_HIGH;
				}
                            /* Otherwise, make sure he is not asked for his *
                             *   initials.                                  */
			    else
				Score[Player] = 0L;

                    /* If there was no high score, go into attract mode */
		    if (iGameMode != GAME_MODE_HIGH)
			WinSendMsg(hwnd,WM_INITGAME,MPFROMSHORT(1),(MPARAM) 0L);
                    /* Else, check for player 1's initials first then 2's   *
                     * This is not faithful, in the arcade game the player  *
                     *   with the higher score always goes first.           */
		    else {
			if (Score[0] > 0L)
			    Player = 0;
			else
			    Player = 1;
			DrawScore(hps, cx, cy, DRAW_REINIT);
			DrawHighScore(hps, cx, cy, DRAW_INIT);
			}
		    }
		}
	    break;

          /* Mode which prompts players to enter their initials */
	  case GAME_MODE_HIGH:
            /* If the player's position is > 0 then refresh the screen */
	    if (Score[Player] > 0L)
		DrawHighScore(hps, cx, cy, DRAW_REFRESH);
            /* Else, the current player is done go to the next */
	    else if ((cPlayers == MAXPLAYERS) && (Player == 0) &&
		     (Score[1] > 0L)) {
		Player++;
		DrawHighScore(hps, cx, cy, DRAW_REINIT);
		}
            /* If there are no more high scores then go into attract mode */
	    else
		WinSendMsg(hwnd, WM_INITGAME, MPFROMSHORT(1), MPVOID);
	    break;
	  }
	return 0;

      /* Used by help manager */
      case HM_QUERY_KEYS_HELP:
	 return((MRESULT)IDH_CLIENTKEYS);

      /* Recieved always from the system or in the case of an initialization*
       *   error.  Both messages will normally save the profile information.*
       * Ideally the profile section should be moved to a subroutine and the*
       *   the following should be broken into two distinct cases.	    */
      case WM_SAVEAPPLICATION:
      case WM_DESTROY:
	/* If the fonts were not found bApplicationOk will be false, in     *
	 *   that case the window profile information should not be updated.*/
	if (TRUE) {
	    /* Copy window position and size info into profile structure */
	    WinQueryWindowPos(hwndFrame, &swp);
	    if (swp.fl & SWP_MAXIMIZE)
		prfProfile.ulMINMAX = SWP_MAXIMIZE;
	    else if (swp.fl & SWP_MINIMIZE)
		prfProfile.ulMINMAX = SWP_MINIMIZE;
	    else {
		prfProfile.ulMINMAX = 0;
		prfProfile.x  = swp.x;prfProfile.y   = swp.y;
		prfProfile.cx = swp.cx;prfProfile.cy = swp.cy;
		}

	    /* Write profile information */
	    PrfWriteProfileData(HINI_USERPROFILE, szClientClass, "Data",
		&prfProfile, sizeof(PROFILEREC));
	    }

        /* If the application is terminating release the fonts and the hps. */
        if (msg == WM_DESTROY) {
	    /* Make sure mouse is visible if we hid it before */
            ShowMouse(TRUE);
            
	    /* Release font identifiers and DLL resource module */
	    GpiSetCharSet(hps, LCID_DEFAULT);
	    GpiDeleteSetId(hps, LCID_LARGE);
	    GpiDeleteSetId(hps, LCID_SMALL);
	    GpiUnloadFonts(hab, "ASTEROID");

	    /* Release the "permanent" presentation space */
	    WinReleasePS(hps);
            }
	return 0;

      }
    return WinDefWindowProc(hwnd, msg, mp1, mp2);
}
Beispiel #22
0
int main (int argc, char *argv[])
   {
   APIRET       rc;
   PCHAR        pcEnv;
   PRFPROFILE   prfProfile;

#ifdef DEBUG
   ulDebugMask = 0xFFFFFFFF;
#endif /* DEBUG */

   hab = WinInitialize(0);
   hmq = WinCreateMsgQueue(hab, 0);
   DebugS (1, "PM Interface initialized");

   /* Shared Memory organisieren */
   if (rc = DosGetNamedSharedMem ((PPVOID) &pShareInitOS2,
                                  SHARE_INITOS2,
                                  PAG_READ | PAG_WRITE))
      {
      if (rc = DosAllocSharedMem( (PPVOID) &pShareInitOS2,    // Pointer to shared mem
                                  SHARE_INITOS2,              // Name
                                  CCHSHARE_INITOS2,           // Size of shared mem
                                  PAG_COMMIT | PAG_READ | PAG_WRITE)) // Flags
         return(1);
      else
         {
         /* Shared Memory initialisieren */

         memset (pShareInitOS2, '\0', CCHSHARE_INITOS2);

         pShareInitOS2->pszRegFile       = (PCHAR) pShareInitOS2 +
                                          sizeof(*pShareInitOS2);
         strcpy (pShareInitOS2->pszRegFile,
                 DosScanEnv (ENV_SYSTEM_INI, &pcEnv) ? "" : pcEnv);
         pShareInitOS2->pszRootUserIni   = pShareInitOS2->pszRegFile +
                                          strlen(pShareInitOS2->pszRegFile) + 1;
         pShareInitOS2->pszRootSystemIni = pShareInitOS2->pszRootUserIni + 1;
         pShareInitOS2->pszUserIni       = pShareInitOS2->pszRootSystemIni + 1;
         pShareInitOS2->pszSystemIni     = pShareInitOS2->pszUserIni   + CCHMAXPATH;
         pShareInitOS2->pszEnvironment   = pShareInitOS2->pszSystemIni + CCHMAXPATH;
         }
      }
   DebugS (1, "Shared Memory initialized");

   /* Semaphoren organisieren */
   rc = DosOpenEventSem (HEV_SAMMY, &hevSammy);

   if( rc )
      rc = DosCreateEventSem( HEV_SAMMY,   // Name
                              &hevSammy,   // Pointer to sem
                              0,           // Not used with named sems
                              FALSE);      // Initial state (FALSE = SET)

   else        /* Sammy ist bereits installiert */
      {
      pShareInitOS2->pszEnvironment[0] = '\0';
      pShareInitOS2->pszEnvironment[1] = '\0';
      pShareInitOS2->pszSystemIni[0]   = '\0';
      pShareInitOS2->pszUserIni[0]     = '\0';
      DosPostEventSem(hevSammy);
      goto Exit;
      }

   if( rc )
      {
      intSammyRetCode = rc;
      goto Exit;
      }

   rc = DosOpenEventSem (HEV_PRFRESETLOCK, &hevPrfResetLock);

   if( rc )
      rc = DosCreateEventSem( HEV_PRFRESETLOCK, // Name
                              &hevPrfResetLock, // Pointer to sem
                              0,                // Not used with named sems
                              TRUE);            // Initial state (TRUE = POSTED)

   if( rc )
      {
      intSammyRetCode = rc;
      goto Exit;
      }
   DebugS (1, "Semaphores initialized");

   ChangeWPS(pShareInitOS2->pszUserIni, pShareInitOS2->pszSystemIni);

   /* Hintergrundloop starten, das Shell mit aktueller Env. startet */

   DosCreateThread (&tid1,
                    (PFNTHREAD) thStartProg,
                    (ULONG) ((argc > 1) ? argv[1] : ""),
                    0,
                    THREADSTACK);
   DebugS (1, "Background loop started");

   /* Hintergrundloop starten, das jeweils nach L�schen einer Semaphore */
   /* einen prfReset initiiert                      */
   DosCreateThread (&tid2,
                    (PFNTHREAD) thSwitch,
                    (ULONG) 0,
                    0,
                    THREADSTACK);

   while (WinGetMsg (hab, &qmsg, 0, 0, 0))
      WinDispatchMsg (hab, &qmsg);

   if (intSammyRetCode)
      {
      DosKillThread (tid1);
      DosKillThread (tid2);

      WinSetObjectData(WinQueryObject("<WP_DESKTOP>"), "WORKAREA=NO");
      WinPostMsg(WinQueryWindow(HWND_DESKTOP, QW_BOTTOM), WM_CLOSE, 0, 0);

      WinAlarm (HWND_DESKTOP, WA_ERROR);

      prfProfile.pszSysName  = (DosScanEnv (ENV_SYSTEM_INI, &pcEnv) ? "" : pcEnv);
      prfProfile.pszUserName = (DosScanEnv (ENV_USER_INI, &pcEnv) ? "" : pcEnv);

      prfProfile.cchUserName = strlen(prfProfile.pszUserName);
      prfProfile.cchSysName  = strlen(prfProfile.pszSysName);

      DosSleep (1000);
      DosKillProcess( DKP_PROCESSTREE, ulShellID );

      if ( !PrfReset(hab, &prfProfile))
         WinSetObjectData(WinQueryObject("<WP_DESKTOP>"), "OPEN=ICON;WORKAREA=YES");
      }
Exit:
   WinDestroyMsgQueue(hmq);
   WinTerminate(hab);

   DebugS (1, "Application terminated");

   return intSammyRetCode;
   }
Beispiel #23
0
ULONG ulExecProg (CHAR *szProgName)
   {
   ULONG        ulBootDrive;
   ULONG        ulAppType;
   CHAR         szCmdName[CCHMAXPATH];
   CHAR         szLine[CCHMAXPATH];
   PSZ          pszScanEnv;
   RESULTCODES  rcTermination;
   APIRET       rcFailure = 0;
   PCHAR        pszEnvironment;

/*
 *  Diese Routine versucht eine Shell zu starten.
 */

   pszEnvironment = MakeEnv (pShareInitOS2->pszEnvironment);

   if ( !(rcFailure = ScanEnv(ENV_SAMWORKPLACE, &pszScanEnv, pszEnvironment)) )
      {
      rcFailure = DosQueryAppType(pszScanEnv, &ulAppType);

      if ( !rcFailure )
         if ( ( (ulAppType & 7) == FAPPTYP_NOTSPEC) ||
              ( (ulAppType & 7) == FAPPTYP_WINDOWAPI) )
            rcFailure = DosExecPgm (szLine,           /* Object name buffer */
                                 sizeof(szLine),      /* Length of object name buffer */
                                 EXEC_ASYNCRESULT,    /* Execution flags */
                                 "",                  /* Argument string */
                                 pszEnvironment,       /* Environment */
                                 &rcTermination,      /* Termination codes */
                                 pszScanEnv);         /* Program file name */
         else
            rcFailure = 1;
      }

   if (rcFailure)
      {
      WinAlarm (HWND_DESKTOP, WA_ERROR);
      DebugS (1, "DosExecPgm <1> failed");
      }

   if (rcFailure)
      {
      rcFailure = DosExecPgm (szLine,              /* Object name buffer */
                              sizeof(szLine),      /* Length of object name buffer */
                              EXEC_ASYNCRESULT,    /* Execution flags */
                              "",                  /* Argument string */
                              pszEnvironment,       /* Environment */
                              &rcTermination,      /* Termination codes */
                              szProgName);         /* Program file name */
      }

   if (rcFailure)
      {
      if (!(rcFailure = DosScanEnv (ENV_SAMWORKPLACE, &pszScanEnv)))
         rcFailure = DosExecPgm (szLine,        /* Object name buffer */
                           sizeof(szLine),      /* Length of object name buffer */
                           EXEC_ASYNCRESULT,    /* Execution flags */
                           "",                  /* Argument string */
                           pszEnvironment,       /* Environment */
                           &rcTermination,      /* Termination codes */
                           pszScanEnv);         /* Program file name */
      }

   if (rcFailure)
      {
      DebugS (1, "DosExecPgm <2> failed");
      DosQuerySysInfo (QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof (ULONG));

      memset (szCmdName, '\0', sizeof(szCmdName));
      szCmdName[0] = (CHAR) (ulBootDrive - 1) + 'A';
      strcpy (szCmdName+1, ":\\OS2\\PMSHELL.EXE");

      rcFailure = DosExecPgm (szLine,           /* Object name buffer */
                           sizeof(szLine),      /* Length of object name buffer */
                           EXEC_ASYNCRESULT,    /* Execution flags */
                           "",                  /* Argument string */
                           pszEnvironment,       /* Environment */
                           &rcTermination,      /* Termination codes */
                           szCmdName);          /* Program file name */
      }

/* Falls Shell nicht gestartet werden konnte, wird cmd.exe aufgerufen */

   if (rcFailure)
      {
      DebugS (1, "DosExecPgm <3> failed");
      if (!(rcFailure = DosScanEnv ("COMSPEC", &pszScanEnv)))
         rcFailure = DosExecPgm (szLine,        /* Object name buffer */
                           sizeof(szLine),      /* Length of object name buffer */
                           EXEC_ASYNCRESULT,    /* Execution flags */
                           "/K",                /* Argument string */
                           pszEnvironment,       /* Environment */
                           &rcTermination,      /* Termination codes */
                           pszScanEnv);         /* Program file name */
      }

   if (rcFailure)
      {
      DebugS (1, "DosExecPgm <4> failed");
      DosQuerySysInfo (QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, &ulBootDrive, sizeof (ULONG));

      memset (szCmdName, '\0', sizeof(szCmdName));
      szCmdName[0] = (CHAR) (ulBootDrive - 1) + 'A';
      strcpy (szCmdName+1, ":\\OS2\\CMD.EXE");

      rcFailure = DosExecPgm (szLine,        /* Object name buffer */
                        sizeof(szLine),      /* Length of object name buffer */
                        EXEC_ASYNCRESULT,    /* Execution flags */
                        "/K",                /* Argument string */
                        pszEnvironment,       /* Environment */
                        &rcTermination,      /* Termination codes */
                        szCmdName);          /* Program file name */
      }

   DosFreeMem(pszEnvironment);

   if (rcFailure)
      {
      intSammyRetCode = rcFailure;
      WinPostQueueMsg (hmq, WM_CLOSE, 0L, 0L);
      DebugS (1, "DosExecPgm <5> failed");
      }

   return (rcFailure ? 0 : rcTermination.codeTerminate);
   }
Beispiel #24
0
// Set some data onto the clipboard
void nsClipboard::SetClipboardData(const char *aFlavor)
{
  void *pMozData = nsnull;
  PRUint32 NumOfBytes = 0;

  // Get the data from the transferable
  nsCOMPtr<nsISupports> genericDataWrapper;
#ifdef DEBUG
  nsresult errCode =
#endif
  mTransferable->GetTransferData( aFlavor, getter_AddRefs(genericDataWrapper), &NumOfBytes );
#ifdef DEBUG
  if (NS_FAILED(errCode)) printf( "nsClipboard:: Error getting data from transferable\n" );
#endif
  if (NumOfBytes == 0) return;
  nsPrimitiveHelpers::CreateDataFromPrimitive( aFlavor, genericDataWrapper, &pMozData, NumOfBytes );

  /* If creating the data failed, just return */
  if (!pMozData) {
    return;
  }

  ULONG ulFormatID = GetFormatID( aFlavor );

  if (strstr( aFlavor, "text/" ))  // All text/.. flavors are null-terminated
  {
    if (ulFormatID == CF_TEXT)     // CF_TEXT is one byte character set
    {
      char* pByteMem = nsnull;

      if (DosAllocSharedMem( reinterpret_cast<PPVOID>(&pByteMem), nsnull, NumOfBytes + sizeof(char), 
                             PAG_WRITE | PAG_COMMIT | OBJ_GIVEABLE ) == NO_ERROR)
      {
        memcpy( pByteMem, pMozData, NumOfBytes );       // Copy text string
        pByteMem[NumOfBytes] = '\0';                    // Append terminator

        // With Warp4 copying more than 64K to the clipboard works well, but
        // legacy apps cannot always handle it. So output an alarm to alert the
        // user that there might be a problem.
        if (strlen(pByteMem) > 0xFFFF) {
          WinAlarm(HWND_DESKTOP, WA_ERROR);
        }
        WinSetClipbrdData(0, reinterpret_cast<ULONG>(pByteMem), ulFormatID, CFI_POINTER);
      }
    }
    else                           // All other text/.. flavors are in unicode
    {
      UniChar* pUnicodeMem = nsnull;
      PRUint32 NumOfChars = NumOfBytes / sizeof(UniChar);
   
      if (DosAllocSharedMem( reinterpret_cast<PPVOID>(&pUnicodeMem), nsnull, NumOfBytes + sizeof(UniChar), 
                             PAG_WRITE | PAG_COMMIT | OBJ_GIVEABLE ) == NO_ERROR) 
      {
        memcpy( pUnicodeMem, pMozData, NumOfBytes );    // Copy text string
        pUnicodeMem[NumOfChars] = L'\0';                // Append terminator

        WinSetClipbrdData( 0, reinterpret_cast<ULONG>(pUnicodeMem), ulFormatID, CFI_POINTER );
      }

      // If the flavor is unicode, we also put it on the clipboard as CF_TEXT
      // after conversion to locale charset.

      if (!strcmp( aFlavor, kUnicodeMime ))
      {
        char* pByteMem = nsnull;

        if (DosAllocSharedMem(reinterpret_cast<PPVOID>(&pByteMem), nsnull,
                              NumOfBytes + 1, 
                              PAG_WRITE | PAG_COMMIT | OBJ_GIVEABLE ) == NO_ERROR) 
        {
          PRUnichar* uchtemp = (PRUnichar*)pMozData;
          for (PRUint32 i=0;i<NumOfChars;i++) {
            switch (uchtemp[i]) {
              case 0x2018:
              case 0x2019:
                uchtemp[i] = 0x0027;
                break;
              case 0x201C:
              case 0x201D:
                uchtemp[i] = 0x0022;
                break;
              case 0x2014:
                uchtemp[i] = 0x002D;
                break;
            }
          }

          nsAutoCharBuffer buffer;
          PRInt32 bufLength;
          WideCharToMultiByte(0, static_cast<PRUnichar*>(pMozData),
                              NumOfBytes, buffer, bufLength);
          memcpy(pByteMem, buffer.Elements(), NumOfBytes);
          // With Warp4 copying more than 64K to the clipboard works well, but
          // legacy apps cannot always handle it. So output an alarm to alert the
          // user that there might be a problem.
          if (strlen(pByteMem) > 0xFFFF) {
            WinAlarm(HWND_DESKTOP, WA_ERROR);
          }
          WinSetClipbrdData(0, reinterpret_cast<ULONG>(pByteMem), CF_TEXT, CFI_POINTER);
        }
      }
    }
  }
  else                             // Assume rest of flavors are binary data
  {
    PBYTE pBinaryMem = nsnull;

    if (DosAllocSharedMem( reinterpret_cast<PPVOID>(&pBinaryMem), nsnull, NumOfBytes + sizeof(PRUint32), 
                           PAG_WRITE | PAG_COMMIT | OBJ_GIVEABLE ) == NO_ERROR) 
    {
      *(reinterpret_cast<PRUint32*>(pBinaryMem)) = NumOfBytes;          // First DWORD contains data length
      memcpy( pBinaryMem + sizeof(PRUint32), pMozData, NumOfBytes );  // Copy binary data

      WinSetClipbrdData( 0, reinterpret_cast<ULONG>(pBinaryMem), ulFormatID, CFI_POINTER );
    }

    // If the flavor is image, we also put it on clipboard as CF_BITMAP
    // after conversion to OS2 bitmap

    if (strstr (aFlavor, "image/"))
    {
      //  XXX OS2TODO  Convert jpg, gif, png to bitmap
#ifdef DEBUG
      printf( "nsClipboard:: Putting image on clipboard; should also convert to BMP\n" );
#endif
    }
  }
  nsMemory::Free(pMozData);
}
Beispiel #25
0
/*
	SAVER_PROC
	This is the entry point into the saver module that is called by
	the ScreenSaver program.
	There should be no reason to alter the code.
	Depending on the requested function, the following tasks
	are performed:
	* set the name of the INI file to store and query settings
	* call the configuration dialog of the saver module
	* copy the name of the saver module into the supplied buffer
	* tell if the saver module is enabled
	* set the "enabled" state of the saver module
	* start the saver
	* stop the saver
	Note that before any processing is done, module configuration data is
	loaded from the INI-files.
*/
void	EXPENTRY SAVER_PROC(int function, HAB _hab, HWND hwndOwner, char *appname, void *buffer)
{
	hab = _hab;
	application_name = appname;
	hwndApplication = hwndOwner;
	// load all configuration data from INI-file
        if(function != FUNCTION_SETINIFILENAME)
	    load_configuration_data();
	switch(function){
	case FUNCTION_SETINIFILENAME:
		if(buffer != NULL)
			strcpy(ini_filename, (char *)buffer);
		else
			strcpy(ini_filename, "");
		return;
	case FUNCTION_CONFIGURE:
		// call the configuration dialog
		WinDlgBox(HWND_DESKTOP, hwndOwner, ConfigureDlgProc,
		  hmodDLL, IDD_CONFIGURE, application_name);
		return;
	case FUNCTION_STARTSAVER:
		// start the saver
		// get "low priority" state from supplied buffer (BOOL *)
		low_priority = *((BOOL *)buffer);
		// query size of screen
		screenSizeX = WinQuerySysValue(HWND_DESKTOP, SV_CXSCREEN);
		screenSizeY = WinQuerySysValue(HWND_DESKTOP, SV_CYSCREEN);
		// register window class for the saver window
		WinRegisterClass(hab, (PSZ)modulename,
		  (PFNWP)SaverWindowProc, 0, 0);
		// create the saver window
		hwndSaver = WinCreateWindow(HWND_DESKTOP, (PSZ)modulename,
		  (PSZ)NULL, WS_VISIBLE, 0, 0, screenSizeX, screenSizeY,
		  HWND_DESKTOP, HWND_TOP, 0, NULL, NULL);
		return;
	case FUNCTION_STOPSAVER:
		// stop the saver
		if(low_priority){
			stop_priority_thread = TRUE;
			DosSetPriority(PRTYS_THREAD, PRTYC_REGULAR, 0, tidPriority);
			DosSetPriority(PRTYS_THREAD, PRTYC_REGULAR, 0, tidDraw);
			DosWaitThread(&tidPriority, DCWW_WAIT);
//			  DosKillThread(tidPriority);	***** kills thread 1 under OS/2 2.11
		}
		// tell drawing-thread to stop
		stop_draw_thread = TRUE;
		if(DosWaitThread(&tidDraw, DCWW_NOWAIT) == ERROR_THREAD_NOT_TERMINATED){
			// if priority of drawing-thread was set to idle time
			// priority, set it back to normal value
			DosSetPriority(PRTYS_THREAD, PRTYC_REGULAR, PRTYD_MAXIMUM, tidDraw);
			// wait until drawing-thread has ended
			DosWaitThread(&tidDraw, DCWW_WAIT);
		}

		if(hwndSaver != NULLHANDLE){
			// move saver window to front
			WinSetWindowPos(hwndSaver, HWND_TOP,
			  0, 0, 0, 0, SWP_ZORDER);
			// destroy saver window
			WinDestroyWindow(hwndSaver);
			hwndSaver = NULLHANDLE;
		}
		return;
	case FUNCTION_QUERYNAME:
		// copy module name to supplied buffer (CHAR *)
		strcpy(buffer, modulename);
		return;
	case FUNCTION_QUERYENABLED:
		// copy "enabled" state to supplied buffer (BOOL *)
		*((BOOL *)buffer) = configuration_data.enabled;
		return;
	case FUNCTION_SETENABLED:
		// get new "enabled" state from supplied buffer (BOOL *)
		configuration_data.enabled = *((BOOL *)buffer);
		write_profile_data();
		return;
	}

	// illegal function request
	WinAlarm(HWND_DESKTOP, WA_ERROR);
	return;
}
VOID main( VOID )
{
 // ********************************************************** //

 // Можно создать приложение, *.dll или *.obj.
 CHAR Target[] = "/Ge+ /Ss+";    // Приложение.
 // CHAR Target[] = "/C /Ss+";   // Object.
 // CHAR Target[] = "/Ge- /Ss+"; // Library.

 // Процессор - Pentium.
 CHAR Processor[] = "/G5 /Gf+ /Gi+";

 // Оптимизация - по скорости.
 CHAR Optimization[] = "/Gs+ /O+ /Oi+";

 // Размер стека - как и у всех потоков.
 CHAR Stack_size[] = "/B\"/ST:32768\"";

 // Имена файлов.
 CHAR CPP_Name[] = "Nice-os2.cpp";
 CHAR DEF_Name[] = "Nice-os2.def";
 CHAR LIB_Name[] = "..\\Shared\\DosCalls\\Doscalls.lib";

 CHAR RC_Name[] =  "Resources\\Resources.rc";
 CHAR RES_Name[] = "Resources\\Resources.res";

 CHAR OBJ_Name[] = "Nice-os2.obj";
 CHAR TGT_Name[] = "Nice-os2.exe ";

 // ********************************************************** //

 // Задаем параметры.
 CHAR Compiler[] = "Icc.exe"; CHAR Parameters[ 255 ] = "";
 strcpy( Parameters, Compiler );     strcat( Parameters, "|" );
 strcat( Parameters, Target );       strcat( Parameters, " " );
 strcat( Parameters, CPP_Name );     strcat( Parameters, " " );
 strcat( Parameters, DEF_Name );     strcat( Parameters, " " );
 strcat( Parameters, LIB_Name );     strcat( Parameters, " " );
 strcat( Parameters, Processor );    strcat( Parameters, " " );
 strcat( Parameters, Optimization ); strcat( Parameters, " " );
 strcat( Parameters, Stack_size );
 strchg( Parameters, '|', 0x00 );

 // Удаляем файлы, которые требуется получить.
 DosForceDelete( TGT_Name );

 // Вызываем IBM VA C++.
 CHAR Error_string[ 1 ]; RESULTCODES Return_codes;
 DosResetBuffer( -1 ); DosExecPgm( Error_string, sizeof( Error_string ), EXEC_SYNC, Parameters, NULL, &Return_codes, Compiler );

 // Задаем параметры для Resource Compiler.
 // RC.exe - 16-разрядное приложение, и его надо вызвать как "Cmd /C RC.exe".
 CHAR RC_starter[] = "Cmd.exe"; Parameters[ 0 ] = 0;
 strcpy( Parameters, RC_starter );   strcat( Parameters, "|" );
 strcat( Parameters, "/C RC.exe" );  strcat( Parameters, " " );
 strcat( Parameters, RC_Name );      strcat( Parameters, " " );
 strcat( Parameters, TGT_Name );
 strchg( Parameters, '|', 0x00 );

 // Вызываем Resource Compiler.
 DosResetBuffer( -1 ); DosExecPgm( Error_string, sizeof( Error_string ), EXEC_SYNC, Parameters, NULL, &Return_codes, RC_starter );

 // Удаляем временные файлы.
 DosForceDelete( OBJ_Name ); DosForceDelete( RES_Name );

 // Звук.
 WinAlarm( HWND_DESKTOP, WA_NOTE );

 // Выход.
 return;
}
/*����������������������������������������������������������������������������*/
 MRESULT FilterDlgProc(          HWND    hwnd,
                        register ULONG   message,
                                 MPARAM  lParam1,
                                 MPARAM  lParam2 )

  {
     /*���������������������������������������������������������������������Ŀ*/
     /*� Local Variables                                                     �*/
     /*�����������������������������������������������������������������������*/
     MRESULT            dpResult = NULL;

     register USHORT    pbSelected;
     CHAR               sFilterItem[128];
     PMSG_ITEM          pMsg;

     static PSPY_DATA   pSpyData = NULL;

     HWND               hwndLB;                /* HWND of message listbox */

    /*����������������������������������������������������������������������Ŀ*/
    /*� Process the message                                                  �*/
    /*������������������������������������������������������������������������*/
    switch (message)                          /* Switch off of the message ID */
    {
        /*������������������������������������������������������������������Ŀ*/
        /*� One of our pushbuttons was pressed...                            �*/
        /*��������������������������������������������������������������������*/
        case WM_COMMAND:

          switch( pbSelected = LOUSHORT( lParam1 ) )
          {
              /*������������������������������������������������������������Ŀ*/
              /*� Process selected items                                     �*/
              /*��������������������������������������������������������������*/
              default:
              {
                USHORT        curItem,            /* current list item        */
                              nSelected;          /* Number of items selected */

                MSG_COLOR     color = GetColor( hwnd, pSpyData);

                /*����������������������������������������������������������Ŀ*/
                /*� Obtain HWND of message listbox once for performance      �*/
                /*������������������������������������������������������������*/
                hwndLB = WinWindowFromID(hwnd, IDD_FILTER);

                /************************************************************
                * "Lock" the ListBox to minimize performance impact
                ************************************************************/
                WinLockWindowUpdate(HWND_DESKTOP,     /* Desktop */
                                    hwndLB);          /* Lockee  */

                /************************************************************
                * Process the "selected" ListBox items
                ************************************************************/
                for(nSelected = 0,                    /* Initialize */
                    curItem   = SHORT1FROMMR(WinSendMsg(hwndLB,
                                                        LM_QUERYSELECTION,
                                                        MPFROMSHORT(LIT_FIRST),
                                                        NULL) );

                    curItem != (USHORT)LIT_NONE;      /* While      */

                    nSelected++,                     /* Iterate     */
                    curItem   = SHORT1FROMMR(WinSendMsg(hwndLB,
                                                        LM_QUERYSELECTION,
                                                        MPFROMSHORT(curItem),
                                                        NULL) )
                   )
                {
                  /*��������������������������������������������������������Ŀ*/
                  /*� Locate specific MSG item for this selected item        �*/
                  /*����������������������������������������������������������*/
                  pMsg = PVOIDFROMMR( WinSendMsg(hwndLB,
                                                 LM_QUERYITEMHANDLE,
                                                 MPFROMSHORT(curItem),
                                                 NULL) );

                  /*��������������������������������������������������������Ŀ*/
                  /*� Perform action on this selected item                   �*/
                  /*����������������������������������������������������������*/
                  switch( pbSelected )
                  {
                    /*********************************************************
                    * Delete this MSG's definition
                    **********************************************************/
                    case ID_PB_F_DELETE:

                         DeleteMsg(pSpyData, pMsg->Msg);

                         WinSendMsg(hwndLB,
                                    LM_DELETEITEM,
                                    MPFROMSHORT(curItem),
                                    MPFROMP(NULL));

                         curItem = (USHORT)( (curItem == 0)
                                             ? LIT_FIRST
                                             : (curItem - 1) );
                    break;

                    /*********************************************************
                    * Mark that this MSG can NOT be "spied" / act as "trigger"
                    **********************************************************/
                    case ID_PB_F_EXCLUDE:

                         IncludeMsg(pSpyData, pMsg->Msg, BOOL_FALSE, color);

                         WinSendMsg(hwndLB,
                                    LM_SETITEMTEXT,
                                    MPFROMSHORT(curItem),
                                    MPFROMP(FormatMSG(pMsg, sFilterItem)));
                    break;

                    /*********************************************************
                    * Mark that this MSG can be "spied" / act as "trigger"
                    **********************************************************/
                    case ID_PB_F_INCLUDE:

                         IncludeMsg(pSpyData, pMsg->Msg, BOOL_TRUE, color);

                         WinSendMsg(hwndLB,
                                    LM_SETITEMTEXT,
                                    MPFROMSHORT(curItem),
                                    MPFROMP(FormatMSG(pMsg, sFilterItem)));
                    break;

                    /*********************************************************
                    * Set FREEZE "trigger"
                    **********************************************************/
                    case ID_PB_F_FREEZE:

                         pMsg->TriggerFreeze  = BOOL_TRUE;
                         pMsg->TriggerThaw    = BOOL_FALSE;

                         WinSendMsg(hwndLB,
                                           LM_SETITEMTEXT,
                                           MPFROMSHORT(curItem),
                                           MPFROMP(FormatMSG(pMsg, sFilterItem)));

                         if (color != Color_Asis)
                           pMsg->ClrFG = color;
                    break;

                    /*********************************************************
                    * Set THAW "trigger"
                    **********************************************************/
                    case ID_PB_F_THAW:

                         pMsg->TriggerThaw    = BOOL_TRUE;
                         pMsg->TriggerFreeze  = BOOL_FALSE;

                         WinSendMsg(hwndLB,
                                    LM_SETITEMTEXT,
                                    MPFROMSHORT(curItem),
                                    MPFROMP(FormatMSG(pMsg, sFilterItem)));

                         if (color != Color_Asis)
                           pMsg->ClrFG = color;
                    break;

                    /*********************************************************
                    * Remove FREEZE and THAW "triggers"
                    **********************************************************/
                    case ID_PB_F_NO_TRIGGER:

                         pMsg->TriggerFreeze  =
                         pMsg->TriggerThaw    = BOOL_FALSE;

                         WinSendMsg(hwndLB,
                                    LM_SETITEMTEXT,
                                    MPFROMSHORT(curItem),
                                    MPFROMP(FormatMSG(pMsg, sFilterItem)));

                         if (color != Color_Asis)
                           pMsg->ClrFG = color;
                    break;

                    /*********************************************************
                    * Reset MSG unique data
                    **********************************************************/
                    case ID_PB_F_RESET:

                         pMsg->aulTimes[MSG_TIMES_SINCE] = 0;

                         if (color != Color_Asis)
                           pMsg->ClrFG = color;
                    break;
                  }
                }

                /************************************************************
                * Finally, "unlock" the ListBox so it is only redrawn once
                ************************************************************/
                WinLockWindowUpdate(HWND_DESKTOP, NULLHANDLE);

                /************************************************************
                * Make "noise" if no items were selected...
                ************************************************************/
                if (nSelected == 0)
                  WinAlarm(HWND_DESKTOP, WA_ERROR);
              }
              break;

              /*������������������������������������������������������������Ŀ*/
              /*� User cancelled dialog                                      �*/
              /*��������������������������������������������������������������*/
              case DID_CANCEL:

                   WinDismissDlg(hwnd, 0);              /* Close dialog */
              break;
          }
        break;                                          /* Break WM_COMMAND             */

        /*������������������������������������������������������������������Ŀ*/
        /*� WM_CLOSE:                                                        �*/
        /*� - Call WinDismissDlg to close the dialog box                     �*/
        /*��������������������������������������������������������������������*/

        case WM_CLOSE:                                  /* Close Dialog Box.    */

             WinDismissDlg( hwnd, 0);

        break;

        /*������������������������������������������������������������������Ŀ*/
        /*� WM_INITDLG:                                                      �*/
        /*� - Init pointer to data pointed to by WinDlgBox                   �*/
        /*� - Init global handle of this dlg                                 �*/
        /*�                                                                  �*/
        /*� - MP2 = PSPY_DATA                                                �*/
        /*��������������������������������������������������������������������*/
        case WM_INITDLG:
        {
               register USHORT  list_index;

               /*�����������������������������������������������������������Ŀ*/
               /*� Locate "SPY" data to utilize                              �*/
               /*�������������������������������������������������������������*/
               pSpyData = PVOIDFROMMP(lParam2);

               /*�����������������������������������������������������������Ŀ*/
               /*� Obtain HWND of message listbox once for performance       �*/
               /*�������������������������������������������������������������*/
               hwndLB = WinWindowFromID(hwnd, IDD_FILTER);

              /*������������������������������������������������������������Ŀ*/
              /*� Set listbox FONT to current non-proportional value         �*/
              /*��������������������������������������������������������������*/
              SetListboxFont(hwndLB, (PSZ) pSpyData->pfnLB);

              /************************************************************
              * "Lock" the ListBox to minimize performance impact
              ************************************************************/
              WinLockWindowUpdate(HWND_DESKTOP,     /* Desktop */
                                  hwndLB);          /* Lockee  */

              /*�����������������������������������������������������������Ŀ*/
              /*� Add all Messages to list box                              �*/
              /*�������������������������������������������������������������*/
              for( /* Initialize */  pMsg = ProcessFirstMsg(pSpyData); /* start @ first MSG */
                   /* Terminate  */  pMsg != NULL;                     /* stop at End-Of-Table */
                   /* Iterate    */  pMsg = ProcessNextMsg(pSpyData)   /* try the next MSG */
                 )
              {
                list_index = (USHORT)
                    WinSendMsg(hwndLB,
                               LM_INSERTITEM,
                               MPFROMSHORT(LIT_SORTASCENDING),
                               MPFROMP(FormatMSG(pMsg, sFilterItem)) );

                WinSendMsg(hwndLB,                    /* Window Handle              */
                           LM_SETITEMHANDLE,          /* Message                    */
                           MPFROMSHORT(list_index),   /* Index of list item         */
                           MPFROMP(pMsg));            /* Handle of list item        */
              }

              /************************************************************
              * Finally, "unlock" the ListBox so it is only redrawn once
              ************************************************************/
              WinLockWindowUpdate(HWND_DESKTOP, NULLHANDLE);

              /************************************************************
              * Other dialog set-up
              ************************************************************/
              SetColors( hwnd, pSpyData );      /* load colors       */

              CenterDialog(hwnd);               /* Center the Dialog */
        }
        break;

        /*������������������������������������������������������������������Ŀ*/
        /*� We don't need to handle any other messages...                    �*/
        /*�                                                                  �*/
        /*� If this isn't an IPF message, let PM do it's default "thing"     �*/
        /*��������������������������������������������������������������������*/
        default:
             if ( !HandleIPF(hwnd, message, lParam1, lParam2, &dpResult) )
               dpResult = WinDefDlgProc(hwnd,       /* Dialog Handle                */
                                        message,    /* Message                      */
                                        lParam1,    /* First parameter for message. */
                                        lParam2);   /* Second parameter for message.*/

      } /* End MSG switch */

   /*�����������������������������������������������������������������������Ŀ*/
   /*� Exit                                                                  �*/
   /*�������������������������������������������������������������������������*/
   return( dpResult );
}
Beispiel #28
0
SOM_Scope BOOL SOMLINK WPSamFolder_RootDesktop (WPSamF *somSelf)
    {
    static PRFPROFILE    prfProfile;
    PCHAR                szUserIni;
    PCHAR                szSysIni;
    /* WPSamFData *somThis = WPSamFGetData(somSelf); */
    WPSamFMethodDebug ("WPSamF","WPSamFolder_RootDesktop");

    /** Untersuchung, ob bereits im Rootdesktop **/
    /* Namen der laufenden User- und System-INI-Dateien */
    prfProfile.cchUserName = 0L;
    prfProfile.cchSysName  = 0L;

    PrfQueryProfile (WinQueryAnchorBlock(HWND_DESKTOP), &prfProfile);

    prfProfile.pszUserName = malloc (prfProfile.cchUserName);
    prfProfile.pszSysName  = malloc (prfProfile.cchSysName);

    PrfQueryProfile (WinQueryAnchorBlock(HWND_DESKTOP), &prfProfile);

    DebugE (D_SWT, "RootDesktop (current user-INI)",   prfProfile.pszUserName);
    DebugE (D_SWT, "RootDesktop (current system-INI)", prfProfile.pszSysName);

    /* Namen der Stammprofile */
    if (pShareInitOS2)
        {
        szUserIni = pShareInitOS2->pszRootUserIni;
        szSysIni  = pShareInitOS2->pszRootSystemIni;
        }
    else
        szUserIni = szSysIni = "";

    if (szUserIni[0] == '\0')
        if (DosScanEnv(USER_INI, &szUserIni))
            goto root_false;

    if (szSysIni[0] == '\0')
        if (DosScanEnv (SYSTEM_INI, &szSysIni))
            goto root_false;

    /* Vergleich der User-Ini Namen */
    if (strcmpi (szUserIni, prfProfile.pszUserName) == 0)
        {
        WinAlarm (HWND_DESKTOP, WA_NOTE);
        MessageBox (IDS_ALREADYINROOT, IDS_INFORMATION, MB_ENTER | MB_INFORMATION);
            goto root_false;
        }

    free (prfProfile.pszUserName);
    free (prfProfile.pszSysName);

    /** Umschaltung **/
    if (hevSammy)
        {
        pShareInitOS2->pszEnvironment[0] = '\0';
        pShareInitOS2->pszEnvironment[1] = '\0';
        pShareInitOS2->pszSystemIni[0]   = '\0';
        pShareInitOS2->pszUserIni[0]     = '\0';
        DebugE (D_SWT, "RootDesktop", "Ab hier macht Sammy weiter");
        DosPostEventSem (hevSammy);
        }

    return TRUE;

root_false:
    free (prfProfile.pszUserName);
    free (prfProfile.pszSysName);

    return FALSE;
    }