emu48-mirror/sources/Emu48/EMU48.C
2024-03-19 22:37:03 +01:00

1537 lines
41 KiB
C

/*
* Emu48.c
*
* This file is part of Emu48
*
* Copyright (C) 1995 Sebastien Carlier
*
*/
#include "pch.h"
#include "resource.h"
#include "Emu48.h"
#include "io.h"
#include "kml.h"
#include "debugger.h"
#define VERSION "1.25"
#define CF_HPOBJ "CF_HPOBJ" // clipboard format for DDE
#define MAXPORTS 16 // number of COM ports
// #define MONOCHROME // CF_BITMAP clipboard format
#ifdef _DEBUG
LPTSTR szNoTitle = _T("Emu48 ")_T(VERSION)_T(" Debug");
#else
LPTSTR szNoTitle = _T("Emu48 ")_T(VERSION);
#endif
LPTSTR szAppName = _T("Emu48"); // application name for DDE server
LPTSTR szTopic = _T("Stack"); // topic for DDE server
LPTSTR szTitle = NULL;
static const TCHAR szLicence[] =
_T("This program is free software; you can redistribute it and/or modify\r\n")
_T("it under the terms of the GNU General Public License as published by\r\n")
_T("the Free Software Foundation; either version 2 of the License, or\r\n")
_T("(at your option) any later version.\r\n")
_T("\r\n")
_T("This program is distributed in the hope that it will be useful,\r\n")
_T("but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n")
_T("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n")
_T("See the GNU General Public License for more details.\r\n")
_T("\r\n")
_T("You should have received a copy of the GNU General Public License\r\n")
_T("along with this program; if not, write to the Free Software Foundation,\r\n")
_T("Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA");
CRITICAL_SECTION csGDILock; // critical section for hWindowDC
CRITICAL_SECTION csKeyLock; // critical section for key scan
CRITICAL_SECTION csIOLock; // critical section for I/O access
CRITICAL_SECTION csT1Lock; // critical section for timer1 access
CRITICAL_SECTION csT2Lock; // critical section for timer2 access
CRITICAL_SECTION csRecvLock; // critical section for receive byte
INT nArgc; // no. of command line arguments
LPCTSTR *ppArgv; // command line arguments
LARGE_INTEGER lFreq; // high performance counter frequency
LARGE_INTEGER lAppStart; // high performance counter value at Appl. start
DWORD idDdeInst; // DDE server id
UINT uCF_HpObj; // DDE clipboard format
HANDLE hThread;
DWORD lThreadId;
HANDLE hEventShutdn; // event handle to stop cpu thread
HINSTANCE hApp = NULL;
HWND hWnd = NULL;
HWND hDlgDebug = NULL; // handle for debugger dialog
HWND hDlgFind = NULL; // handle for debugger find dialog
HDC hWindowDC = NULL;
HPALETTE hPalette = NULL;
HPALETTE hOldPalette = NULL; // old palette of hWindowDC
BOOL bAutoSave = FALSE;
BOOL bAutoSaveOnExit = TRUE;
BOOL bAlwaysDisplayLog = TRUE;
//################
//#
//# Window Status
//#
//################
VOID SetWindowTitle(LPTSTR szString)
{
if (szTitle) LocalFree(szTitle);
_ASSERT(hWnd != NULL);
if (szString)
{
szTitle = DuplicateString(szString);
SetWindowText(hWnd, szTitle);
}
else
{
szTitle = NULL;
SetWindowText(hWnd, szNoTitle);
}
return;
}
VOID UpdateWindowStatus()
{
if (hWnd) // window open
{
// disable stack loading items on HP38G, HP39/40G
BOOL bStackEnable = cCurrentRomType!='6' && cCurrentRomType!='A' && cCurrentRomType!='E';
BOOL bRun = nState == SM_RUN || nState == SM_SLEEP;
UINT uStackEnable = (bRun && bStackEnable) ? MF_ENABLED : MF_GRAYED;
UINT uRun = bRun ? MF_ENABLED : MF_GRAYED;
UINT uBackup = bBackup ? MF_ENABLED : MF_GRAYED;
HMENU hMenu = GetMenu(hWnd); // get menu handle
EnableMenuItem(hMenu,ID_FILE_NEW,MF_ENABLED);
EnableMenuItem(hMenu,ID_FILE_OPEN,MF_ENABLED);
EnableMenuItem(hMenu,ID_FILE_SAVE,(bRun && szCurrentFilename[0]) ? MF_ENABLED : MF_GRAYED);
EnableMenuItem(hMenu,ID_FILE_SAVEAS,uRun);
EnableMenuItem(hMenu,ID_FILE_CLOSE,uRun);
EnableMenuItem(hMenu,ID_OBJECT_LOAD,uStackEnable);
EnableMenuItem(hMenu,ID_OBJECT_SAVE,uStackEnable);
EnableMenuItem(hMenu,ID_VIEW_COPY,uRun);
EnableMenuItem(hMenu,ID_STACK_COPY,uStackEnable);
EnableMenuItem(hMenu,ID_STACK_PASTE,uStackEnable);
EnableMenuItem(hMenu,ID_VIEW_RESET,uRun);
EnableMenuItem(hMenu,ID_BACKUP_SAVE,uRun);
EnableMenuItem(hMenu,ID_BACKUP_RESTORE,uBackup);
EnableMenuItem(hMenu,ID_BACKUP_DELETE,uBackup);
EnableMenuItem(hMenu,ID_VIEW_SCRIPT,uRun);
EnableMenuItem(hMenu,ID_TOOL_DISASM,uRun);
EnableMenuItem(hMenu,ID_TOOL_DEBUG,(bRun && !bDbgEnable) ? MF_ENABLED : MF_GRAYED);
}
return;
}
//################
//#
//# Clipboard Tool
//#
//################
VOID CopyItemsToClipboard(HWND hWnd) // save selected Listbox Items to Clipboard
{
LONG i;
LPINT lpnCount;
// get number of selections
if ((i = SendMessage(hWnd,LB_GETSELCOUNT,0,0)) == 0)
return; // no items selected
if ((lpnCount = (LPINT) LocalAlloc(LMEM_FIXED,i * sizeof(INT))) != NULL)
{
HANDLE hClipObj;
LONG j,lMem = 0;
// get indexes of selected items
i = SendMessage(hWnd,LB_GETSELITEMS,i,(LPARAM) lpnCount);
for (j = 0;j < i;++j) // scan all selected items
{
// calculate total amount of needed memory
lMem += SendMessage(hWnd,LB_GETTEXTLEN,lpnCount[j],0) + 2;
}
// allocate clipboard data
if ((hClipObj = GlobalAlloc(GMEM_MOVEABLE,lMem + 1)) != NULL)
{
LPBYTE lpData;
if ((lpData = GlobalLock(hClipObj)))
{
for (j = 0;j < i;++j) // scan all selected items
{
lpData += SendMessage(hWnd,LB_GETTEXT,lpnCount[j],(LPARAM) lpData);
*lpData++ = '\r';
*lpData++ = '\n';
}
*lpData = 0; // set end of string
GlobalUnlock(hClipObj); // unlock memory
}
if (OpenClipboard(hWnd))
{
if (EmptyClipboard())
SetClipboardData(CF_TEXT,hClipObj);
else
GlobalFree(hClipObj);
CloseClipboard();
}
else // clipboard open failed
{
GlobalFree(hClipObj);
}
}
LocalFree(lpnCount); // free item table
}
return;
}
//################
//#
//# Settings
//#
//################
// set listfield for serial combobox
static VOID SetCommList(HWND hDlg,int nIDDlgItem,LPCTSTR szSetting)
{
HANDLE hComm;
BOOL bAdd;
WORD wCount, wIndex = 1;
TCHAR szBuffer[16];
WPARAM wSelect = 0; // set select to disabled
SendDlgItemMessage(hDlg,nIDDlgItem,CB_ADDSTRING,0,(LPARAM) NO_SERIAL);
for (wCount = 1;wCount <= MAXPORTS;++wCount)
{
wsprintf(szBuffer,_T("COM%u"),wCount);
if ((bAdd = (lstrcmp(szBuffer,szSetting) == 0)))
wSelect = wIndex;
// test if COM port is valid
hComm = CreateFile(szBuffer,GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
if(hComm != INVALID_HANDLE_VALUE)
{
BOOL bError = CloseHandle(hComm);
_ASSERT(bError);
bAdd = TRUE;
}
if (bAdd) // add item to combobox
{
SendDlgItemMessage(hDlg,nIDDlgItem,CB_ADDSTRING,0,(LPARAM) szBuffer);
++wIndex;
}
}
SendDlgItemMessage(hDlg,nIDDlgItem,CB_SETCURSEL,wSelect,0L);
}
static BOOL CALLBACK SettingsProc(HWND hDlg, UINT message, DWORD wParam, LONG lParam)
{
switch (message)
{
case WM_INITDIALOG:
// init speed checkbox
CheckDlgButton(hDlg,IDC_REALSPEED,bRealSpeed);
CheckDlgButton(hDlg,IDC_AUTOSAVE,bAutoSave);
CheckDlgButton(hDlg,IDC_AUTOSAVEONEXIT,bAutoSaveOnExit);
CheckDlgButton(hDlg,IDC_ALWAYSDISPLOG,bAlwaysDisplayLog);
// set disassebler mode
CheckDlgButton(hDlg,(disassembler_mode == HP_MNEMONICS) ? IDC_DISASM_HP : IDC_DISASM_CLASS,BST_CHECKED);
// set combobox parameter
SetCommList(hDlg,IDC_WIRE,szSerialWire);
SetCommList(hDlg,IDC_IR,szSerialIr);
if (bCommInit) // disable when port open
{
EnableWindow(GetDlgItem(hDlg,IDC_WIRE),FALSE);
EnableWindow(GetDlgItem(hDlg,IDC_IR),FALSE);
}
// HP48SX/GX
if (cCurrentRomType=='S' || cCurrentRomType=='G')
{
// init port1 enable checkbox
CheckDlgButton(hDlg,IDC_PORT1EN,(Chipset.cards_status & PORT1_PRESENT) != 0);
CheckDlgButton(hDlg,IDC_PORT1WR,(Chipset.cards_status & PORT1_WRITE) != 0);
// init port2 shared checkbox and set port2 filename
CheckDlgButton(hDlg,IDC_PORT2ISSHARED,bPort2IsShared);
SetDlgItemText(hDlg,IDC_PORT2,szPort2Filename);
if (nState == SM_INVALID) // Invalid State
{
EnableWindow(GetDlgItem(hDlg,IDC_PORT1EN),FALSE);
EnableWindow(GetDlgItem(hDlg,IDC_PORT1WR),FALSE);
}
}
else // HP38G/HP39G/HP40G/HP49G
{
EnableWindow(GetDlgItem(hDlg,IDC_PORT1EN),FALSE);
EnableWindow(GetDlgItem(hDlg,IDC_PORT1WR),FALSE);
if (nState == SM_INVALID) // Invalid State
{
// init port2 shared checkbox and set port2 filename
CheckDlgButton(hDlg,IDC_PORT2ISSHARED,bPort2IsShared);
SetDlgItemText(hDlg,IDC_PORT2,szPort2Filename);
}
if (cCurrentRomType=='X') // HP49G
{
SendDlgItemMessage(hDlg,IDC_IR,CB_RESETCONTENT,0,0);
EnableWindow(GetDlgItem(hDlg,IDC_IR),FALSE);
}
}
if (nState != SM_INVALID) // not in Invalid State
{
// hide port2 settings
EnableWindow(GetDlgItem(hDlg,IDC_PORT2ISSHARED),FALSE);
EnableWindow(GetDlgItem(hDlg,IDC_PORT2),FALSE);
}
return TRUE;
case WM_COMMAND:
if (wParam == IDOK)
{
if (Chipset.Port1Size && cCurrentRomType!='X')
{
UINT nOldState = SwitchToState(SM_SLEEP);
// save old card status
BYTE bCardsStatus = Chipset.cards_status;
// port1 disabled?
Chipset.cards_status &= ~(PORT1_PRESENT | PORT1_WRITE);
if (IsDlgButtonChecked(hDlg, IDC_PORT1EN))
{
Chipset.cards_status |= PORT1_PRESENT;
if (IsDlgButtonChecked(hDlg, IDC_PORT1WR))
Chipset.cards_status |= PORT1_WRITE;
}
// changed card status in slot1?
if ( ((bCardsStatus ^ Chipset.cards_status) & (PORT1_PRESENT | PORT1_WRITE)) != 0
&& (Chipset.IORam[CARDCTL] & ECDT) != 0 && (Chipset.IORam[TIMER2_CTRL] & RUN) != 0
)
{
Chipset.HST |= MP; // set Module Pulled
IOBit(SRQ2,NINT,FALSE); // set NINT to low
Chipset.SoftInt = TRUE; // set interrupt
bInterrupt = TRUE;
}
Map(0x00,0xFF);
SwitchToState(nOldState);
}
// get speed checkbox value
bRealSpeed = IsDlgButtonChecked(hDlg,IDC_REALSPEED);
bAutoSave = IsDlgButtonChecked(hDlg, IDC_AUTOSAVE);
bAutoSaveOnExit = IsDlgButtonChecked(hDlg, IDC_AUTOSAVEONEXIT);
bAlwaysDisplayLog = IsDlgButtonChecked(hDlg, IDC_ALWAYSDISPLOG);
SetSpeed(bRealSpeed); // set speed
if (nState == SM_INVALID)
{
bPort2IsShared = IsDlgButtonChecked(hDlg,IDC_PORT2ISSHARED);
GetDlgItemText(hDlg,IDC_PORT2,szPort2Filename,ARRAYSIZEOF(szPort2Filename));
}
// set disassebler mode
disassembler_mode = IsDlgButtonChecked(hDlg,IDC_DISASM_HP) ? HP_MNEMONICS : CLASS_MNEMONICS;
// set combobox parameter
GetDlgItemText(hDlg,IDC_WIRE,szSerialWire,ARRAYSIZEOF(szSerialWire));
if (cCurrentRomType!='X') // HP49G Ir port is not connected
GetDlgItemText(hDlg,IDC_IR,szSerialIr,ARRAYSIZEOF(szSerialIr));
EndDialog(hDlg, wParam);
}
if (wParam == IDCANCEL)
{
EndDialog(hDlg, wParam);
}
break;
}
return FALSE;
UNREFERENCED_PARAMETER(lParam);
}
//################
//#
//# Save Helper
//#
//################
//
// UINT SaveChanges(BOOL bAuto);
// Return code :
// IDYES File successfuly saved
// IDNO File not saved
// IDCANCEL Cancel command
//
static UINT SaveChanges(BOOL bAuto)
{
UINT uReply;
if (pbyRom == NULL) return IDNO;
if (bAuto)
uReply = IDYES;
else
uReply = YesNoCancelMessage(_T("Do you want to save changes ?"));
if (uReply != IDYES) return uReply;
if (szCurrentFilename[0]==0)
{ // Save As...
uReply = GetSaveAsFilename();
if (uReply != IDOK) return uReply;
if (!SaveDocumentAs(szBufferFilename)) return IDCANCEL;
WriteLastDocument(szCurrentFilename);
return IDYES;
}
SaveDocument();
return IDYES;
}
//################
//#
//# Message Handlers
//#
//################
//
// WM_CREATE
//
static LRESULT OnCreate(HWND hWindow)
{
InitializeCriticalSection(&csGDILock);
InitializeCriticalSection(&csKeyLock);
InitializeCriticalSection(&csIOLock);
InitializeCriticalSection(&csT1Lock);
InitializeCriticalSection(&csT2Lock);
InitializeCriticalSection(&csRecvLock);
hWnd = hWindow;
hWindowDC = GetDC(hWnd);
DragAcceptFiles(hWnd,TRUE); // support dropped files
return 0;
}
//
// WM_DESTROY
//
static LRESULT OnDestroy(HWND hWindow)
{
DragAcceptFiles(hWnd,FALSE); // no WM_DROPFILES message any more
ReleaseDC(hWnd, hWindowDC);
SetWindowTitle(NULL); // free memory of title
hWindowDC = NULL; // hWindowDC isn't valid any more
hWnd = NULL;
DeleteCriticalSection(&csGDILock);
DeleteCriticalSection(&csKeyLock);
DeleteCriticalSection(&csIOLock);
DeleteCriticalSection(&csT1Lock);
DeleteCriticalSection(&csT2Lock);
DeleteCriticalSection(&csRecvLock);
#if defined _USRDLL // DLL version
DLLDestroyWnd(); // cleanup system
#else // EXE version
PostQuitMessage(0); // exit message loop
#endif
return 0;
UNREFERENCED_PARAMETER(hWindow);
}
//
// WM_PAINT
//
static LRESULT OnPaint(HWND hWindow)
{
PAINTSTRUCT Paint;
HDC hPaintDC;
hPaintDC = BeginPaint(hWindow, &Paint);
if (hMainDC != NULL)
{
EnterCriticalSection(&csGDILock); // solving NT GDI problems
{
UINT nLines = (Chipset.lcounter == 0) ? 64 : (Chipset.lcounter + 1);
// redraw background bitmap
BitBlt(hPaintDC, Paint.rcPaint.left, Paint.rcPaint.top,
Paint.rcPaint.right-Paint.rcPaint.left, Paint.rcPaint.bottom-Paint.rcPaint.top,
hMainDC, Paint.rcPaint.left, Paint.rcPaint.top, SRCCOPY);
// redraw main display area
BitBlt(hWindowDC, nLcdX, nLcdY,
131*nLcdDoubled, nLines*nLcdDoubled,
hLcdDC, Chipset.boffset*nLcdDoubled, 0, SRCCOPY);
// redraw menu display area
BitBlt(hWindowDC, nLcdX, nLcdY+nLines*nLcdDoubled,
131*nLcdDoubled, (64-nLines)*nLcdDoubled,
hLcdDC, 0, nLines*nLcdDoubled, SRCCOPY);
GdiFlush();
}
LeaveCriticalSection(&csGDILock);
UpdateAnnunciators();
RefreshButtons(&Paint.rcPaint);
}
EndPaint(hWindow, &Paint);
return 0;
}
//
// WM_DROPFILES
//
static LRESULT OnDropFiles(HANDLE hFilesInfo)
{
TCHAR szFileName[MAX_PATH];
WORD wNumFiles,wIndex;
BOOL bSuccess;
// HP38G/HP39G/HP40G has no stack, ignore
if (cCurrentRomType=='6' || cCurrentRomType=='A' || cCurrentRomType=='E') return 0;
// get number of files dropped
wNumFiles = DragQueryFile (hFilesInfo,(UINT)-1,NULL,0);
if (!Chipset.dispon && !bDbgEnable) // calculator off, turn on
{
// turn on HP
KeyboardEvent(TRUE,0,0x8000);
Sleep(200);
KeyboardEvent(FALSE,0,0x8000);
}
_ASSERT(nState == SM_RUN); // emulator must be in RUN state
if (WaitForSleepState()) // wait for cpu SHUTDN then sleep state
{
DragFinish (hFilesInfo);
InfoMessage(_T("The emulator is busy."));
return 0;
}
_ASSERT(nState == SM_SLEEP);
// get each name and load it into the emulator
for (wIndex = 0;wIndex < wNumFiles;++wIndex)
{
DragQueryFile (hFilesInfo,wIndex,szFileName,ARRAYSIZEOF(szFileName));
// szFileName has file name, now try loading it
if ((bSuccess = LoadObject(szFileName)) == FALSE)
break;
}
DragFinish (hFilesInfo);
SwitchToState(SM_RUN); // run state
while (nState!=nNextState) Sleep(0);
_ASSERT(nState == SM_RUN);
if (bSuccess == FALSE) // data not copied
return 0;
KeyboardEvent(TRUE,0,0x8000);
Sleep(200);
KeyboardEvent(FALSE,0,0x8000);
// wait for sleep mode
while(Chipset.Shutdn == FALSE) Sleep(0);
return 0;
}
//
// ID_FILE_NEW
//
static LRESULT OnFileNew()
{
SaveBackup();
if (pbyRom)
{
SwitchToState(SM_INVALID);
if (IDCANCEL == SaveChanges(bAutoSave))
goto cancel;
}
if (NewDocument()) SetWindowTitle(_T("Untitled"));
UpdateWindowStatus();
cancel:
if (pbyRom) SwitchToState(SM_RUN);
return 0;
}
//
// ID_FILE_OPEN
//
static LRESULT OnFileOpen()
{
if (pbyRom)
{
SwitchToState(SM_INVALID);
if (IDCANCEL == SaveChanges(bAutoSave))
goto cancel;
}
if (GetOpenFilename())
{
OpenDocument(szBufferFilename);
}
cancel:
if (pbyRom) SwitchToState(SM_RUN);
return 0;
}
//
// ID_FILE_SAVE
//
static LRESULT OnFileSave()
{
if (pbyRom == NULL) return 0;
SwitchToState(SM_INVALID);
SaveChanges(TRUE);
SwitchToState(SM_RUN);
return 0;
}
//
// ID_FILE_SAVEAS
//
static LRESULT OnFileSaveAs()
{
UINT uReply;
if (pbyRom == NULL) return 0;
SwitchToState(SM_INVALID);
uReply = GetSaveAsFilename();
if (uReply != IDOK)
{
SwitchToState(SM_RUN);
return 0;
}
if (!SaveDocumentAs(szBufferFilename))
{
SwitchToState(SM_RUN);
return 0;
}
WriteLastDocument(szCurrentFilename);
SwitchToState(SM_RUN);
return 0;
}
//
// ID_FILE_CLOSE
//
static LRESULT OnFileClose()
{
if (pbyRom == NULL) return 0;
SwitchToState(SM_INVALID);
if (SaveChanges(bAutoSave)!=IDCANCEL)
{
KillKML();
ResetDocument();
SetWindowTitle(NULL);
}
else
{
SwitchToState(SM_RUN);
}
return 0;
}
//
// ID_FILE_EXIT
//
// WM_SYS_CLOSE
//
static LRESULT OnFileExit()
{
SwitchToState(SM_INVALID); // hold emulation thread
if (SaveChanges(bAutoSaveOnExit) == IDCANCEL)
{
SwitchToState(SM_RUN); // on cancel restart emulation thread
return 0;
}
DestroyWindow(hWnd);
return 0;
}
//
// ID_STACK_COPY
//
static LRESULT OnStackCopy() // copy data from stack
{
HANDLE hClipObj;
LPBYTE lpData;
DWORD dwAddress,dwSize;
_ASSERT(nState == SM_RUN); // emulator must be in RUN state
if (WaitForSleepState()) // wait for cpu SHUTDN then sleep state
{
InfoMessage(_T("The emulator is busy."));
return 0;
}
_ASSERT(nState == SM_SLEEP);
if ((dwAddress = RPL_Pick(1)) == 0) // pick address of level1 object
{
MessageBeep(MB_OK); // error beep
goto error;
}
if (Read5(dwAddress) != 0x02A2C) // string object
{
MessageBeep(MB_OK); // error beep
goto error;
}
dwAddress += 5; // address of string length
dwSize = (Read5(dwAddress) - 5) / 2; // length of string
// memory allocation for clipboard data
if ((hClipObj = GlobalAlloc(GMEM_MOVEABLE,dwSize + 1)) == NULL)
goto error;
if ((lpData = GlobalLock(hClipObj))) // lock memory
{
// copy data into clipboard buffer
for (dwAddress += 5;dwSize-- > 0;dwAddress += 2,++lpData)
*lpData = Read2(dwAddress);
*lpData = 0; // set end of string
GlobalUnlock(hClipObj); // unlock memory
if (OpenClipboard(hWnd))
{
if (EmptyClipboard())
SetClipboardData(CF_TEXT,hClipObj);
else
GlobalFree(hClipObj);
CloseClipboard();
}
}
else // lock memory failed
{
GlobalFree(hClipObj);
}
error:
SwitchToState(SM_RUN);
return 0;
}
//
// ID_STACK_PASTE
//
static LRESULT OnStackPaste() // paste data to stack
{
HANDLE hClipObj;
LPBYTE lpClipdata,lpData;
BOOL bSuccess = FALSE;
if (!Chipset.dispon && !bDbgEnable) // calculator off, turn on
{
KeyboardEvent(TRUE,0,0x8000);
Sleep(200);
KeyboardEvent(FALSE,0,0x8000);
// wait for sleep mode
while(Chipset.Shutdn == FALSE) Sleep(0);
}
_ASSERT(nState == SM_RUN); // emulator must be in RUN state
if (WaitForSleepState()) // wait for cpu SHUTDN then sleep state
{
InfoMessage(_T("The emulator is busy."));
return 0;
}
_ASSERT(nState == SM_SLEEP);
if (OpenClipboard(hWnd))
{
if ( IsClipboardFormatAvailable(CF_TEXT)
|| IsClipboardFormatAvailable(CF_OEMTEXT))
{
if ((hClipObj = GetClipboardData(CF_TEXT)))
{
if ((lpClipdata = GlobalLock(hClipObj)))
{
DWORD dwSize = strlen(lpClipdata);
if ((lpData = (LPBYTE) LocalAlloc(LMEM_FIXED,dwSize * 2)))
{
memcpy(lpData+dwSize,lpClipdata,dwSize); // copy data
bSuccess = (WriteStack(lpData,dwSize) == S_ERR_NO);
LocalFree(lpData);
}
GlobalUnlock(hClipObj);
}
}
}
else // unknown clipboard format
{
MessageBeep(MB_OK); // error beep
}
CloseClipboard();
}
SwitchToState(SM_RUN); // run state
while (nState!=nNextState) Sleep(0);
_ASSERT(nState == SM_RUN);
if (bSuccess == FALSE) // data not copied
return 0;
KeyboardEvent(TRUE,0,0x8000);
Sleep(200);
KeyboardEvent(FALSE,0,0x8000);
// wait for sleep mode
while(Chipset.Shutdn == FALSE) Sleep(0);
return 0;
}
//
// ID_VIEW_COPY
//
static LRESULT OnViewCopy()
{
if (OpenClipboard(hWnd))
{
if (EmptyClipboard())
{
#if !defined MONOCHROME
// DIB bitmap
#define WIDTHBYTES(bits) (((bits) + 31) / 32 * 4)
#define PALVERSION 0x300
BITMAP bm;
LPBITMAPINFOHEADER lpbi;
PLOGPALETTE ppal;
HBITMAP hBmp;
HDC hBmpDC;
HANDLE hClipObj;
WORD wBits;
DWORD dwLen, dwSizeImage;
_ASSERT(nLcdDoubled == 1 || nLcdDoubled == 2 || nLcdDoubled == 4);
hBmp = CreateCompatibleBitmap(hLcdDC,131*nLcdDoubled,64*nLcdDoubled);
hBmpDC = CreateCompatibleDC(hLcdDC);
hBmp = SelectObject(hBmpDC,hBmp);
BitBlt(hBmpDC, 0, 0, 131*nLcdDoubled, 64*nLcdDoubled, hLcdDC, 0, 0, SRCCOPY);
hBmp = SelectObject(hBmpDC,hBmp);
// fill BITMAP structure for size information
GetObject(hBmp, sizeof(bm), &bm);
wBits = bm.bmPlanes * bm.bmBitsPixel;
// make sure bits per pixel is valid
if (wBits <= 1)
wBits = 1;
else if (wBits <= 4)
wBits = 4;
else if (wBits <= 8)
wBits = 8;
else // if greater than 8-bit, force to 24-bit
wBits = 24;
dwSizeImage = WIDTHBYTES((DWORD)bm.bmWidth * wBits) * bm.bmHeight;
// calculate memory size to store CF_DIB data
dwLen = sizeof(BITMAPINFOHEADER) + dwSizeImage;
if (wBits != 24) // a 24 bitcount DIB has no color table
{
// add size for color table
dwLen += (1 << wBits) * sizeof(RGBQUAD);
}
// memory allocation for clipboard data
if ((hClipObj = GlobalAlloc(GMEM_MOVEABLE, dwLen)) != NULL)
{
lpbi = GlobalLock(hClipObj);
// initialize BITMAPINFOHEADER
lpbi->biSize = sizeof(BITMAPINFOHEADER);
lpbi->biWidth = bm.bmWidth;
lpbi->biHeight = bm.bmHeight;
lpbi->biPlanes = 1;
lpbi->biBitCount = wBits;
lpbi->biCompression = BI_RGB;
lpbi->biSizeImage = dwSizeImage;
lpbi->biXPelsPerMeter = 0;
lpbi->biYPelsPerMeter = 0;
lpbi->biClrUsed = 0;
lpbi->biClrImportant = 0;
// get bitmap color table and bitmap data
GetDIBits(hBmpDC, hBmp, 0, lpbi->biHeight, (LPBYTE)lpbi + dwLen - dwSizeImage,
(LPBITMAPINFO)lpbi, DIB_RGB_COLORS);
GlobalUnlock(hClipObj);
SetClipboardData(CF_DIB, hClipObj);
// get number of entries in the logical palette
GetObject(hPalette,sizeof(WORD),&wBits);
// memory allocation for temporary palette data
if ((ppal = LocalAlloc(LPTR, sizeof(LOGPALETTE) + wBits * sizeof(PALETTEENTRY))) != NULL)
{
ppal->palVersion = PALVERSION;
ppal->palNumEntries = wBits;
GetPaletteEntries(hPalette, 0, wBits, ppal->palPalEntry);
SetClipboardData(CF_PALETTE, CreatePalette(ppal));
LocalFree(ppal);
}
}
DeleteDC(hBmpDC);
DeleteObject(hBmp);
#undef WIDTHBYTES
#undef PALVERSION
#else
HBITMAP hOldBmp, hBmp;
HDC hBmpDC;
_ASSERT(nLcdDoubled == 1 || nLcdDoubled == 2 || nLcdDoubled == 4);
hBmp = CreateBitmap(131*nLcdDoubled,64*nLcdDoubled,1,1,NULL);
hBmpDC = CreateCompatibleDC(NULL);
hOldBmp = (HBITMAP)SelectObject(hBmpDC,hBmp);
BitBlt(hBmpDC, 0, 0, 131*nLcdDoubled, 64*nLcdDoubled, hLcdDC, 0, 0, SRCCOPY);
SetClipboardData(CF_BITMAP,hBmp);
SelectObject(hBmpDC,hOldBmp);
DeleteDC(hBmpDC);
#endif
}
CloseClipboard();
}
return 0;
}
//
// ID_VIEW_RESET
//
static LRESULT OnViewReset()
{
if (nState != SM_RUN) return 0;
if (YesNoMessage(_T("Are you sure you want to press the Reset Button ?"))==IDYES)
{
SwitchToState(SM_SLEEP);
CpuReset(); // register setting after Cpu Reset
SwitchToState(SM_RUN);
}
return 0;
}
//
// ID_VIEW_SETTINGS
//
static LRESULT OnViewSettings()
{
ReadSettings();
// not in nState = SM_INVALID or port2 file must be closed from document
_ASSERT(nState != SM_INVALID || pbyPort2 == NULL);
if (DialogBox(hApp, MAKEINTRESOURCE(IDD_SETTINGS), hWnd, (DLGPROC)SettingsProc) == -1)
AbortMessage(_T("Settings Dialog Creation Error !"));
WriteSettings();
return 0;
}
//
// ID_VIEW_SCRIPT
//
static LRESULT OnViewScript()
{
BYTE cType = cCurrentRomType;
if (nState != SM_RUN)
{
InfoMessage(_T("You cannot change the KML script when Emu48 is not running.\n")
_T("Use the File,New menu item to create a new calculator."));
return 0;
}
SwitchToState(SM_INVALID);
retry:
if (!DisplayChooseKml(cType)) goto ok;
if (!InitKML(szCurrentKml,FALSE))
{
if (AbortMessage(_T("This KML Script has errors.\nPress Ok to try to find a correct script."))==IDCANCEL)
{
if (szCurrentFilename[0])
OnFileSave();
else
OnFileSaveAs();
goto ok;
}
goto retry;
}
ok:
if (pbyRom) SwitchToState(SM_RUN);
return 0;
}
//
// ID_BACKUP_SAVE
//
static LRESULT OnBackupSave()
{
UINT nOldState;
if (pbyRom == NULL) return 0;
nOldState = SwitchToState(SM_INVALID);
SaveBackup();
SwitchToState(nOldState);
return 0;
}
//
// ID_BACKUP_RESTORE
//
static LRESULT OnBackupRestore()
{
SwitchToState(SM_INVALID);
RestoreBackup();
if (pbyRom) SwitchToState(SM_RUN);
return 0;
}
//
// ID_BACKUP_DELETE
//
static LRESULT OnBackupDelete()
{
ResetBackup();
return 0;
}
//
// ID_OBJECT_LOAD
//
static LRESULT OnObjectLoad()
{
static BOOL bWarning = TRUE;
if (!Chipset.dispon && !bDbgEnable) // calculator off, turn on
{
// turn on HP
KeyboardEvent(TRUE,0,0x8000);
Sleep(200);
KeyboardEvent(FALSE,0,0x8000);
}
if (nState != SM_RUN)
{
InfoMessage(_T("The emulator must be running to load an object."));
return 0;
}
if (WaitForSleepState()) // wait for cpu SHUTDN then sleep state
{
InfoMessage(_T("The emulator is busy."));
return 0;
}
_ASSERT(nState == SM_SLEEP);
if (bWarning)
{
UINT uReply = YesNoCancelMessage(
_T("Warning: Trying to load an object while the emulator is busy\n")
_T("will certainly result in a memory lost. Before loading an object\n")
_T("you should be sure that the calculator is not doing anything.\n")
_T("Do you want to see this warning next time you try to load an object ?"));
switch (uReply)
{
case IDYES:
break;
case IDNO:
bWarning = FALSE;
break;
case IDCANCEL:
SwitchToState(SM_RUN);
return 0;
}
}
if (!GetLoadObjectFilename())
{
SwitchToState(SM_RUN);
return 0;
}
if (!LoadObject(szBufferFilename))
{
SwitchToState(SM_RUN);
return 0;
}
SwitchToState(SM_RUN); // run state
while (nState!=nNextState) Sleep(0);
_ASSERT(nState == SM_RUN);
KeyboardEvent(TRUE,0,0x8000);
Sleep(200);
KeyboardEvent(FALSE,0,0x8000);
while(Chipset.Shutdn == FALSE) Sleep(0);
return 0;
}
//
// ID_OBJECT_SAVE
//
static LRESULT OnObjectSave()
{
if (nState != SM_RUN)
{
InfoMessage(_T("The emulator must be running to save an object."));
return 0;
}
if (WaitForSleepState()) // wait for cpu SHUTDN then sleep state
{
InfoMessage(_T("The emulator is busy."));
return 0;
}
_ASSERT(nState == SM_SLEEP);
if (!GetSaveObjectFilename())
{
SwitchToState(SM_RUN);
return 0;
}
SaveObject(szBufferFilename);
SwitchToState(SM_RUN);
return 0;
}
//
// ID_TOOL_DISASM
//
static BOOL CALLBACK Disasm(HWND hDlg, UINT message, DWORD wParam, LONG lParam)
{
static DWORD dwAddress, dwAddressMax;
LONG i;
TCHAR *cpStop,szAddress[256] = _T("0");
switch (message)
{
case WM_INITDIALOG:
// set fonts & cursor
SendDlgItemMessage(hDlg,IDC_DISASM_MODULE,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_MAP,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_ROM,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_RAM,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_PORT1,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_PORT2,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_MAP,BM_SETCHECK,1,0);
SendDlgItemMessage(hDlg,IDC_ADDRESS,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_ADR,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_NEXT,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDC_DISASM_COPY,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SendDlgItemMessage(hDlg,IDCANCEL,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),MAKELPARAM(FALSE,0));
SetDlgItemText(hDlg,IDC_DISASM_ADR,szAddress);
disassembler_map = MEM_MAP; // disassemble with mapped modules
dwAddress = _tcstoul(szAddress,&cpStop,16);
dwAddressMax = 0x100000; // greatest address (mapped mode)
return TRUE;
case WM_COMMAND:
switch(wParam)
{
// decode radio buttons
case IDC_DISASM_MAP:
disassembler_map = MEM_MAP;
dwAddressMax = 0x100000;
return TRUE;
case IDC_DISASM_ROM:
disassembler_map = MEM_ROM;
dwAddressMax = dwRomSize;
return TRUE;
case IDC_DISASM_RAM:
disassembler_map = MEM_RAM;
dwAddressMax = Chipset.Port0Size * 2048;
return TRUE;
case IDC_DISASM_PORT1:
disassembler_map = MEM_PORT1;
dwAddressMax = ((Chipset.cards_status & PORT1_PRESENT) != 0) ? (Chipset.Port1Size * 2048) : 0;
return TRUE;
case IDC_DISASM_PORT2:
disassembler_map = MEM_PORT2;
dwAddressMax = (cCurrentRomType=='E' || cCurrentRomType=='X')
? (Chipset.Port2Size * 2048)
: ((dwPort2Mask != 0) ? ((dwPort2Mask + 1) << 18) : (dwPort2Size * 2048));
return TRUE;
case IDOK:
SendDlgItemMessage(hDlg,IDC_DISASM_ADR,EM_SETSEL,0,-1);
GetDlgItemText(hDlg,IDC_DISASM_ADR,szAddress,ARRAYSIZEOF(szAddress));
// test if valid hex address
for (i = 0; i < (LONG) lstrlen(szAddress); ++i)
{
if (_istxdigit(szAddress[i]) == FALSE)
return FALSE;
}
dwAddress = _tcstoul(szAddress,&cpStop,16);
// no break
case IDC_DISASM_NEXT:
if (dwAddress >= dwAddressMax)
return FALSE;
i = wsprintf(szAddress,(dwAddress <= 0xFFFFF) ? _T("%05lX ") : _T("%06lX "),dwAddress);
dwAddress = disassemble(dwAddress,&szAddress[i],VIEW_LONG);
i = SendDlgItemMessage(hDlg,IDC_DISASM_WIN,LB_ADDSTRING,0,(LPARAM) szAddress);
SendDlgItemMessage(hDlg,IDC_DISASM_WIN,LB_SELITEMRANGE,FALSE,MAKELPARAM(0,i));
SendDlgItemMessage(hDlg,IDC_DISASM_WIN,LB_SETSEL,TRUE,i);
SendDlgItemMessage(hDlg,IDC_DISASM_WIN,LB_SETTOPINDEX,i,0);
return TRUE;
case IDC_DISASM_COPY:
// copy selected items to clipboard
CopyItemsToClipboard(GetDlgItem(hDlg,IDC_DISASM_WIN));
return TRUE;
case IDCANCEL:
EndDialog(hDlg, wParam);
return TRUE;
}
break;
}
return FALSE;
UNREFERENCED_PARAMETER(lParam);
}
//
// ID_ABOUT
//
static BOOL CALLBACK About(HWND hDlg, UINT message, DWORD wParam, LONG lParam)
{
switch (message)
{
case WM_INITDIALOG:
SetDlgItemText(hDlg,IDC_VERSION,szNoTitle);
SetDlgItemText(hDlg,IDC_LICENSE,szLicence);
return TRUE;
case WM_COMMAND:
if ((wParam==IDOK)||(wParam==IDCANCEL))
{
EndDialog(hDlg, wParam);
return TRUE;
}
break;
}
return FALSE;
UNREFERENCED_PARAMETER(lParam);
}
static LRESULT OnToolDisasm() // disasm dialogbox call
{
if (pbyRom) SwitchToState(SM_SLEEP);
if (DialogBox(hApp, MAKEINTRESOURCE(IDD_DISASM), hWnd, (DLGPROC)Disasm) == -1)
AbortMessage(_T("Disassembler Dialog Box Creation Error !"));
if (pbyRom) SwitchToState(SM_RUN);
return 0;
}
static LRESULT OnAbout()
{
if (DialogBox(hApp, MAKEINTRESOURCE(IDD_ABOUT), hWnd, (DLGPROC)About) == -1)
AbortMessage(_T("About Dialog Box Creation Error !"));
return 0;
}
static LRESULT OnLButtonDown(UINT nFlags, WORD x, WORD y)
{
if (nState == SM_RUN) MouseButtonDownAt(nFlags, x,y);
return 0;
}
static LRESULT OnLButtonUp(UINT nFlags, WORD x, WORD y)
{
if (nState == SM_RUN) MouseButtonUpAt(nFlags, x,y);
return 0;
}
static LRESULT OnMouseMove(UINT nFlags, WORD x, WORD y)
{
if (nState == SM_RUN) MouseMovesTo(nFlags, x,y);
return 0;
}
static LRESULT OnKeyDown(int nVirtKey, DWORD lKeyData)
{
// call RunKey() only once (suppress autorepeat feature)
if (nState == SM_RUN && (lKeyData & 0x40000000) == 0)
RunKey((BYTE)nVirtKey, TRUE);
return 0;
}
static LRESULT OnKeyUp(int nVirtKey, DWORD lKeyData)
{
if (nState == SM_RUN) RunKey((BYTE)nVirtKey, FALSE);
return 0;
UNREFERENCED_PARAMETER(lKeyData);
}
LRESULT CALLBACK MainWndProc(HWND hWindow, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE: return OnCreate(hWindow);
case WM_DESTROY: return OnDestroy(hWindow);
case WM_PAINT: return OnPaint(hWindow);
case WM_DROPFILES: return OnDropFiles((HANDLE)wParam);
case WM_ACTIVATE:
if (LOWORD(wParam)==WA_INACTIVE) break;
case WM_QUERYNEWPALETTE:
if (hPalette)
{
SelectPalette(hWindowDC, hPalette, FALSE);
if (RealizePalette(hWindowDC))
{
InvalidateRect(hWindow,NULL,TRUE);
return TRUE;
}
}
return FALSE;
case WM_PALETTECHANGED:
if ((HWND)wParam == hWindow) break;
if (hPalette)
{
SelectPalette(hWindowDC, hPalette, FALSE);
if (RealizePalette(hWindowDC))
{
// UpdateColors(hWindowDC);
InvalidateRect (hWnd, (LPRECT) (NULL), 1);
}
}
return FALSE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case ID_FILE_NEW: return OnFileNew();
case ID_FILE_OPEN: return OnFileOpen();
case ID_FILE_SAVE: return OnFileSave();
case ID_FILE_SAVEAS: return OnFileSaveAs();
case ID_FILE_CLOSE: return OnFileClose();
case ID_FILE_EXIT: return OnFileExit();
case ID_STACK_COPY: return OnStackCopy();
case ID_STACK_PASTE: return OnStackPaste();
case ID_VIEW_COPY: return OnViewCopy();
case ID_VIEW_RESET: return OnViewReset();
case ID_VIEW_SETTINGS: return OnViewSettings();
case ID_VIEW_SCRIPT: return OnViewScript();
case ID_BACKUP_SAVE: return OnBackupSave();
case ID_BACKUP_RESTORE:return OnBackupRestore();
case ID_BACKUP_DELETE: return OnBackupDelete();
case ID_OBJECT_LOAD: return OnObjectLoad();
case ID_OBJECT_SAVE: return OnObjectSave();
case ID_TOOL_DISASM: return OnToolDisasm();
case ID_TOOL_DEBUG: return OnToolDebug();
case ID_ABOUT: return OnAbout();
}
break;
case WM_SYSCOMMAND:
switch (LOWORD(wParam))
{
case SC_CLOSE: return OnFileExit();
}
break;
case WM_RBUTTONDOWN:
case WM_LBUTTONDOWN: return OnLButtonDown(wParam, LOWORD(lParam), HIWORD(lParam));
case WM_LBUTTONUP: return OnLButtonUp(wParam, LOWORD(lParam), HIWORD(lParam));
case WM_MOUSEMOVE: return OnMouseMove(wParam, LOWORD(lParam), HIWORD(lParam));
case WM_KEYUP: return OnKeyUp((int)wParam, lParam);
case WM_KEYDOWN: return OnKeyDown((int)wParam, lParam);
}
return DefWindowProc(hWindow, uMsg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
WNDCLASS wc;
RECT rectWindow;
HSZ hszService, hszTopic; // variables for DDE server
DWORD dwAffMask;
hApp = hInst;
#if defined _UNICODE
{
ppArgv = CommandLineToArgvW(GetCommandLine(),&nArgc);
}
#else
{
nArgc = __argc; // no. of command line arguments
ppArgv = (LPCTSTR*) __argv; // command line arguments
}
#endif
wc.style = CS_BYTEALIGNCLIENT;
wc.lpfnWndProc = (WNDPROC)MainWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInst;
wc.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_EMU48));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU);
wc.lpszClassName = _T("CEmu48");
if (!RegisterClass(&wc))
{
AbortMessage(
_T("CEmu48 class registration failed.\n")
_T("This application will now terminate."));
return FALSE;
}
// Create window
rectWindow.left = 0;
rectWindow.top = 0;
rectWindow.right = 256;
rectWindow.bottom = 0;
AdjustWindowRect(&rectWindow, WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_OVERLAPPED, TRUE);
hWnd = CreateWindow(_T("CEmu48"), _T("Emu48"),
WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_OVERLAPPED,
CW_USEDEFAULT, CW_USEDEFAULT,
rectWindow.right - rectWindow.left,
rectWindow.bottom - rectWindow.top,
NULL,NULL,hApp,NULL
);
if (hWnd == NULL)
{
AbortMessage(_T("Window creation failed."));
return FALSE;
}
// initialization
QueryPerformanceFrequency(&lFreq); // init high resolution counter
QueryPerformanceCounter(&lAppStart);
GetCurrentDirectory(ARRAYSIZEOF(szCurrentDirectory), szCurrentDirectory);
ReadSettings();
UpdateWindowStatus();
// create auto event handle
hEventShutdn = CreateEvent(NULL,FALSE,FALSE,NULL);
if (hEventShutdn == NULL)
{
AbortMessage(_T("Event creation failed."));
DestroyWindow(hWnd);
return FALSE;
}
nState = SM_RUN; // init state must be <> nNextState
nNextState = SM_INVALID; // go into invalid state
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&WorkerThread, NULL, CREATE_SUSPENDED, &lThreadId);
if (hThread == NULL)
{
CloseHandle(hEventShutdn); // close event handle
AbortMessage(_T("Thread creation failed."));
DestroyWindow(hWnd);
return FALSE;
}
// on multiprocessor machines for QueryPerformanceCounter()
dwAffMask = SetThreadAffinityMask(hThread,1);
_ASSERT(dwAffMask != 0);
ResumeThread(hThread); // start thread
while (nState!=nNextState) Sleep(0); // wait for thread initialized
idDdeInst = 0; // initialize DDE server
if (DdeInitialize(&idDdeInst,(PFNCALLBACK) &DdeCallback,
APPCLASS_STANDARD |
CBF_FAIL_EXECUTES | CBF_FAIL_ADVISES |
CBF_SKIP_REGISTRATIONS | CBF_SKIP_UNREGISTRATIONS,0))
{
TerminateThread(hThread, 0); // kill emulation thread
CloseHandle(hEventShutdn); // close event handle
AbortMessage(_T("Could not initialize server!"));
DestroyWindow(hWnd);
return FALSE;
}
_ASSERT(hWnd != NULL);
_ASSERT(hWindowDC != NULL);
if (nArgc >= 2) // use decoded parameter line
{
TCHAR szTemp[256] = _T("Loading ");
lstrcat(szTemp, ppArgv[1]);
SetWindowTitle(szTemp);
if (OpenDocument(ppArgv[1]))
goto start;
}
ReadLastDocument(szBufferFilename, ARRAYSIZEOF(szBufferFilename));
if (szBufferFilename[0])
{
TCHAR szTemp[256] = _T("Loading ");
lstrcat(szTemp, szBufferFilename);
SetWindowTitle(szTemp);
if (OpenDocument(szBufferFilename))
goto start;
}
SetWindowTitle(_T("New Document"));
if (NewDocument())
{
SetWindowTitle(_T("Untitled"));
goto start;
}
ResetDocument();
start:
// init clipboard format and name service
uCF_HpObj = RegisterClipboardFormat(_T(CF_HPOBJ));
hszService = DdeCreateStringHandle(idDdeInst,szAppName,0);
hszTopic = DdeCreateStringHandle(idDdeInst,szTopic,0);
DdeNameService(idDdeInst,hszService,NULL,DNS_REGISTER);
ShowWindow(hWnd, nCmdShow);
if (pbyRom) SwitchToState(SM_RUN);
while (GetMessage(&msg, NULL, 0, 0))
{
if( (hDlgDebug == NULL || !IsDialogMessage(hDlgDebug, &msg))
&& (hDlgFind == NULL || !IsDialogMessage(hDlgFind, &msg)))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
SwitchToState(SM_RETURN); // exit emulation thread
// clean up DDE server
DdeNameService(idDdeInst, hszService, NULL, DNS_UNREGISTER);
DdeFreeStringHandle(idDdeInst, hszService);
DdeFreeStringHandle(idDdeInst, hszTopic);
DdeUninitialize(idDdeInst);
WriteSettings(); // save emulation settings
CloseHandle(hThread); // close thread handle
CloseHandle(hEventShutdn); // close event handle
_ASSERT(nState == SM_RETURN); // emulation thread down?
ResetDocument();
ResetBackup();
_ASSERT(pbyPort2 == NULL); // port2 file unmapped
_ASSERT(pKml == NULL); // KML script not closed
_ASSERT(szTitle == NULL); // freed allocated memory
_ASSERT(hPalette == NULL); // freed resource memory
return msg.wParam;
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(hPrevInst);
}