Example #1
0
//注册窗口类
BOOL CMainWnd::RegisterWnd(HINSTANCE hInst)
{
	WNDCLASS wc;//窗口类

	wc.hInstance = hInst;//所属实例
	wc.lpszClassName = ClsName;//窗口类名
	wc.lpfnWndProc = (WNDPROC)MainWndProc;//窗体回调函数的地址
	wc.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_ICON));//图标
	wc.lpszMenuName = NULL;//菜单名
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);//指针
	wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);//背景画刷
	wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;//窗体支持双击事件,水平、竖直方向大小改变时重绘窗口
	wc.cbWndExtra = 0;
	wc.cbClsExtra = 0;
	if (RegisterClass(&wc) == NULL)
	{
		ErrorBox("RegisterMainWindowClass failed");
		return FALSE;
	}
	return TRUE;
}
// creates as temp file, then spawns notepad with it...
//
bool SendStringToNotepad(LPCSTR psWhatever, LPCSTR psLocalFileName)
{
	bool bReturn = false;

	LPCSTR psOutputFileName = va("%s\\%s",scGetTempPath(),psLocalFileName);

	FILE *handle = fopen(psOutputFileName,"wt");
	if (handle)
	{
		fprintf(handle,psWhatever);
		fclose(handle);

		bReturn = SendFileToNotepad(psOutputFileName);
	}
	else
	{
		ErrorBox(va("Unable to create file \"%s\" for notepad to use!",psOutputFileName));
	}

	return bReturn;
}
Example #3
0
/******************************************************************************
 * BOOL  APIENTRY WidthProc(hDial, message, wParam, lParam)
 *
 * purpose: dialog function for Width menu function
 *
 * params:  same as for all dialog fns.
 *
 * side effects: changes Box width variable
 *
 *****************************************************************************/
BOOL  APIENTRY 
WidthProc(
	HWND   hDial,
	WORD   message,
	WPARAM wParam,
	LONG   lParam
	)
{
	INT i;
	BOOL fOk;

	UNREFERENCED_PARAMETER(lParam);

	switch (message) {
	default:
		return FALSE;
	case WM_INITDIALOG:
		SetDlgItemInt(hDial, BOX_WIDTH, newWidth, FALSE);
		break;

	case WM_COMMAND:
		switch (GET_WM_COMMAND_ID(wParam, lParam)) {
		case IDOK:
			fChanged = TRUE;
			i = GetDlgItemInt(hDial, BOX_WIDTH, (LPBOOL)&fOk, FALSE);
			if (fOk && i < wBoxLim)
				newWidth = i;
			else
				ErrorBox(hDial, vszWidthOutOfBounds);

		case IDCANCEL:
			EndDialog(hDial, GET_WM_COMMAND_ID(wParam, lParam) != IDCANCEL);
			break;

		default:
			break;
		}
	}
	return TRUE;
}
Example #4
0
bool CModDoc::ConvertSamplesToInstruments()
//-----------------------------------------
{
	const INSTRUMENTINDEX instrumentMax = m_SndFile.GetModSpecifications().instrumentsMax;
	if(GetNumInstruments() > 0 || instrumentMax == 0) return false;

	// If there is no actual sample data, don't bother creating any instruments
	bool anySamples = false;
	for(SAMPLEINDEX smp = 1; smp <= m_SndFile.m_nSamples; smp++)
	{
		if(m_SndFile.GetSample(smp).HasSampleData())
		{
			anySamples = true;
			break;
		}
	}
	if(!anySamples) return true;

	m_SndFile.m_nInstruments = std::min(m_SndFile.GetNumSamples(), instrumentMax);
	for(SAMPLEINDEX smp = 1; smp <= m_SndFile.m_nInstruments; smp++)
	{
		const bool muted = IsSampleMuted(smp);
		MuteSample(smp, false);

		ModInstrument *instrument = m_SndFile.AllocateInstrument(smp, smp);
		if(instrument == nullptr)
		{
			ErrorBox(IDS_ERR_OUTOFMEMORY, CMainFrame::GetMainFrame());
			return false;
		}

		InitializeInstrument(instrument);
		mpt::String::Copy(instrument->name, m_SndFile.m_szNames[smp]);
		MuteInstrument(smp, muted);
	}

	return true;

}
Example #5
0
void SearchOk(HWND hDlg)
{	INT  ErrNo = 0;
	HWND hSearchButton, hFocus;
	BOOL OldSuppress = SuppressStatusBeep;

	SuppressStatusBeep = TRUE;
	hFocus = GetFocus();
	EnableWindow(hSearchButton = GetDlgItem(hDlg, IDOK), FALSE);
	if (SetupSearchString(hDlg, &ErrNo)) {
		if (!MatchValid) ErrNo = SearchErrNo;
		else if (!SearchAgain(0)) ErrNo = 238;
	}
	SuppressStatusBeep = OldSuppress;
	EnableWindow(hSearchButton, TRUE);
	if (hFocus == hSearchButton) SetFocus(hSearchButton);
	if (!ErrNo) {
		extern void HorizontalScrollIntoView(void);

		if (!ReplaceOpen) {
			if (!ViewOnlyFlag)
				EnableWindow(GetDlgItem(hDlg, IDC_SHOWREPLACE), TRUE);
		} else {
			EnableWindow(GetDlgItem(hDlg, IDC_REPLACE), TRUE);
			SendMessage(hDlg, DM_SETDEFID, IDC_REPLACE, 0);
			SendDlgItemMessage(hDlg, IDOK, BM_SETSTYLE,
							   (WPARAM)BS_PUSHBUTTON, TRUE);
		}
		/*main window does not have the focus...*/
		HorizontalScrollIntoView();
	} else {
		if (ReplaceOpen)
			 EnableWindow(GetDlgItem(hDlg, IDC_REPLACE),	 FALSE);
		else EnableWindow(GetDlgItem(hDlg, IDC_SHOWREPLACE), FALSE);
		hwndErrorParent = hDlg;			/*change parent of message box*/
		ErrorBox(ErrNo==216 || ErrNo==217 ? MB_ICONINFORMATION : MB_ICONSTOP,
				 ErrNo);
		hwndErrorParent = hwndMain;		/*reset to normal value*/
	}
}
Example #6
0
/**
 * PlaySnd - 播放音效
 * @tag:	音效标签
 */
bool CNoGo::PlaySnd(int tag)
{
	char filename[MAX_PATH] = { 0 };

	switch (tag)
	{
	case 0://落子音效
		strcpy(filename, LibPath);
		strcat(filename, "\\wav\\落子.wav");
		break;
	default:
		break;
	}

	//播放音效
	if (!PlaySound(filename, NULL, SND_NOWAIT | SND_FILENAME))
	{
		ErrorBox("PlaySound failed");
		return false;
	}

	return true;
}
Example #7
0
/***启动线程***/
HANDLE CThread::StartThread(
	LPTHREAD_START_ROUTINE lpStartAddress,
	LPVOID lpParameter,
	LPSECURITY_ATTRIBUTES lpThreadAttributes,
	DWORD dwStackSize,
	DWORD dwCreationFlags,
	LPDWORD lpThreadId
	)
{
	hThread = CreateThread(
		lpThreadAttributes,
		dwStackSize,
		lpStartAddress,
		lpParameter,
		dwCreationFlags,
		lpThreadId
		);
	if (hThread == NULL)
	{
		ErrorBox("CreateThread failed");
	}
	return hThread;
}
Example #8
0
bool Hook_CL_Disconnect()
{
	static bool firstRun = true;
	static bool firstResult = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	LONG error = NO_ERROR;

	g_Old_CL_Disconnect = (CL_Disconnect_t)AFXADDR_GET(CL_Disconnect);

	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourAttach(&(PVOID&)g_Old_CL_Disconnect, New_CL_Disconnect);
	error = DetourTransactionCommit();

	if (NO_ERROR != error)
	{
		firstResult = false;
		ErrorBox("Interception failed:\nhw.dll:CL_Disconnect");
	}

	return firstResult;
}
Example #9
0
/* basically just allocate memory for buffers and tables, and then
   call Steve B.'s decoder */
short gif_decoder(short linewidth)
{
	unsigned char far *buf, far * stack, far * suffix;
	unsigned short far *prefix;
	short ret;

	ret = OUT_OF_MEMORY;
	stack = suffix = (unsigned char *) prefix = NULL;
	safe_alloc = 1;
	if ((buf = farmalloc(linewidth + 1)) == NULL)
		goto OUT;
	safe_alloc = 1;
	if ((stack = farmalloc(MAX_CODES + 1)) == NULL)
		goto OUT;
	safe_alloc = 1;
	if ((suffix = farmalloc(MAX_CODES + 1)) == NULL)
		goto OUT;
	safe_alloc = 1;
	if ((prefix = (unsigned short far *) farmalloc((MAX_CODES + 1) * sizeof(unsigned short))) == NULL)
		goto OUT;
	ret = decoder(linewidth, buf, stack, suffix, prefix);
OUT:
	if (buf)
		farfree(buf);
	if (stack)
		farfree(stack);
	if (prefix)
		farfree(prefix);
	if (suffix)
		farfree(suffix);

	if (ret == OUT_OF_MEMORY)
		ErrorBox("Not enough memory to view a Gif file.");

	return (ret);
}
Example #10
0
//创建窗口
BOOL CMainWnd::CreateWnd(HWND hParentWnd, HMENU hMenu)
{
	DWORD WndStyle;//窗口风格

	/*窗体样式*/
	WndStyle = WS_VISIBLE |
		WS_OVERLAPPED |
		WS_CAPTION |
		WS_SYSMENU |
		WS_MAXIMIZEBOX |
		WS_MINIMIZEBOX |
		WS_SIZEBOX |
		WS_CLIPCHILDREN |//Excludes the area occupied by child windows when drawing occurs within the parent window.父子窗体之间不会因为重叠而绘制混乱
		WS_CLIPSIBLINGS;//Excludes the area occupied by child windows when drawing occurs within another child window.子窗体之间不会因为重叠而绘制混乱	

	hWnd = CreateWindow(
		ClsName,//Class name
		WndName,//Window name		
		WndStyle,//WndStyle
		CW_USEDEFAULT, 0,//Default position
		CW_USEDEFAULT, 0,//Default size
		(HWND)hParentWnd,//No parent window		
		hMenu,//Main menu
		hInst,//Application instance
		NULL//Do not create MDI client window
		);
	if (hWnd == NULL)
	{
		ErrorBox("CreateMainWindow failed");
		return FALSE;
	}

	ShowWindow(hWnd, SW_SHOW);
	UpdateWindow(hWnd);
	return TRUE;
}
Example #11
0
static bool LoadAnimationCFG(LPCSTR psFullPath, ModelContainer_t *pContainer, FILE *handle)//, HDC hDC)	// hDC for text metrics
{
//	int  iLongestTextMetric = 0;
//	SIZE Size;
	bool bOk = false;	

//	FILE *handle = fopen(psFullPath,"rt");

	if (handle)
	{
		static char sLineBuffer[2048];

		int iFirstFrameAfterBoth = -1;	// stuff I need to do for ID's non-folded frame numbers
		int iFirstFrameAfterTorso= -1;

		while (1)
		{
			ZEROMEM(sLineBuffer);
			if (!fgets(sLineBuffer,sizeof(sLineBuffer),handle))
			{
				if (ferror(handle))
				{
					ErrorBox(va("Error while reading \"%s\"!",psFullPath));
//					ClearAnimationCFG();
				}
				break;	// whether error or EOF
			}

			char sComment[2048] = {0};	// keep comments now because of the way ID cfg files work

			// zap any comments...
			//
			char *p = strstr(sLineBuffer,"//");
			if (p)
			{
				strcpy(sComment,p+2);
				*p=0;
			}

			// update, to read ID cfg files, we need to skip over some stuff that Raven ones don't have...
			//
			// our cfg files don't have "sex" (how depressingly apt...)
			//
			if (strnicmp(sLineBuffer,"sex",3)==0)
				continue;
			//
			// or this other crap either...
			//
			if (strnicmp(sLineBuffer,"footsteps",9)==0)
				continue;
			if (strnicmp(sLineBuffer,"headoffset",10)==0)
				continue;
			if (strnicmp(sLineBuffer,"soundpath",9)==0)
				continue;

			Sequence_t seq;
			memset(&seq,0,sizeof(seq));

			char sLine[2048];
			int iElementsDone = sscanf( sLineBuffer, "%s %d %d %d %d", &sLine, &seq.iStartFrame, &seq.iFrameCount, &seq.iLoopFrame, &seq.iFPS );
			if (iElementsDone == EOF)
				continue;	// probably skipping over a comment line

			bool bElementsScannedOk = false;

			if (iElementsDone == 5)
			{
				// then it must be a Raven line...
				//
				bElementsScannedOk = true;
//				mdview.bAnimIsMultiPlayerFormat = false;
			}
			else
			{
				// try scanning it as an ID line...
				//
				iElementsDone = sscanf( sLineBuffer, "%d %d %d %d", &seq.iStartFrame, &seq.iFrameCount, &seq.iLoopFrame, &seq.iFPS );
				if (iElementsDone == 4)
				{
//					mdview.bAnimIsMultiPlayerFormat = true;
					// scanned an ID line in ok, now convert it to Raven format...
					//
					iElementsDone = sscanf( sComment, "%s", &sLine );	// grab anim name from original saved comment
					if (iElementsDone == 1)
					{
						// ... and convert their loop format to ours...
						//
						if (seq.iLoopFrame == 0)
						{
							seq.iLoopFrame = -1;
						}
						else
						{
							seq.iLoopFrame = seq.iFrameCount - seq.iLoopFrame;
						}


						// now do the folding number stuff since ID don't do it in their files...
						//
						if ( !strnicmp(sLine,"TORSO_",6) && iFirstFrameAfterBoth == -1)
						{
							iFirstFrameAfterBoth = seq.iStartFrame;
						}
						if ( !strnicmp(sLine,"LEGS_",5))
						{
							if (iFirstFrameAfterTorso == -1)
							{
								iFirstFrameAfterTorso = seq.iStartFrame;
							}

							// now correct the leg framenumber...
							//
							if (iFirstFrameAfterBoth != -1)	// if it did, then there'd be no torso frames, so no adj nec.
							{
								seq.iStartFrame -= (iFirstFrameAfterTorso - iFirstFrameAfterBoth);
							}
						}

						bElementsScannedOk = true;
					}
				}
			}

			if (bElementsScannedOk)
			{	
				strcpy(seq.sName,sLine);//seq.sName = sLine;

				pContainer->SequenceList.push_back(seq);

				//
				// this line seems to be ok...
				//
//				OutputDebugString(va("%s  %d %d %d %d\n",seq.sName.c_str(), seq.iStartFrame, seq.iFrameCount, seq.iLoopFrame, seq.iFrameSpeed ));


				// "both" or "torso" get added to 'upper' menu...
				//
/*				if ( (!strnicmp(seq.sName.c_str(),"BOTH_",5)) || (!strnicmp(seq.sName.c_str(),"TORSO_",6)) )
				{
					Sequences_UpperAnims.push_back(seq);
					if (iAnimLockLongestString < strlen(seq.sName.c_str()))
						iAnimLockLongestString = strlen(seq.sName.c_str());

					if (GetTextExtentPoint(	hDC,						// HDC hdc,           // handle to device context
											seq.sName.c_str(),			// LPCTSTR lpString,  // pointer to text string
											strlen(seq.sName.c_str()),	// int cbString,      // number of characters in string
											&Size						// LPSIZE lpSize      // pointer to structure for string size
											)
						)
					{
						if (iLongestTextMetric < Size.cx)
							iLongestTextMetric = Size.cx;
					}

//					Menu_UpperAnims_AddItem(seq.sName.c_str());					
				}

				// "both" or "legs" get added to 'lower' menu...
				//
				if ( (!strnicmp(seq.sName.c_str(),"BOTH_",5)) || (!strnicmp(seq.sName.c_str(),"LEGS_",5)) )
				{
					Sequences_LowerAnims.push_back(seq);
					if (iAnimLockLongestString < strlen(seq.sName.c_str()))
						iAnimLockLongestString = strlen(seq.sName.c_str());

					if (GetTextExtentPoint(	hDC,						// HDC hdc,           // handle to device context
											seq.sName.c_str(),			// LPCTSTR lpString,  // pointer to text string
											strlen(seq.sName.c_str()),	// int cbString,      // number of characters in string
											&Size						// LPSIZE lpSize      // pointer to structure for string size
											)
						)
					{
						if (iLongestTextMetric < Size.cx)
							iLongestTextMetric = Size.cx;
					}
 
//					Menu_LowerAnims_AddItem(seq.sName.c_str());
				}
*/
			}
			else
			{
				// so do we report this as an error or what?
				//
				ErrorBox(sLineBuffer);
			}
		}

		fclose(handle);
/*
		// now add to menus... (this code is awful, it was simple at first then mutated with feature-add)
		//
		char sLine[2048];
		vector< Sequence_t >::iterator it;
		for (it=Sequences_UpperAnims.begin(); it!=Sequences_UpperAnims.end(); it++)
		{
			sprintf(sLine,(*it).sName.c_str());

			while (1)
			{
				GetTextExtentPoint(	hDC,			// HDC hdc,           // handle to device context
									sLine,			// LPCTSTR lpString,  // pointer to text string
									strlen(sLine),	// int cbString,      // number of characters in string
									&Size			// LPSIZE lpSize      // pointer to structure for string size
									);
				if (Size.cx >= iLongestTextMetric)
					break;

				strcat(sLine," ");
			}

			Menu_UpperAnims_AddItem(va("%s (%d...%d)%s",sLine,(*it).iStartFrame,((*it).iStartFrame+(*it).iFrameCount)-1,((*it).iLoopFrame==-1)?"":va("  Loop %d",(*it).iStartFrame+(*it).iLoopFrame)));
		}

		for (it=Sequences_LowerAnims.begin(); it!=Sequences_LowerAnims.end(); it++)
		{
			sprintf(sLine,(*it).sName.c_str());

			while (1)
			{
				GetTextExtentPoint(	hDC,			// HDC hdc,           // handle to device context
									sLine,			// LPCTSTR lpString,  // pointer to text string
									strlen(sLine),	// int cbString,      // number of characters in string
									&Size			// LPSIZE lpSize      // pointer to structure for string size
									);
				if (Size.cx >= iLongestTextMetric)
					break;

				strcat(sLine," ");
			}

			Menu_LowerAnims_AddItem(va("%s (%d...%d)%s",sLine,(*it).iStartFrame,((*it).iStartFrame+(*it).iFrameCount)-1,((*it).iLoopFrame==-1)?"":va("  Loop %d",(*it).iStartFrame+(*it).iLoopFrame)));
		}
  */

		/*
		// a bit of sanity checking, to cope with something Bob tried to do...   :-)
		//
		Sequence_t* pSeq = NULL;
		gl_model* pModel;		
		
		if ((pModel = pModel_Lower)!=0)
		{
			pSeq = Animation_GetLowerSequence(Animation_GetNumLowerSequences()-1);
			ReportFrameMismatches(pSeq,pModel);
		}

		if ((pModel = pModel_Upper)!=0)
		{
			pSeq = Animation_GetUpperSequence(Animation_GetNumUpperSequences()-1);
			ReportFrameMismatches(pSeq,pModel);
		}
		*/
	}

	//return bOk;
	return !!(pContainer->SequenceList.size());
}
Example #12
0
// looks a lot like Dave's :-)
bool GLPort::Initialize()
{
    PIXELFORMATDESCRIPTOR pfd;
    int npf;

    // need the DC later
    HDC dc = GetDC(MainForm->pnlView->Handle);

    // this is what we want who knows what we get
    memset(&pfd, 0, sizeof pfd);
    pfd.nSize      = sizeof pfd;
    pfd.nVersion   = 1;
    pfd.dwFlags    = /*PFD_SUPPORT_GDI|*/PFD_SUPPORT_OPENGL|
                                         PFD_DOUBLEBUFFER|PFD_DRAW_TO_WINDOW;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 16;
    pfd.iLayerType = PFD_MAIN_PLANE;

    // set the pixel format for the window
    npf = ChoosePixelFormat(dc, &pfd);
    SetPixelFormat(dc, npf, &pfd);
    DescribePixelFormat(dc, npf, sizeof pfd, &pfd);
    if (pfd.dwFlags & PFD_NEED_PALETTE)
    {
        ErrorMsg("Segeltuch does not yet support 8-bit video modes.\n\n"
                 "Please increase your video depth to atleast 16-bit.");
        //return false;
        //for now, we allow the program to continue even though the
        //display will be very ugly....
    }
    if (!(pfd.dwFlags & PFD_DOUBLEBUFFER))
    {
        ErrorMsg("No available double buffering support.");
    }
    InfoMsg("Found graphics card with %d-bits of color resolution and a %d-bit depth buffer.",
            pfd.cColorBits, pfd.cDepthBits);

    // create the OpenGL interface
    hRC = wglCreateContext(dc);
    if (hRC == NULL)
    {
        ErrorBox("Unable to create OpenGL renderring context.");
        return false;
    }

    // start her up
    Activate();
    ResetCamera();

    // no more
    MainForm->pnlView->EraseBack = false;
    // Clear the screen initially
    glClearColor(ColBck.r, ColBck.g, ColBck.b, ColBck.a);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    SwapBuffers(dc);

    // setup the new window
    ResetSize(false);

    // Our options
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CCW);
    glAlphaFunc(GL_GREATER, 0.5);
    glDisable(GL_ALPHA_TEST);

    // Utility Object
    qobj = gluNewQuadric();

    // clean up our stuff
    Deactivate();

    return (Created=true);
}
Example #13
0
void CMobileOpalDlg::InitialiseOPAL()
{
  /////////////////////////////////////////////////////////////////////
  // Start up and initialise OPAL

  if (m_opal == NULL) {
    m_opal = OpalInitialise(&m_opalVersion, "pc h323 sip " TRACE_OPTIONS);
    if (m_opal == NULL) {
      ErrorBox(IDS_INIT_FAIL);
      EndDialog(IDCANCEL);
      return;
    }
  }

  OpalMessage command;
  OpalMessage * response;

  // SIP registrar un-regisration
  CStringA strAOR = GetOptionStringA(RegistrarAorKey);
  CStringA strHost = GetOptionStringA(RegistrarHostKey);
  if (!m_currentAOR.IsEmpty() && (m_currentAOR != strAOR || m_currentHost != strHost)) {
    // Registration changed, so unregister the previous name
    memset(&command, 0, sizeof(command));
    command.m_type = OpalCmdRegistration;
    command.m_param.m_registrationInfo.m_protocol = "sip";
    command.m_param.m_registrationInfo.m_identifier = m_currentAOR;
    command.m_param.m_registrationInfo.m_hostName = m_currentHost;
    response = OpalSendMessage(m_opal, &command);
    if (response != NULL && response->m_type == OpalCmdRegistration) {
      OpalFreeMessage(response);

      UpdateWindow();

      // Wait for unregister to complete.
      while ((response = OpalGetMessage(m_opal, 30000)) != NULL) {
        HandleMessage(*response);
        if (response->m_type == OpalIndRegistration && response->m_param.m_registrationStatus.m_status == OpalRegisterRemoved)
          break;
      }
    }
    OpalFreeMessage(response);
    m_currentAOR.Empty();
    m_currentHost.Empty();
  }

  /* Calucalte some configuration strings, determine position of a QCIF
     window so is in bottom left corner, and a preview window for camera
     in lower right corner, scaled to fit remaining space. */
  static const unsigned videoWidth = 176;
  static const unsigned videoHeight = 144;
  CRect box;
  GetClientRect(&box);

  CRect commandBox;
  m_dlgCommandBar.GetWindowRect(&commandBox);
  box.bottom -= commandBox.Height();

  CStringA strVideoOutputDevice;
  strVideoOutputDevice.Format("MSWIN STYLE=0x%08X PARENT=0x%08X X=%i Y=%i WIDTH=%u HEIGHT=%u",
                              WS_CHILD|WS_BORDER, GetSafeHwnd(),
                              0, box.Height()-videoHeight,
                              videoWidth, videoHeight);

  unsigned previewWidth = box.Width() - videoWidth - 2;
  unsigned previewHeight = previewWidth*videoHeight/videoWidth;
  CStringA strVideoPreviewDevice;
  strVideoPreviewDevice.Format("MSWIN STYLE=0x%08X PARENT=0x%08X X=%i Y=%i WIDTH=%u HEIGHT=%u",
                               WS_CHILD|WS_BORDER, GetSafeHwnd(),
                               videoWidth+2, box.Height()-previewHeight,
                               previewWidth, previewHeight);

  CStringA strMediaOptions;
  strMediaOptions.Format("Video:Max Bit Rate=128000\n"
                         "Video:Target Bit Rate=128000\n"
                         "Video:Frame Time=9000\n" // 10 frames/second
                         "Video:Frame Width=%u\n"
                         "Video:Frame Height=%u\n"
                         "Video:Max Rx Frame Width=%u\n"
                         "Video:Max Rx Frame Height=%u\n"
                         "H.264:Level=1b\n",
                          videoWidth, videoHeight,
                          videoWidth, videoHeight);

  // General options
  memset(&command, 0, sizeof(command));
  command.m_type = OpalCmdSetGeneralParameters;

  CStringA strStunServer = GetOptionStringA(STUNServerKey);
  command.m_param.m_general.m_stunServer = strStunServer;
  command.m_param.m_general.m_audioPlayerDevice = "Audio Output";
  command.m_param.m_general.m_audioRecordDevice = "Audio Input";
  command.m_param.m_general.m_videoInputDevice = "CAM1:";
  command.m_param.m_general.m_videoOutputDevice = strVideoOutputDevice;
  command.m_param.m_general.m_videoPreviewDevice = strVideoPreviewDevice;
  command.m_param.m_general.m_mediaMask = "RFC4175*\nMPEG4";
  command.m_param.m_general.m_mediaOptions = strMediaOptions;
  command.m_param.m_general.m_autoTxMedia = GetOptionInt(AutoStartTxVideoKey, true) != 0 ? "audio video" : "audio";
  command.m_param.m_general.m_rtpMaxPayloadSize = 1400;

  if ((response = OpalSendMessage(m_opal, &command)) == NULL || response->m_type == OpalIndCommandError)
    ErrorBox(IDS_CONFIGURATION_FAIL, response);
  OpalFreeMessage(response);

  // Options across all protocols
  memset(&command, 0, sizeof(command));
  command.m_type = OpalCmdSetProtocolParameters;

  CStringA strUserName = GetOptionStringA(UserNameKey);
  command.m_param.m_protocol.m_userName = strUserName;

  CStringA strDisplayName = GetOptionStringA(UserNameKey);
  command.m_param.m_protocol.m_displayName = strDisplayName;

  CStringA interfaceAddress = GetOptionStringA(InterfaceAddressKey, L"*");
  command.m_param.m_protocol.m_interfaceAddresses = interfaceAddress;

  if ((response = OpalSendMessage(m_opal, &command)) == NULL || response->m_type == OpalIndCommandError)
    ErrorBox(IDS_LISTEN_FAIL, response);
  OpalFreeMessage(response);

  // H.323 gatekeeper registration
  memset(&command, 0, sizeof(command));
  command.m_type = OpalCmdRegistration;

  UINT gkType = GetOptionInt(GkTypeKey);
  if (gkType > 0) {
    command.m_param.m_registrationInfo.m_protocol = "h323";

    CStringA strAliasName = GetOptionStringA(GkAliasKey);
    command.m_param.m_registrationInfo.m_identifier = strAliasName;

    CStringA strGkId = GetOptionStringA(GkIdKey);
    command.m_param.m_registrationInfo.m_adminEntity = strGkId;

    CStringA strGkHost = GetOptionStringA(GkHostKey);
    command.m_param.m_registrationInfo.m_hostName = strGkHost;

    CStringA strGkAuthUser = GetOptionStringA(GkAuthUserKey);
    command.m_param.m_registrationInfo.m_authUserName = strGkAuthUser;

    CStringA strGkPassword = GetOptionStringA(GkPasswordKey);
    command.m_param.m_registrationInfo.m_password = strGkPassword;

    SetStatusText(IDS_REGISTERING);
    if ((response = OpalSendMessage(m_opal, &command)) == NULL || response->m_type == OpalIndCommandError)
      ErrorBox(IDS_REGISTRATION_FAIL, response);
    OpalFreeMessage(response);
  }

  // SIP registrar registration
  if (strAOR.IsEmpty())
    SetStatusText(IDS_READY);
  else {
    memset(&command, 0, sizeof(command));
    command.m_type = OpalCmdRegistration;

    command.m_param.m_registrationInfo.m_protocol = "sip";

    command.m_param.m_registrationInfo.m_identifier = strAOR;
    command.m_param.m_registrationInfo.m_hostName = strHost;

    CStringA strAuthUser = GetOptionStringA(RegistrarUserKey);
    command.m_param.m_registrationInfo.m_authUserName = strAuthUser;

    CStringA strPassword = GetOptionStringA(RegistrarPassKey);
    command.m_param.m_registrationInfo.m_password = strPassword;

    CStringA strRealm = GetOptionStringA(RegistrarRealmKey);
    command.m_param.m_registrationInfo.m_adminEntity = strRealm;

    command.m_param.m_registrationInfo.m_timeToLive = 300;

    SetStatusText(IDS_REGISTERING);
    if ((response = OpalSendMessage(m_opal, &command)) != NULL && response->m_type != OpalIndCommandError) {
      m_currentAOR = strAOR;
      m_currentHost = strHost;
    }
    else {
      ErrorBox(IDS_REGISTRATION_FAIL, response);
      SetStatusText(IDS_READY);
    }
    OpalFreeMessage(response);
  }

  PowerPolicyNotify(PPN_UNATTENDEDMODE, TRUE);
}
Example #14
0
BOOL FAR  MergeFile(LPSTR FileName, int view)
{
    HCURSOR hSaveCursor;
    char line[MAX_USER_LINE + 1];
    int offset; //Current offset of storage in block
    int lineLen; // length of line
    BYTE prevLength; //Previous line size
    LPVIEWREC v = &Views[view];
    WORD res;
    LPDOCREC d =&Docs[v->Doc];
    LPLINEREC pCurLine, pLastLine;
    LPBLOCKDEF pCurBlock, pNewBlock;
    long y;

    Assert( v->Doc >= 0);


    if ((hFileDoc = _lopen(FileName, OF_READ)) == HFILE_ERROR)
          return ErrorBox(ERR_File_Open, (LPSTR)FileName);

    if ((pszBufferDoc = DocAlloc(DISK_BLOCK_SIZE)) == NULL) {
        ErrorBox(SYS_Allocate_Memory);
        goto error1;
    }

    dwBytesReadDoc = DISK_BLOCK_SIZE;
    dwOffsetDoc = DISK_BLOCK_SIZE;
    lineLen = 0;

    //Delete selected text if any
    if (v->BlockStatus) {

        long XR, YR;

        GetBlockCoord (view, &(v->X), &(v->Y), &XR, &YR);
        DeleteStream(view, v->X, v->Y, XR, YR, FALSE);
    }

    //Set the Hour glass cursor
          hSaveCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));

    //Insert first line

    res = LoadLine(line, &lineLen, d->NbLines);
    if (res == END_OF_FILE || res == END_OF_LINE) {

        //Add a CR+LF
        if (res == END_OF_LINE) {
            line[lineLen] = CR;
            line[lineLen + 1] = LF;
            lineLen += 2;
        }
        if (!InsertBlock(v->Doc, v->X, v->Y, (WORD) lineLen, line))
            goto error2;
    }
    else {

        if (res == ERR_File_Read || res == ERR_Not_A_Text_File)
              ErrorBox(res, (LPSTR)FileName);
        goto error2;
    }

    if (res != END_OF_FILE) {

        //Get current line status (we just inserted it)

        y = v->Y;
        if (!FirstLine(v->Doc, &pCurLine, &y, &pCurBlock))
              return FALSE;

        //Get next line (just after the line we just inserted)

        if (!NextLine(v->Doc, &pCurLine, &y, &pCurBlock))
              return FALSE;

        //Set offset to StoreLine start
              offset =  (LPSTR)pCurLine - (LPSTR)pCurBlock->Data;
        prevLength = pCurLine->PrevLength;

        //Split block in 2 blocks by first allocating a new block and then
        //copying right side of block in new block

        if (!AllocateBlock(pCurBlock, pCurBlock->NextBlock, &pNewBlock))
              return FALSE;

        pLastLine = (LPLINEREC)(pCurBlock->Data + pCurBlock->LastLineOffset);
        memmove(pNewBlock->Data, (LPSTR)pCurLine,
              (LPSTR)pLastLine - (LPSTR)pCurLine + pLastLine->Length);

        //Set new old block len and new new block len
              pCurBlock->LastLineOffset = (LPSTR)pCurLine - (LPSTR)pCurBlock->Data - pCurLine->PrevLength;
        pNewBlock->LastLineOffset = (LPSTR)pLastLine - (LPSTR)pCurLine;

        //Backward links next block with new one
        if (pCurBlock->NextBlock == NULL)
              d->LastBlock = pNewBlock;
        else
              (pCurBlock->NextBlock)->PrevBlock = pNewBlock;

        //Forward link current block with new block

        pCurBlock->NextBlock = pNewBlock;

        CloseLine(v->Doc, &pCurLine, y, &pCurBlock);

        //Read and store all lines in new blocks

        res = LoadLine(line, &lineLen, d->NbLines);
        while (res == END_OF_LINE) {

            //Truncate a file too large

            if (d->NbLines >= MAX_LINE_NUMBER - 1) {
                ErrorBox(ERR_Truncate_Doc);
                res = END_OF_FILE;
                break;
            }

            if (!StoreLine(line, lineLen, &offset, &prevLength, &pCurBlock)) {
                res = END_ABORT;
                break;
            }

            res = LoadLine(line, &lineLen, ++d->NbLines);
        }

        //Take decisions
        switch (res) {

          case END_OF_FILE:

            //Store last line
            if (StoreLine(line, lineLen, &offset, &prevLength, &pCurBlock)) {

                d->NbLines++;

                //Forward link of last allocated block with new block

                pCurBlock->NextBlock = pNewBlock;

                //Backward link of new block with last allocated block

                pNewBlock->PrevBlock = pCurBlock;
                ((LPLINEREC)(pNewBlock->Data))->PrevLength = (BYTE)(lineLen + LHD);

                //Free memory

                if (!DocFree(pszBufferDoc))
                      InternalErrorBox(SYS_Free_Memory);

                //Restore cursor

                SetCursor(hSaveCursor);

                //Check syntax if C

                if (d->language == C_LANGUAGE) {
                    d->lineTop = 0;
                    d->lineBottom = d->NbLines;
                    CheckSyntax(v->Doc);
                }
                SetVerticalScrollBar(view, TRUE);

                PosXY(view, v->X, v->Y, FALSE);
                InvalidateRect(v->hwndClient, (LPRECT)NULL, FALSE);

                CloseHandle (hFileDoc);
                return TRUE;
            }
            else
                goto abort;

          case ERR_File_Read:
          case ERR_Not_A_Text_File:
            ErrorBox(res, (LPSTR)FileName);
            //Fall through

          case END_ABORT:
            {

              abort:
                SetCursor(hSaveCursor);
                break;
            }

          default:
            Assert(FALSE);
            break;
        }

    } else
          InvalidateRect(v->hwndClient, (LPRECT)NULL, FALSE);

  error2: {
        SetCursor (hSaveCursor);
        if (!DocFree(pszBufferDoc))
              InternalErrorBox(SYS_Free_Memory);
    }

  error1: {
        CloseHandle (hFileDoc);
    }

    return FALSE;
}                                       /* MergeFile() */
Example #15
0
int 
OpenDocument(
    WORD    mode,
    WORD    type,
    int     doc,
    LPSTR   FileName,
    int     dupView,
    int     Preference,
    BOOL    bUserActivated
    )

/*++

Routine Description:

    This routine is used to create a new document or to duplicate
    the view of an existing document.

Arguments:

    mode        - Supplies MODE_DUPLICATE if the document is to be duplicated
                           MODE_RELOAD if the file is to be reloaded
                           MODE_CREATE if the document is to be created
    type        - Supplies the document type
    doc         - Supplies
    FileName    - Supplies a pointer to the name of the file for the document
    dupView     - Supplies the view to be duplicated (mode == MODE_DUPLICATE)
    Preference  - Supplies the view preference (-1 if none)
    bUserActivated - Indicates whether this action was initiated by the
                user or by windbg. The value is to determine the Z order of
                any windows that are opened.

Return Value:

    -1 on failure
    view number on success (>= 0)
    return-value - Description of conditions needed to return value. - or -

--*/

{
    LPLINEREC   pl;
    int         nView = 0;
    BOOL        create;
    int         n;
    int         language;
    LPDOCREC    d;
    LPVIEWREC   views;

    //
    //  In mode duplicate, we create a new nView being a copy of the previous
    //  nView of the same document
    //

    if (mode == MODE_DUPLICATE) {

        //
        // Search a free entry for the nView we will create
        //

        if ( (Preference != -1) && Views[ Preference ].Doc == -1 ) {
            nView = Preference;
        } else {
            for (nView = 0; (nView < MAX_VIEWS) && (Views[nView].Doc != -1); nView++);
        }

        if (nView == MAX_VIEWS) {
            ErrorBox(ERR_Too_Many_Opened_Views);
            return -1;
        }

        //
        // Copy parameters from previous nView
        //

        Assert( Docs[Views[dupView].Doc].FirstView >= 0);

        //
        //      Find the last nView for this document
        //

        n = dupView;
        while (Views[n].NextView != -1) {
            n = Views[n].NextView;
        }

        Assert(n < MAX_VIEWS);

        //
        //     Attach new nView to last one found
        //

        Views[nView] = Views[n];
        Views[n].NextView = nView;
        Views[nView].hwndClient = NULL;

        //
        //
        //

        Views[nView].iYTop = Views[dupView].iYTop;

        //
        //     Enlist nView in window menu
        //

        AddWindowMenuItem(Views[dupView].Doc, nView);

        return nView;

    } else if (mode == MODE_RELOAD) {
        nView = Docs[doc].FirstView;
    }

    //
    // First search a free entry for the document
    //

    if (mode != MODE_RELOAD) {
        for (doc = 0; (doc < MAX_DOCUMENTS) && (Docs[doc].FirstView != -1); doc++);
    }

    if (doc >= MAX_DOCUMENTS) {
        ErrorBox(ERR_Too_Many_Opened_Documents);
        return -1;
    }

    d = &Docs[doc];

    if (type == DOC_WIN) {

        //
        //      Check if file is not already loaded
        //

        if (mode == MODE_RELOAD) {
            DestroyDocument(doc);
            language = SetLanguage(doc);
        } else {
            if (FileName != NULL) {
                TCHAR szAbsolutePath[_MAX_PATH] = {0};

                Assert(sizeof(szAbsolutePath) == sizeof(d->szFileName));

                // We may have a relative path name to a file. Try to get the absolute path.
                if ( _fullpath(szAbsolutePath, FileName, sizeof(szAbsolutePath) ) ) {
                    // success
                    _tcscpy(d->szFileName, szAbsolutePath);
                } else {
                    // error. Use as is.
                    _tcscpy(d->szFileName, FileName);
                }

                for (n = 0; n < MAX_DOCUMENTS; n++) {
                    if (Docs[n].FirstView != -1
                        && _strcmpi(Docs[n].szFileName, d->szFileName) == 0) {

                        SetMessageText_StatusBar(ERR_File_Already_Loaded, STATUS_INFOTEXT, FileName);
                        MessageBeep(0);

                        //
                        //  Reactivate window
                        //

                        //SendMessage(g_hwndMDIClient, WM_MDIACTIVATE, (WPARAM) Views[Docs[n].FirstView].hwndFrame, 0L);
                        ActivateMDIChild(Views[Docs[n].FirstView].hwndFrame, bUserActivated);
                        return -1;
                    }
                }

                language = SetLanguage(doc);

            } else {
                // shouldn't happen anymore
                Assert(0);
// BUGBUG - dead code - kcarlos
#if 0
                //
                //  Initialize document record and first nView
                //

                register int i, j;

                for (i = 0; i < MAX_DOCUMENTS; i++) {
                    CreateUntitled(d->FileName, i + 1);
                    for (j = 0; j < MAX_DOCUMENTS; j++) {
                        if (j != doc &&
                            _strcmpi (d->szFileName, Docs[j].szFileName) == 0) {
                            break;
                        }
                    }
                    if (j >= MAX_DOCUMENTS) {
                        break;
                    }
                }

                language = C_LANGUAGE;
#endif
            }
        }
    } else {

        WORD winTitle;
        char rgch[MAX_MSG_TXT];

        language = NO_LANGUAGE;

        //
        //  Non Document type, Load window title from ressource
        //

        switch (type) {

        case DISASM_WIN:
            winTitle = SYS_DisasmWin_Title;
            break;       
        case COMMAND_WIN:
            winTitle = SYS_CmdWin_Title;
            break;
        case MEMORY_WIN:
            winTitle = SYS_MemoryWin_Title;
            break;
        default:
            Assert(FALSE);
            return -1;
            break;
        }
        Dbg(LoadString(g_hInst, winTitle, rgch, MAX_MSG_TXT));
        RemoveMnemonic(rgch, d->szFileName);

        if (type == MEMORY_WIN) {
            lstrcat (d->szFileName,"(");
            lstrcat (d->szFileName,TempMemWinDesc.szAddress);
            lstrcat (d->szFileName,")");
        }
    }

    //
    //  Then search a free entry for the first nView we will create
    //

    if (mode != MODE_RELOAD) {

        if ( (Preference != -1) && Views[ Preference ].Doc == -1 ) {
            nView = Preference;
        } else {
            for (nView = 0; nView < MAX_VIEWS && Views[nView].Doc != -1; nView++);
        }
        if (nView == MAX_VIEWS) {
            ErrorBox(ERR_Too_Many_Opened_Views);
            return -1;
        }
    }

    //
    // Check if file exist
    //

    if (mode == MODE_CREATE || type != DOC_WIN) {
        create = TRUE;
    } else {
        if (mode == MODE_OPEN || FileExist(FileName)) {
            create = FALSE;
        } else {
            if (mode == MODE_OPENCREATE) {
                // Tell the user that the file does not exist.

                // kcarlos
                // BUGBUG
                // Quick hack. To fix a bug, hopefully this all disappear soon.
                VarMsgBox(hwndFrame, SYS_Does_Not_Exist_Create, MB_OK, FileName);
                return -1;
            } else {
                create = FALSE;
            }
        }
    }

    d->readOnly = FALSE;
    d->docType = type;
    d->language = (WORD) language;
    d->untitled = (FileName == NULL);
    d->ismodified = FALSE;

    if (create) {

        LPBLOCKDEF pb;

        //
        //  Initialize the file with a null-string
        //


        d->LastBlock = d->FirstBlock = (LPBLOCKDEF)DocAlloc(sizeof(BLOCKDEF));
        GetSystemTimeAsFileTime(&d->time);

        if (d->FirstBlock == NULL) {
            ErrorBox(SYS_Allocate_Memory);
            return -1;
        }

        pb = d->FirstBlock;

        //
        //  Initialize first block
        //

        pb->PrevBlock = pb->NextBlock = NULL;
        pb->LastLineOffset = 0;

        //
        // Initialize first line
        //

        pl = (LPLINEREC)pb->Data;
        pl->PrevLength = 0;
        pl->Length = LHD;
        pl->Status = 0;

        d->NbLines = 1;         // We start with one null line

    } else {

        //
        // Load the file and check if it's a valid one
        //

        if (!LoadFile(doc)) {
            return -1;
        }
    }

    //
    // Initialize current pointers
    //

    d->CurrentBlock = d->FirstBlock;
    d->CurrentLine = 0;
    d->CurrentLineOffset = 0;
    pl = (LPLINEREC)(d->FirstBlock->Data);
    ExpandTabs(&pl);

    //
    // Undo/redo part
    //

    d->undo.h = 0;
    d->redo.h = 0;
    d->playCount = REC_CANNOTUNDO;
    if (g_contGlobalPreferences_WkSp.m_dwUndoResize == 0 || type != DOC_WIN) {
        d->recType = REC_STOPPED;
    } else {
        d->recType = REC_UNDO;
    }
    CreateRecBuf(doc, REC_UNDO, g_contGlobalPreferences_WkSp.m_dwUndoResize);

    if (mode == MODE_RELOAD) {
        RefreshWindowsTitle(doc);
    } else {

        //
        //  Initialize nView part
        //

        views = &Views[nView];
        views->NextView = -1;
        views->X = views->Y = 0;
        views->hwndClient = views->hwndFrame = NULL;
        views->hScrollBar = g_contGlobalPreferences_WkSp.m_bHorzScrollBars;
        views->vScrollBar = g_contGlobalPreferences_WkSp.m_bVertScrollBars;
        views->scrollFactor = 0;
        views->iYTop = -1;

        //
        //  Everything is OK, add title in window menu and return the nView
        //

        d->FirstView = nView;
        views->Doc = doc;
        AddWindowMenuItem(doc, nView);
    }

    //
    // Check syntax if C
    //

    if (d->language == C_LANGUAGE) {
        d->lineTop = 0;
        d->lineBottom = d->NbLines;
        CheckSyntax(doc);
    }

    return nView;
}                                       // OpenDocument()
Example #16
0
//Save document with (possibly) a new file name
BOOL FAR  SaveDocument(int doc, LPSTR FileName)
{
    LPLINEREC pl;
    LPBLOCKDEF pb;
    long y;
    register WORD i;
    WORD len;
    HCURSOR hSaveCursor;
    LPDOCREC d = &Docs[doc];

    //Set the Hour glass cursor
    hSaveCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));

    //Create file
    if (HFILE_ERROR == (hFileDoc = _lcreat(FileName, 0)) ) {
        ErrorBox(ERR_File_Create, (LPSTR)FileName);
        goto error0;
    }

    //Allocate space for Disk Buffer

    if ((pszBufferDoc = DocAlloc(DISK_BLOCK_SIZE)) == NULL) {
        ErrorBox(SYS_Allocate_Memory);
        goto error1;
    }

    dwOffsetDoc = 0; y = 0;

    //Get first line
    if (!FirstLine (doc, &pl, &y, &pb))
          return FALSE;

    //Save each line of file
    while (TRUE) {

        //Remove trailing blanks
        len = (WORD) (pl->Length - LHD);
        {
            TCHAR *pch1;

            pch1 = pl->Text + (pl->Length - LHD);

            while (pch1 > pl->Text) {
                pch1 = CharPrev(pl->Text, pch1);
                if (*pch1 != ' ' && *pch1 != TAB) {
                    break;
                }
                len --;
            }
        }

        //Write line
        i = 0;
        while (i < len) {

            PutChar(FileName, pl->Text[i]);
            i++;
        }

        if (y >= d->NbLines) {
            if (dwOffsetDoc && !Flush(FileName))
                goto error2;
            break;
        }
        else {
            PutChar (FileName, CR);
            PutChar (FileName, LF);
            if (!NextLine (doc, &pl, &y, &pb))
                  goto error2;
        }
    }

    CloseHandle (hFileDoc);

    //Update internal file date
    GetSystemTimeAsFileTime(&d->time);

    CloseLine(doc, &pl, y, &pb);

    d->ismodified = FALSE;
    RefreshWindowsTitle(doc);

    SetCursor (hSaveCursor);

    return TRUE;

  error2:
    CloseLine(doc, &pl, y, &pb);
    if (!DocFree(pszBufferDoc))
          InternalErrorBox(SYS_Free_Memory);

  error1:
    CloseHandle (hFileDoc);

  error0:
    SetCursor (hSaveCursor);
    return FALSE;
}                                       /* SaveDocument() */
Example #17
0
BOOL

LoadFile(
    int doc
    )
{
    LPDOCREC d =&Docs[doc];
    char line[MAX_USER_LINE + 1];
    int offset; //Current offset of storage in block
    int lineLen;
    BYTE prevLength; //Previous line size
    HCURSOR hSaveCursor;
    WORD res;
    WORD nbLines = 0;

    //
    // Documents are now always read only. Because WinDbg is no longer and IDE, it
    // is strictly a debugger now.
    //

    hFileDoc = CreateFile(d->szFileName, GENERIC_READ, FILE_SHARE_READ, 
        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (INVALID_HANDLE_VALUE == hFileDoc) {
        ErrorBox( ERR_File_Open, (LPSTR)d->szFileName );
        return FALSE;
    }

    d->readOnly = TRUE;

    //Store file date

    if (!GetFileTimeByName( d->szFileName, NULL, NULL, &d->time ) ) {
        GetSystemTimeAsFileTime(&d->time);
    }

    if ((pszBufferDoc = DocAlloc(DISK_BLOCK_SIZE)) == NULL) {
        ErrorBox(SYS_Allocate_Memory);
        goto error1;
    }

    //Alloc first block

    if (!AllocateBlock(NULL, NULL, &d->FirstBlock)) {
        return FALSE;
    }

    //If we are in reload mode, and a message box shows up, a repaint
    //of the document being loaded is done, so force number of lines
    //to a value != 0

    d->NbLines = MAX_LINE_NUMBER;

    d->LastBlock = d->FirstBlock;
    dwBytesReadDoc = DISK_BLOCK_SIZE;
    dwOffsetDoc = DISK_BLOCK_SIZE;
    offset = 0;
    prevLength = 0;

    //Set the Hour glass cursor

    hSaveCursor = SetCursor (LoadCursor(NULL, IDC_WAIT));

    //Read file line after line

    res = LoadLine(line, &lineLen, nbLines);
    while (res == END_OF_LINE) {

        //Truncate a file too large

        if (nbLines >= MAX_LINE_NUMBER - 1) {
            ErrorBox(ERR_Truncate_Doc);
            res = END_OF_FILE;
            break;
        }

        if (!StoreLine(line, lineLen, &offset, &prevLength, &d->LastBlock)) {
            res = END_ABORT;
            break;
        }

        res = LoadLine(line, &lineLen, ++nbLines);
    }

    //Take decisions

    switch (res) {

      case END_OF_FILE:

        //Store last line

        if (StoreLine(line, lineLen, &offset, &prevLength, &d->LastBlock)) {

            nbLines++;

            //Free memory

            if (!DocFree(pszBufferDoc))
                  InternalErrorBox(SYS_Free_Memory);

            //Restore cursor

            SetCursor(hSaveCursor);

            CloseHandle(hFileDoc);
            d->NbLines = nbLines;
            return TRUE;
        } else
              goto abort;

      case ERR_File_Read:
      case ERR_Not_A_Text_File:
        ErrorBox(res, (LPSTR)d->szFileName);
        //Fall through

      case END_ABORT:
        {
            LPBLOCKDEF pB;

          abort:
            while (TRUE) {

                pB = (d->LastBlock)->PrevBlock;
                if (!DocFree((LPSTR)d->LastBlock))
                      InternalErrorBox(SYS_Free_Memory);
                d->LastBlock = pB;
                if (pB == NULL)
                      break;
            }
            SetCursor(hSaveCursor);
            break;
        }

      default:
        Assert(FALSE);
        break;
    }

    //Restore cursor

    SetCursor(hSaveCursor);

    if (!DocFree(pszBufferDoc))
          InternalErrorBox(SYS_Free_Memory);

  error1: {
        CloseHandle(hFileDoc);
    }

    return FALSE;
}                                       /* LoadFile() */
Example #18
0
BOOL ClipboardCopy(void)
{	HGLOBAL	  hMem;
	char huge *pMem;
	LONG	  lSize;
	BOOL	  WideCharConvert = FALSE;
	UINT	  Codepage = 0;

	/*prepare resources...*/
	if (!SelectCount) {
		Error(209);
		return (FALSE);
	}
	if (!OpenClipboard(hwndMain)) {
		ErrorBox(MB_ICONEXCLAMATION, 302);
		return (FALSE);
	}
	lSize = SelectCount + sizeof(BinaryPart);
	if (!(GetVersion() & 0x80000000U))
		if (UtfEncoding || CharSet == CS_OEM || AnsiCodePage != CP_ACP) {
			/*copy as wide chars...*/
			Codepage = CharSet == CS_OEM ? OemCodePage : AnsiCodePage;
			if (UtfEncoding != 16)
				lSize <<= 1;
			WideCharConvert = TRUE;
		}
	hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, lSize);
	if (!hMem) {
		CloseClipboard();
		ErrorBox(MB_ICONEXCLAMATION, 304);
		return (FALSE);
	}
	pMem = GlobalLock(hMem);
	if (pMem == NULL) {
		CloseClipboard();
		GlobalFree(hMem);
		ErrorBox(MB_ICONEXCLAMATION, 305);
		return (FALSE);
	}

	/*copy into memory...*/
	{	POSITION Pos;
		ULONG    Bytes = SelectCount;
		UINT     i;
		BOOL	 NullbyteFound = FALSE;

		Pos = SelectStart;
		if (UtfEncoding && WideCharConvert) {
			POSITION EndPos = Pos;
			WCHAR	 *pw = (WCHAR *)pMem;

			Advance(&EndPos, Bytes);
			//if (CountBytes(&Pos) != 0 || (i = CharAndAdvance(&Pos)) == C_BOM)
			i = CharAndAdvance(&Pos);
			for (;;) {
				if (ComparePos(&Pos, &EndPos) > 0)
					break;
				if (i == C_EOF) break;
				if (i == C_CRLF) {
					if ((char *)pw + 6 > pMem + lSize)
						break;
					*pw++ = '\r';
					i = '\n';
				}
				if ((char *)pw + 4 > pMem + lSize)
					break;
				*pw++ = i;
				i = CharAndAdvance(&Pos);
			}
			*pw = '\0';
		} else while (Bytes) {
			LPSTR p, pNull;

			CharAt(&Pos);	/*normalize position and enforce page load*/
			i = Pos.p->Fill - Pos.i;
			if (i > Bytes) i = (UINT)Bytes;
			p = Pos.p->PageBuf + Pos.i;
			if (!NullbyteFound && (pNull = _fmemchr(p, '\0', i)) != NULL) {
				if (ErrorBox(MB_ICONINFORMATION|MB_OKCANCEL, 328) == IDCANCEL) {
					CloseClipboard();
					GlobalUnlock(hMem);
					GlobalFree(hMem);
					return (FALSE);
				}
				NullbyteFound = TRUE;
				i = pNull - p + 1;
				if (CharSet == CS_EBCDIC) EbcdicConvert(pMem, p, i);
				else if (WideCharConvert) {
					MultiByteToWideChar(Codepage, 0, p, i, (WCHAR*)pMem, i);
					pMem += i;
				} else hmemcpy(pMem, p, i);
				pMem  += i;
				Bytes -= --i;
				Pos.i += i;
				i = wsprintf(BinaryPart, BinaryFormat, Bytes);
				if (WideCharConvert) {
					MultiByteToWideChar(Codepage, 0, BinaryPart, i,
													 (WCHAR*)pMem, i);
					pMem += i;
				} else hmemcpy(pMem, BinaryPart, i);
				pMem += i;
				continue;
			}
			if (CharSet == CS_EBCDIC)
				EbcdicConvert(pMem, Pos.p->PageBuf + Pos.i, i);
			else if (WideCharConvert) {
				MultiByteToWideChar(Codepage, 0, Pos.p->PageBuf + Pos.i, i,
												 (WCHAR*)pMem, i);
				if (CharSet == CS_OEM) {
					extern WCHAR const MapLowOemToUtf16[33];
					PWSTR			   pw = (WCHAR*)pMem;
					INT				   j;

					for (j=i; j>0; --j) {
						if (*pw < ' ') {
							switch (*pw) {
							case '\0':
							case '\t':
							case '\n':
							case '\r':	break;
							default:	*pw = MapLowOemToUtf16[*pw];
							}
						}
						++pw;
					}
				}
				pMem += i;
			} else hmemcpy(pMem, Pos.p->PageBuf + Pos.i, i);
			pMem  += i;
			Bytes -= i;
			Pos.i += i;
		}
	}

	/*unlock...*/
	GlobalUnlock(hMem);

	/*clear previous clipboard contents...*/
	if (!EmptyClipboard()) {
		CloseClipboard();
		GlobalFree(hMem);
		ErrorBox(MB_ICONEXCLAMATION, 303);
		return (FALSE);
	}

	/*finally, publish...*/
	SetClipboardData(WideCharConvert ? CF_UNICODETEXT
									 : CharSet == CS_OEM ? CF_OEMTEXT
														 : CF_TEXT, hMem);
	CloseClipboard();
	CheckClipboard();
	return (TRUE);
}
Example #19
0
int APIENTRY _tWinMain(HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPTSTR    lpCmdLine,
    int       nCmdShow)
{
    std::vector<std::wstring> cmdArgs = splitCmdArgs(lpCmdLine);
    std::wstring newCmdLine = lpCmdLine;

    std::wstring curPath;

    TCHAR szFileName[MAX_PATH];
    GetModuleFileName(NULL, szFileName, MAX_PATH);
    WCHAR** lppPart = { NULL };
    WCHAR fulPath_s[4096] = L"";
    GetFullPathName(szFileName, 4096, fulPath_s, lppPart);
    curPath = dirnameOf(fulPath_s);

    std::wstring pathToSMBX = curPath+L"\\smbx.exe"; //use either smbx.exe or the first arg
        if (pathToSMBX == fulPath_s) // If LunaLoader.exe renamed into "SMBX.exe"
            pathToSMBX = curPath + L"\\smbx.legacy";

    if (cmdArgs.size() > 0) { //if more than one arg then possible of a smbx path
        if (cmdArgs[0].find(L"--") == std::wstring::npos) { //if the first arg starting with "--" then no smbx path --> just starting with argument
            pathToSMBX = cmdArgs[0];
            newCmdLine = L""; //reset the arg path
            if (cmdArgs.size() > 1){ //strip the smbx-path from the arguments
                for (unsigned int i = 1; i < cmdArgs.size(); ++i){
                    newCmdLine += cmdArgs[i] + std::wstring(L" ");
                        if (i == cmdArgs.size() - 1){ //if the last argument of the args list then remove the last space.
                            std::wstring::iterator it = newCmdLine.end();
                            newCmdLine.erase(--it);
                        }
                }
            }
        }
    }

    FILE *test;
    _wfopen_s(&test, pathToSMBX.c_str(), L"rb");
    if (!test) {
            pathToSMBX = curPath+L"\\smbx.legacy";
    }
    else fclose(test);

    LunaLoaderResult ret = LunaLoaderRun(pathToSMBX.c_str(), newCmdLine.c_str(), curPath.c_str());

    switch(ret)
    {
    case LUNALOADER_OK:
        return 0;
    case LUNALOADER_CREATEPROCESS_FAIL:
        ErrorBox("Error: Couldn't run SMBX\nHowever you can try to drag and drop the SMBX exe file to LunaLoader.exe\nIf this doesn't work then ask on the forums.", "Couldn't run SMBX");
        return 1;
    case LUNALOADER_PATCH_FAIL:
        ErrorBox("Error: Failed to patch SMBX", "Failed to patch SMBX");
        return 1;
    default:
        ErrorBox("Unknown Error in LunaLoader.", "Unknown Error");
        return 1;
    }
}
Example #20
0
//  (possibly more than one per "Alias" brace? I'll code for it.
// 
// return = success / fail...
//
bool Parser_Load(LPCSTR psFullPathedFilename, MappedString_t &ParsedAliases)
{
	bool bReturn = false;

	ParsedAliases.clear();

	FILE *fhHandle = fopen(psFullPathedFilename,"rt");
	if (fhHandle)
	{			
		bool bParsingBlock = false;
		bool bSkippingBlock= false;
		char sLine[1024];

		while (fgets(sLine,sizeof(sLine)-1,fhHandle)!=NULL)
		{
			sLine[sizeof(sLine)-1]='\0';

			// :-)
			CString str(sLine);
					str.TrimLeft();
					str.TrimRight();

			strcpy(sLine,str);

			if (!bSkippingBlock)
			{
				if (!bParsingBlock)
				{
					if (strlen(sLine))	// found any kind of header?
					{
						if (!stricmp(sLine,"Alias"))
						{							
							bParsingBlock = true;						
						}
						else							
						{
							// not a recognised header, so...
							//
							bSkippingBlock = true;
						}
					}
					continue;
				}
				else
				{
					if (!stricmp(sLine,"{"))
						continue;

					if (!stricmp(sLine,"}"))
					{
						bParsingBlock = false;
						continue;
					}

					if (strlen(sLine))
					{
						// must be a value pair, so...
						//
						// first, find the whitespace that seperates them...
						//
						CString strPair(sLine);
						int iLoc = strPair.FindOneOf(" \t");
						if (iLoc == -1)
						{
							assert(0);
							ErrorBox(va("Parser_Load(): Couldn't find whitespace-seperator in line:\n\n\"%s\"\n\n( File: \"%s\" )",(LPCSTR) strPair,psFullPathedFilename));
							bReturn = false;
							break;
						}

						// stl & MFC rule!...
						//
						CString strArg_Left(strPair.Left(iLoc));	// real name
								strArg_Left.TrimRight();
								strArg_Left.Replace("\"","");

						CString strArg_Right(strPair.Mid (iLoc));	// alias name
								strArg_Right.TrimLeft();
								strArg_Right.Replace("\"","");

						ParsedAliases[(LPCSTR)strArg_Left] = (LPCSTR)strArg_Right;

						bReturn = true;
						continue;
					}
				}
			}
			else
			{
				// skip to close brace...
				//
				if (stricmp(sLine,"}"))
					continue;

				bSkippingBlock = false;
			}
		}

		fclose(fhHandle);
	}

	return bReturn;
}
Example #21
0
void StatusBar::Create(HWND hWnd, HINSTANCE hInst)
{
	hCtrl = CreateWindow(STATUSCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | WS_BORDER, -100, -100, 10, 10, hWnd, NULL, hInst, NULL);
	if (hCtrl == NULL)
		ErrorBox(hWnd, "Unable to create ScrollBar", GetLastError());
}
Example #22
0
// Insert a new instrument assigned to sample nSample or duplicate instrument nDuplicate.
// If nSample is invalid, an appropriate sample slot is selected. 0 means "no sample".
INSTRUMENTINDEX CModDoc::InsertInstrument(SAMPLEINDEX nSample, INSTRUMENTINDEX nDuplicate)
//----------------------------------------------------------------------------------------
{
	if (m_SndFile.GetModSpecifications().instrumentsMax == 0) return INSTRUMENTINDEX_INVALID;

	ModInstrument *pDup = nullptr;

	if ((nDuplicate > 0) && (nDuplicate <= m_SndFile.m_nInstruments))
	{
		pDup = m_SndFile.Instruments[nDuplicate];
	}
	if ((!m_SndFile.GetNumInstruments()) && ((m_SndFile.GetNumSamples() > 1) || (m_SndFile.GetSample(1).pSample)))
	{
		if (pDup) return INSTRUMENTINDEX_INVALID;
		ConfirmAnswer result = Reporting::Confirm("Convert existing samples to instruments first?", true);
		if (result == cnfCancel)
		{
			return INSTRUMENTINDEX_INVALID;
		}
		if (result == cnfYes)
		{
			if(!ConvertSamplesToInstruments())
			{
				return INSTRUMENTINDEX_INVALID;
			}
		}
	}
	
	const INSTRUMENTINDEX newins = m_SndFile.GetNextFreeInstrument();
	if(newins == INSTRUMENTINDEX_INVALID)
	{
		ErrorBox(IDS_ERR_TOOMANYINS, CMainFrame::GetMainFrame());
		return INSTRUMENTINDEX_INVALID;
	} else if(newins > m_SndFile.GetNumInstruments())
	{
		m_SndFile.m_nInstruments = newins;
	}

	// Determine which sample slot to use
	SAMPLEINDEX newsmp = 0;
	if (nSample < m_SndFile.GetModSpecifications().samplesMax)
	{
		// Use specified slot
		newsmp = nSample;
	} else if (!pDup)
	{
		newsmp = m_SndFile.GetNextFreeSample(newins);
		if (newsmp > m_SndFile.GetNumSamples())
		{
			// Add a new sample
			const SAMPLEINDEX inssmp = InsertSample();
			if (inssmp != SAMPLEINDEX_INVALID) newsmp = inssmp;
		}
	}

	CriticalSection cs;

	ModInstrument *pIns = m_SndFile.AllocateInstrument(newins, newsmp);
	if(pIns == nullptr)
	{
		cs.Leave();
		ErrorBox(IDS_ERR_OUTOFMEMORY, CMainFrame::GetMainFrame());
		return INSTRUMENTINDEX_INVALID;
	}
	InitializeInstrument(pIns);

	if (pDup)
	{
		*pIns = *pDup;
	}

	SetModified();

	return newins;
}
Example #23
0
void SystemErrorBox(DWORD dwError)
{
	ErrorBox( SystemErrorString(dwError) );
}
Example #24
0
void preserve_data(void)
{
	int i;
	int ok=true;
	stamp_structure *s;

	switch (dimension)
	{
	case LOGISTIC:
		ok = memok((sizeof(fflockstruct1)));
		break;
   case HENON:
		ok = memok((sizeof(fflockstruct2)));
		break;
	case YORKE:
#ifdef OLDWAY
		ok = memok((sizeof(fflockstruct2)));
		break;
#endif
	case LORENZ:
		ok = memok((sizeof(fflockstruct3)));
		break;
	}

	if (!ok)
	{
		stamp_err = 1;
		ErrorBox("Not enough memory to preserve stamp.");
		return;
	}

	/* get rid of the highest */
	if (stamp_data[3])
	{
		s = stamp_data[3];
		switch (s->dimension)
		{
		case LOGISTIC:
			free(s->s.lo.fflock1ptr);
			s->s.lo.fflock1ptr = NULL;
			break;
      case HENON:
			free(s->s.h.fflock2ptr);
			s->s.h.fflock2ptr = NULL;
			break;
#ifdef OLDWAY
		case YORKE:
			free(s->s.y.fflock2ptr);
			s->s.y.fflock2ptr = NULL;
			break;
#endif
		case LORENZ:
			free(s->s.lz.fflock3ptr);
			s->s.lz.fflock3ptr = NULL;
			break;
		}
		free(s);
		s = NULL;
	}

	for (i = 3; i > 0; i--)
		stamp_data[i] = stamp_data[i - 1];

	s = malloc(sizeof(stamp_structure));
	s->dimension = dimension;
	(*stampers[dimension - 1]) (s);
	stamp_data[0] = s;
}
Example #25
0
void restore_data(int n)
{
	stamp_structure s;
	fflockstruct1 *fs1;
	fflockstruct2 *fs2;
	fflockstruct3 *fs3;


	if (!stamp_data[n])
		return;

	s = *stamp_data[n];	/* copy it, we might loose it */
	switch (s.dimension)
	{
	case LOGISTIC:
		if (!memok(sizeof(fflockstruct1)) ||
		    (fs1 = malloc(sizeof(fflockstruct1))) == NULL)
		{
			ErrorBox("Not enough memory to restore stamp.");
			return;
		}
		memcpy(fs1, s.s.lo.fflock1ptr, sizeof(fflockstruct1));
		s.s.lo.fflock1ptr = fs1;
		break;
	case HENON:
      if (!memok(sizeof(fflockstruct2)) ||
		    (fs2 = malloc(sizeof(fflockstruct2))) == NULL)
		{
			ErrorBox("Not enough memory to restore stamp.");
			return;
		}
		memcpy(fs2, s.s.h.fflock2ptr, sizeof(fflockstruct2));
		s.s.h.fflock2ptr = fs2;
		break;
	case YORKE:
#ifdef OLDWAY
		if (!memok(sizeof(fflockstruct2)) ||
		    (fs2 = malloc(sizeof(fflockstruct2))) == NULL)
		{
			ErrorBox("Not enough memory to restore stamp.");
			return;
		}
		memcpy(fs2, s.s.y.fflock2ptr, sizeof(fflockstruct2));
		s.s.y.fflock2ptr = fs2;
#endif
		break;
	case LORENZ:
		if (!memok(sizeof(fflockstruct3)) ||
		    (fs3 = malloc(sizeof(fflockstruct3))) == NULL)
		{
			ErrorBox("Not enough memory to restore stamp.");
			return;
		}
		memcpy(fs3, s.s.lz.fflock3ptr, sizeof(fflockstruct3));
		s.s.lz.fflock3ptr = fs3;
		break;
	}


	erasecursor();
	if (Stamping)
	{
		preserve_data();
		slide_stamps();
	}
	/* the restorer will free the proper flockptr */
	(*restorers[s.dimension - 1]) (&s);
}
Example #26
0
int GifDisplay(char *filename)
{
	int i, j;
	int c;
	int colors;
	union REGS regs;
	struct SREGS sregs;
	unsigned char ctab[17];
	int ret = GIF_COOLMAN;

	if (!memok(16133L))
	{			/* Added mallocs in decoder.c  */
		ErrorBox("Not enough memory to view a Gif file.");
		return OUT_OF_MEMORY;
	}


	giffd = fopen(filename, "rb");
	if (!giffd)
   {
      FileError(filename,NULL);
		return -1;
   }
	gifrow = 0;
	gifcol = 0;
	safe_alloc = 1;
	if ((rowbuf = malloc(512)) == NULL)
	{
		ret = OUT_OF_MEMORY;
		goto TRUNCOUT;
	}
	rowbufptr = 512;	/* to get it started */


	fread(&gif, 1, sizeof(gif), giffd);
	colors = (1 << ((gif.colpix & PIXMASK) + 1));
   if (colors > 16 && hasVGA)
   {
      regs.h.ah = 0;
      regs.h.al = OurMode = 0x13;
      int86(0x10,&regs,&regs);
   }
   else
   {
      if (gif.h > 350 && hasVGA)
	       OurMode = 0x12;
      else
      	 OurMode = 0x10;

      regs.h.ah = 0;
      regs.h.al = OurMode;
      int86(0x10,&regs,&regs);
   }

	if (gif.colpix & COLTAB)
	{
		fread(cmap, 1, colors * 3, giffd);
		/* Now set up the colormap if appropriate */
		for (i = 0; i < colors * 3; i++)
			cmap[i] >>= 2;
		if (hasVGA)
		{
			/*
			 * This is a VGA. Just write the map, shifted
			 * appropriately.
			 */


			regs.h.ah = 0x10;
			regs.h.al = 0x12;
			regs.x.bx = 0;
			regs.x.cx = colors;
			regs.x.dx = FP_OFF(cmap);
			sregs.es = FP_SEG(cmap);
			int86x(0x10, &regs, &regs, &sregs);

			/* We'll also want to set the 0-16 map here? */
			for (i = 0; i < 16; i++)
				ctab[i] = i;
			ctab[16] = 0;
			regs.h.ah = 0x10;
			regs.h.al = 0x2;
			regs.x.dx = FP_OFF(ctab);
			sregs.es = FP_SEG(ctab);
			int86x(0x10, &regs, &regs, &sregs);

		}
		else
		{

			for (i = 0; i < 16; i++)
			{
				for (j = 0; j < 64; j++)
				{
					unsigned char *p = defaultpalette[j];

					if (p[0] == cmap[i * 3] &&
					    p[1] == cmap[i * 3 + 1] &&
					    p[2] == cmap[i * 3 + 2])
						break;
				}
				ctab[i] = j;
			}
			ctab[i] = 0;
			regs.h.ah = 0x10;
			regs.h.al = 0x2;
			regs.x.dx = FP_OFF(ctab);
			sregs.es = FP_SEG(ctab);
			int86x(0x10, &regs, &regs, &sregs);

		}
	}
Example #27
0
void GlobalSubst(HWND hDlg)
{	PWSTR p = CommandBuf;
	INT	  n;

	Magic	 = IsDlgButtonChecked(hDlg, IDC_MAGIC);
	HexInput = IsDlgButtonChecked(hDlg, IDC_HEXSEARCH);
	ReplacingAll = TRUE;
	p += n = _snwprintf(p, WSIZE(CommandBuf), L":%%s//");
	n += GetDlgItemTextW(hDlg, IDC_REPLACESTRING, p, WSIZE(CommandBuf) - n);
	while (*p) {
		switch (*p) {
			case '\\':
				if (Magic) {
					if	 (*++p >= '0' && *p <= '7') {
						if (*p >= '0' && *p <= '3') ++p;
						if (*p >= '0' && *p <= '7') ++p;
						if (*p >= '0' && *p <= '7') ++p;
						continue;
					}
					if (*p == '%') {
						if (ISHEX(p[1])) ++p;
						if (ISHEX(p[1])) ++p;
					}
					break;
				}
				/*FALLTHROUGH*/
			case '&':
				if (*p=='&' && !Magic!=MagicFlag) break;
				/*FALLTHROUGH*/
			case '/':
				if (n+1 < WSIZE(CommandBuf)) {
					memmove(p+1, p, 2*wcslen(p)+2);
					*p++ = '\\';
					++n;
				}
				break;
			default:
				if (HexInput) {
					if (!ISHEX(*p)) {
						if (*p != ' ') {
							hwndErrorParent = hDlg;
							ErrorBox(MB_ICONSTOP, 239);
							hwndErrorParent = hwndMain;
							return;
						}
						memmove(p, p+1, 2*wcslen(p));
						--n;
						continue;
					}
					if (n+2 < WSIZE(CommandBuf)) {
						memmove(p+2, p, 2*wcslen(p)+2);
						*p++ = '\\';
						*p++ = '%';
						if (ISHEX(p[1])) ++p;
						n += 2;
					}
				}
		}
		++p;
	}
	if (n+2 < WSIZE(CommandBuf)) wcscpy(p, L"/g");
	SendMessage(hDlg, DM_SETDEFID, IDCANCEL, 0);
	SetFocus(GetDlgItem(hDlg, IDCANCEL));
	EnableControls(hDlg, FALSE);
	CommandExec(CommandBuf);
	EnableControls(hDlg, TRUE);
	ReplacingAll = FALSE;
}
Example #28
0
BOOL ClipboardPaste(void)
{
	HGLOBAL  hMem = 0;
	LPSTR	 lpMem;
	UINT	 uFormat = CharSet == CS_OEM ? CF_OEMTEXT : CF_TEXT;
	LONG	 lSize;
	MODEENUM SaveMode;
	BOOL	 FreeConversionMemory = FALSE;

	if (IsViewOnly()) return(FALSE);

	/*prepare resources...*/
	if (!OpenClipboard(hwndMain)) {
		ErrorBox(MB_ICONEXCLAMATION, 302);
		return (FALSE);
	}

	/*first check for binary data containing null bytes...*/
	if (UtfEncoding != 16 && (hMem = GetClipboardData(uFormat)) != 0) {
		lSize = GlobalSize(hMem);
		if ((lpMem = GlobalLock(hMem)) != NULL) {
			LPSTR lp;
			LONG  lRemain;

			lp = _fmemchr(lpMem, '\0', (size_t)lSize);
			if (lp != NULL && (lp-lpMem+sizeof(BinaryPart)) <= (size_t)lSize
						   && lp[1]==BinaryFormat[0]
						   && _fmemchr(lp+1, '\0', lSize-(lp+1-lpMem)) != NULL
						   && _fmemcmp(lp+1, BinaryFormat, 10) == 0) {
				/*insert first part of null containing binary data...*/
				SaveMode = Mode;
				if (Mode != InsertMode && Mode != ReplaceMode) {
					StartUndoSequence();
					Mode = InsertMode;
				}
				if (SelectCount) DeleteSelected(17);
				else EnterDeleteForUndo(&CurrPos, 0, 1); /*force new undo elem*/
				Mode = SaveMode;
				HideEditCaret();
				if (*lpMem) InsertBuffer(lpMem, (UINT)(lp-lpMem), 0);
				lRemain = strtoul(lp+11, &lp, 10);
				if (*lp != ':') lSize = 0;
				else {
					if (lSize >= (lp - lpMem) + lRemain) lSize = lRemain;
					else lSize = 0;
					lpMem = lp + 1;
				}
				if (lSize) InsertBuffer(lpMem, (UINT)lSize, 1);
				GetXPos(&CurrCol);
				ShowEditCaret();

				/*clean up...*/
				GlobalUnlock(hMem);
				CloseClipboard();
				return (TRUE);
			}
			GlobalUnlock(hMem);
			hMem = 0;
		}
	}

	/*then, if running on Windows NT, try to get wide chars...*/
	if (!(GetVersion() & 0x80000000U) && CharSet != CS_EBCDIC) {
		UINT Cp;

		if (UtfEncoding == 8)
			 Cp = CP_UTF8;
		else if (CharSet == CS_ANSI)
			 Cp = AnsiCodePage;
		else Cp = OemCodePage;
		if (Cp) {
			HGLOBAL	hWideCharMem = GetClipboardData(CF_UNICODETEXT);
			WCHAR	*lpWideCharMem;

			if (hWideCharMem) {
				lSize		  = GlobalSize(hWideCharMem);
				lpWideCharMem = GlobalLock(hWideCharMem);
				if (lpWideCharMem != NULL) {
					INT	   nSizeRequired;
					PWCHAR wp;

					lSize >>= 1;
					wp = wmemchr(lpWideCharMem, '\0', lSize);
					if (wp != NULL) lSize = wp - lpWideCharMem;
					if (UtfEncoding == 16) {
						lSize <<= 1;
						if (UtfLsbFirst) {
							hMem  = hWideCharMem;
							lpMem = (LPSTR)lpWideCharMem;
						} else {
							hMem  = GlobalAlloc(GMEM_MOVEABLE, lSize);
							if (hMem) {
								lpMem = GlobalLock(hMem);
								if (lpMem != NULL) {
									INT i = 0;

									while ((i += 2) <= lSize) {
										lpMem[i-2] = *lpWideCharMem >> 8;
										lpMem[i-1] = *lpWideCharMem++ & 255;
									}
									FreeConversionMemory = TRUE;
								} else {
									GlobalFree(hMem);
									hMem = 0;
								}
							}
						}
					} else {
int WINAPI WinMain(HINSTANCE inst, 
                   HINSTANCE prevInstance, 
                   LPSTR lpszCmdLine,
                   int nShowCmd)
{
	char* lpszAppName = "HelloWorld";
	HWND wnd;
	WNDCLASSEX wndclass;
	int retCode;

    {	//  Needed to scope all nsCOMPtr within XPCOM Init and Shutdown
      nsresult rv;
      nsCOMPtr<nsIServiceManager> servMan;
      rv = NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
      if(NS_FAILED(rv))
      {
        ErrorBox("Failed to initialize xpcom.");
        return -1;
      }
      
      nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
      NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
      registrar->AutoRegister(nsnull);
      
      nsCOMPtr<nsINativeApp> nativeAppService(do_GetService(kNativeAppCID, &rv));

      if(NS_FAILED(rv))
      {
        ErrorBox("Failed to get nativeAppService");
        return -1;
      }
      wndclass.cbSize        = sizeof(wndclass);
      wndclass.style         = CS_HREDRAW | CS_VREDRAW;
      wndclass.lpfnWndProc   = WndProc;
      wndclass.cbClsExtra    = 0;
      wndclass.cbWndExtra    = 0;
      wndclass.hInstance     = inst;
      wndclass.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
      wndclass.hCursor       = LoadCursor(NULL, IDC_ARROW);
      wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
      wndclass.lpszMenuName  = NULL;
      wndclass.lpszClassName = lpszAppName;
      wndclass.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

      RegisterClassEx(&wndclass) ;
      
      wnd = CreateWindow(lpszAppName, "The Hello World",
                         WS_OVERLAPPEDWINDOW,
                         CW_USEDEFAULT, CW_USEDEFAULT,
                         CW_USEDEFAULT, CW_USEDEFAULT,
                         NULL, NULL, inst, NULL);		     
      
      ShowWindow(wnd, nShowCmd);
      UpdateWindow(wnd);
      
      nsCOMPtr<nsIEventLoop> eventLoop;
      
      if(NS_FAILED(nativeAppService->CreateEventLoop(L"_MainLoop", 
                                                     nsEventLoopTypes::MainAppLoop, getter_AddRefs(eventLoop))))
        {
          ErrorBox("Failed to create event Loop");
          return 0;
        } 
      
      eventLoop->Run(nsnull, nsnull, nsnull, &retCode);
      eventLoop = nsnull; // Clear out before Shutting down XPCOM
      
      InfoBox("Hello World app is out of loop");
    }
	NS_ShutdownXPCOM(nsnull);
	InfoBox("Hello World app is exiting");
	return retCode;
}
Example #30
0
void CMobileOpalDlg::InitialiseOPAL()
{
  /////////////////////////////////////////////////////////////////////
  // Start up and initialise OPAL

  if (m_opal == NULL) {
    m_opal = OpalInitialise("pc h323 sip");
    if (m_opal == NULL) {
      ErrorBox(IDS_INIT_FAIL);
      EndDialog(IDCANCEL);
      return;
    }
  }

  OpalMessage command;
  OpalMessage * response;

  // General options
  memset(&command, 0, sizeof(command));
  command.m_type = OpalCmdSetGeneralParameters;

  CStringA strStunServer = GetOptionStringA(STUNServerKey);
  command.m_param.m_general.m_stunServer = strStunServer;

  if ((response = OpalSendMessage(m_opal, &command)) == NULL || response->m_type == OpalIndCommandError)
    ErrorBox(IDS_CONFIGURATION_FAIL);
  OpalFreeMessage(response);

  // Options across all protocols
  memset(&command, 0, sizeof(command));
  command.m_type = OpalCmdSetProtocolParameters;

  CStringA strUserName = GetOptionStringA(UserNameKey);
  command.m_param.m_protocol.m_name = strUserName;

  CStringA strDisplayName = GetOptionStringA(UserNameKey);
  command.m_param.m_protocol.m_displayName = strDisplayName;

  command.m_param.m_protocol.m_interfaceAddresses = "*";

  if ((response = OpalSendMessage(m_opal, &command)) == NULL || response->m_type == OpalIndCommandError)
    ErrorBox(IDS_LISTEN_FAIL);
  OpalFreeMessage(response);

  // H.323 gatekeeper regisration
  memset(&command, 0, sizeof(command));
  command.m_type = OpalCmdRegistration;

  UINT gkType = GetOptionInt(GkTypeKey);
  if (gkType > 0) {
    command.m_param.m_registrationInfo.m_protocol = "h323";

    CStringA strAliasName = GetOptionStringA(GkAliasKey);
    command.m_param.m_registrationInfo.m_identifier = strAliasName;

    CStringA strGkId = GetOptionStringA(GkIdKey);
    command.m_param.m_registrationInfo.m_adminEntity = strGkId;

    CStringA strGkHost = GetOptionStringA(GkHostKey);
    command.m_param.m_registrationInfo.m_hostName = strGkHost;

    CStringA strGkAuthUser = GetOptionStringA(GkAuthUserKey);
    command.m_param.m_registrationInfo.m_authUserName = strGkAuthUser;

    CStringA strGkPassword = GetOptionStringA(GkPasswordKey);
    command.m_param.m_registrationInfo.m_password = strGkPassword;

    if ((response = OpalSendMessage(m_opal, &command)) == NULL || response->m_type == OpalIndCommandError)
      ErrorBox(IDS_REGISTRATION_FAIL);
    OpalFreeMessage(response);
  }

  // SIP registrar regisration
  CStringA strAor = GetOptionStringA(RegistrarAorKey);
  if (!strAor.IsEmpty()) {
    memset(&command, 0, sizeof(command));
    command.m_type = OpalCmdRegistration;

    command.m_param.m_registrationInfo.m_protocol = "sip";

    command.m_param.m_registrationInfo.m_identifier = strAor;

    CStringA strHost = GetOptionStringA(RegistrarHostKey);
    command.m_param.m_registrationInfo.m_hostName = strHost;

    CStringA strAuthUser = GetOptionStringA(RegistrarUserKey);
    command.m_param.m_registrationInfo.m_authUserName = strAuthUser;

    CStringA strPassword = GetOptionStringA(RegistrarPassKey);
    command.m_param.m_registrationInfo.m_password = strPassword;

    CStringA strRealm = GetOptionStringA(RegistrarRealmKey);
    command.m_param.m_registrationInfo.m_adminEntity = strRealm;

    command.m_param.m_registrationInfo.m_timeToLive = 300;

    if ((response = OpalSendMessage(m_opal, &command)) == NULL || response->m_type == OpalIndCommandError)
      ErrorBox(IDS_REGISTRATION_FAIL);
    OpalFreeMessage(response);
  }
}