void g2LabelEdit::PasteBuffer()
{
    // Win32 implementation
    #ifdef _WIN32
    
        // Attempt to open clipboard
        if(!OpenClipboard(GetForegroundWindow()))
            return;
        
        // Get the windows clipboard text buffer
        HGLOBAL ClipboardHandle = GetClipboardData(CF_TEXT);
        if(ClipboardHandle != NULL)
        {
            // Actually copy the text
            LPTSTR StringLock = (LPTSTR)GlobalLock(ClipboardHandle); 
            if (StringLock != NULL) 
            {
                // Copy as much as we can
                char TempClipBuffer[g2LabelEdit_TextBufferLength];
                strncpy(TempClipBuffer, StringLock, g2LabelEdit_TextBufferLength - strlen(TextBuffer) - strlen(StringLock) - 1);
                
                // Copy the current text buffer
                char TempTextBuffer[g2LabelEdit_TextBufferLength];
                strcpy(TempTextBuffer, TextBuffer);
                
                // Copy into the full buffer (only if text is small enough)
                if(strlen(TempTextBuffer) + strlen(TempClipBuffer) + 1 < g2LabelEdit_TextBufferLength)
                {
                    char NewTextBuffer[g2LabelEdit_TextBufferLength];
                    sprintf(NewTextBuffer, "%s%s", TempTextBuffer, TempClipBuffer);
                    SetText(NewTextBuffer);
                }
                
                // Release the lock
                GlobalUnlock(StringLock); 
            }
        }
        
        // Close clipboard
        CloseClipboard();
    
    // OSX implementation
    #elif __APPLE__
    
        // Allocate or get a reference to the application's active clipboard
        PasteboardRef ClipboardHandle;
        if(PasteboardCreate(kPasteboardClipboard, &ClipboardHandle) != noErr)
            return;
        
        // Explicitly update (possibly not needed...)
        PasteboardSynchronize(ClipboardHandle);
        
        // Get the item count
        ItemCount ClipboardItems;
        if(PasteboardGetItemCount(ClipboardHandle, &ClipboardItems) != noErr)
            return;
        
        // Keep searching until we find valid text
        for(ItemCount ItemIndex = 1; ItemIndex <= ClipboardItems; ItemIndex++)
        {
            // Get item's ID
            PasteboardItemID ItemID;
            if(PasteboardGetItemIdentifier(ClipboardHandle, ItemIndex, &ItemID) != noErr)
                continue;
            
            // Get this item's data types
            CFArrayRef ItemTypes;
            if(PasteboardCopyItemFlavors(ClipboardHandle, ItemID, &ItemTypes) != noErr)
                continue;
            
            // For each data type for this clipboard item
            CFIndex ItemCount = CFArrayGetCount(ItemTypes);
            for(CFIndex ItemTypeIndex = 0; ItemTypeIndex < ItemCount; ItemTypeIndex++)
            {
                // Get the data type
                CFStringRef ItemType = (CFStringRef)CFArrayGetValueAtIndex(ItemTypes, ItemTypeIndex);
                
                // If we have any text-type, then paste and stop
                if(UTTypeConformsTo(ItemType, CFSTR("public.utf8-plain-text")))
                {
                    // Copy from clipboard
                    CFDataRef ItemData;
                    if(PasteboardCopyItemFlavorData(ClipboardHandle, ItemID, ItemType, &ItemData) != noErr)
                        continue;
                    
                    // Paste into active buffer
                    CFIndex DateLength = CFDataGetLength(ItemData);
                    size_t StartIndex = strlen(TextBuffer);
                    
                    char NewTempBuffer[g2LabelEdit_TextBufferLength];
                    strcpy(NewTempBuffer, TextBuffer);
                    
                    for(CFIndex i = 0; (i < DateLength) && (StartIndex + i < g2LabelEdit_TextBufferLength); i++)
                    {
                        char byte = *(CFDataGetBytePtr(ItemData) + i);
                        NewTempBuffer[StartIndex + i] = byte;
                    }
                    
                    // Cap string and set to current buffer
                    NewTempBuffer[StartIndex + DateLength] = '\0';
                    SetText(NewTempBuffer);
                    SetCursorPos((int)strlen(NewTempBuffer));
                    
                    // Release
                    CFRelease(ItemData);
                    
                    // Pasted and done!
                    return;
                }
            }
        }
    
    // Not a feature in Linux...
    #endif
}
void HKStringEntryLogic::Update()
{
	bool shiftL = !!MFInput_Read(Key_LShift, IDD_Keyboard);
	bool shiftR = !!MFInput_Read(Key_RShift, IDD_Keyboard);
	bool ctrlL = !!MFInput_Read(Key_LControl, IDD_Keyboard);
	bool ctrlR = !!MFInput_Read(Key_RControl, IDD_Keyboard);

	int keyPressed = 0;

	bool shift = shiftL || shiftR;
	bool ctrl = ctrlL || ctrlR;

#if defined(MF_WINDOWS)
	if(ctrl && MFInput_WasPressed(Key_C, IDD_Keyboard) && selectionStart != selectionEnd)
	{
		BOOL opened = OpenClipboard(apphWnd);

		if(opened)
		{
			int selMin = MFMin(selectionStart, selectionEnd);
			int selMax = MFMax(selectionStart, selectionEnd);

			int numChars = selMax-selMin;

			HANDLE hData = GlobalAlloc(GMEM_MOVEABLE, numChars + 1);
			char *pString = (char*)GlobalLock(hData);

			MFString_Copy(pString, GetRenderString().SubStr(selMin, numChars).CStr());

			GlobalUnlock(hData);

			EmptyClipboard();
			SetClipboardData(CF_TEXT, hData);

			CloseClipboard();
		}
	}
	else if(ctrl && MFInput_WasPressed(Key_X, IDD_Keyboard) && selectionStart != selectionEnd)
	{
		BOOL opened = OpenClipboard(apphWnd);

		if(opened)
		{
			int selMin = MFMin(selectionStart, selectionEnd);
			int selMax = MFMax(selectionStart, selectionEnd);

			int numChars = selMax-selMin;

			HANDLE hData = GlobalAlloc(GMEM_MOVEABLE, numChars + 1);
			char *pString = (char*)GlobalLock(hData);

			MFString_Copy(pString, GetRenderString().SubStr(selMin, numChars).CStr());

			GlobalUnlock(hData);

			EmptyClipboard();
			SetClipboardData(CF_TEXT, hData);

			CloseClipboard();

			ClearSelection();
		}
	}
	else if(ctrl && MFInput_WasPressed(Key_V, IDD_Keyboard))
	{
		BOOL opened = OpenClipboard(apphWnd);

		if(opened)
		{
			int selMin = MFMin(selectionStart, selectionEnd);
			int selMax = MFMax(selectionStart, selectionEnd);

			int numChars = selMax-selMin;

			HANDLE hData = GetClipboardData(CF_TEXT);
			MFString paste((const char*)GlobalLock(hData), true);

			buffer.Replace(selMin, numChars, paste);

			GlobalUnlock(hData);

			cursorPos = selMin + paste.NumBytes();
			selectionStart = selectionEnd = cursorPos;

			GlobalUnlock(hData);

			CloseClipboard();

			if((numChars || cursorPos != selMin) && changeCallback)
				changeCallback(buffer.CStr());
		}
	}
	else
#endif
	{
		// check for new keypresses
		for(int a=0; a<255; a++)
		{
			if(MFInput_WasPressed(a, IDD_Keyboard))
			{
				keyPressed = a;
				holdKey = a;
				repeatDelay = gRepeatDelay;
				break;
			}
		}

		// handle repeat keys
		if(holdKey && MFInput_Read(holdKey, IDD_Keyboard))
		{
			repeatDelay -= MFSystem_TimeDelta();
			if(repeatDelay <= 0.f)
			{
				keyPressed = holdKey;
				repeatDelay += gRepeatRate;
			}
		}
		else
			holdKey = 0;

		// if there was a new key press
		if(keyPressed)
		{
			switch(keyPressed)
			{
				case Key_Backspace:
				case Key_Delete:
				{
					if(selectionStart != selectionEnd)
					{
						ClearSelection();
					}
					else
					{
						if(keyPressed == Key_Backspace && cursorPos > 0)
						{
							buffer.ClearRange(--cursorPos, 1);
							selectionStart = selectionEnd = cursorPos;

							if(changeCallback)
								changeCallback(buffer.CStr());
						}
						else if(keyPressed == Key_Delete && cursorPos < buffer.NumBytes())
						{
							buffer.ClearRange(cursorPos, 1);
							selectionStart = selectionEnd = cursorPos;

							if(changeCallback)
								changeCallback(buffer.CStr());
						}
					}
					break;
				}

				case Key_Left:
				case Key_Right:
				case Key_Home:
				case Key_End:
				{
					if(ctrl)
					{
						if(keyPressed == Key_Left)
						{
							while(cursorPos && MFIsWhite(buffer[cursorPos-1]))
								--cursorPos;
							if(MFIsAlphaNumeric(buffer[cursorPos-1]))
							{
								while(cursorPos && MFIsAlphaNumeric(buffer[cursorPos-1]))
									--cursorPos;
							}
							else if(cursorPos)
							{
								--cursorPos;
								while(cursorPos && buffer[cursorPos-1] == buffer[cursorPos])
									--cursorPos;
							}
						}
						else if(keyPressed == Key_Right)
						{
							while(cursorPos < buffer.NumBytes() && MFIsWhite(buffer[cursorPos]))
								++cursorPos;
							if(MFIsAlphaNumeric(buffer[cursorPos]))
							{
								while(cursorPos < buffer.NumBytes() && MFIsAlphaNumeric(buffer[cursorPos]))
									++cursorPos;
							}
							else if(cursorPos < buffer.NumBytes())
							{
								++cursorPos;
								while(cursorPos < buffer.NumBytes() && buffer[cursorPos] == buffer[cursorPos-1])
									++cursorPos;
							}
						}
						else if(keyPressed == Key_Home)
							cursorPos = 0;
						else if(keyPressed == Key_End)
							cursorPos = buffer.NumBytes();
					}
					else
					{
						if(keyPressed == Key_Left)
							cursorPos = (!shift && selectionStart != selectionEnd ? MFMin(selectionStart, selectionEnd) : MFMax(cursorPos-1, 0));
						else if(keyPressed == Key_Right)
							cursorPos = (!shift && selectionStart != selectionEnd ? MFMax(selectionStart, selectionEnd) : MFMin(cursorPos+1, buffer.NumBytes()));
						else if(keyPressed == Key_Home)
							cursorPos = 0;	// TODO: if multiline, go to start of line..
						else if(keyPressed == Key_End)
							cursorPos = buffer.NumBytes();	// TODO: if multiline, go to end of line...
					}

					if(shift)
						selectionEnd = cursorPos;
					else
						selectionStart = selectionEnd = cursorPos;

					break;
				}

				default:
				{
					bool caps = MFInput_GetKeyboardStatusState(KSS_CapsLock);
					int ascii = MFInput_KeyToAscii(keyPressed, shift, caps);

					if(ascii && (!maxLen || buffer.NumBytes() < maxLen-1))
					{
						// check character exclusions
						if(MFIsNewline(ascii) && type != ST_MultiLine)
							break;
						if(ascii == '\t' && type != ST_MultiLine)
							break;
						if(type == ST_Numeric && !MFIsNumeric(ascii))
							break;
						if(include)
						{
							if(include.FindChar(ascii) < 0)
								break;
						}
						if(exclude)
						{
							if(exclude.FindChar(ascii) >= 0)
								break;
						}

						int selMin = MFMin(selectionStart, selectionEnd);
						int selMax = MFMax(selectionStart, selectionEnd);
						int selRange = selMax - selMin;

						const uint16 wstr[] = { (uint16)ascii, 0 };
						char insert[5];
						MFString_CopyUTF16ToUTF8(insert, wstr);
						buffer.Replace(selMin, selRange, insert);
						cursorPos = selMin + 1;

						selectionStart = selectionEnd = cursorPos;

						if(changeCallback)
							changeCallback(buffer.CStr());
					}
					break;
				}
			}
		}
	}
}
Example #3
0
void SaveClipboard(UINT uFormat, wchar_t **wpData, char **pData)
{
  HGLOBAL hDataSource;
  LPVOID pDataSource;
  int nLen;

  if (OpenClipboard(NULL))
  {
    if (!IsClipboardFormatAvailable(uFormat))
    {
      if (hDataSource=GetClipboardData(CF_UNICODETEXT))
      {
        if (pDataSource=GlobalLock(hDataSource))
        {
          nLen=lstrlenW((wchar_t *)pDataSource + 1) * sizeof(wchar_t);

          if (*wpData)
          {
            GlobalFree((HGLOBAL)*wpData);
            *wpData=NULL;
          }
          if (*pData)
          {
            GlobalFree((HGLOBAL)*pData);
            *pData=NULL;
          }

          if (*wpData=(wchar_t *)GlobalAlloc(GMEM_FIXED, nLen))
          {
            xmemcpy(*wpData, pDataSource, nLen);
          }
          GlobalUnlock(hDataSource);
        }
      }
      else if (hDataSource=GetClipboardData(CF_TEXT))
      {
        if (pDataSource=GlobalLock(hDataSource))
        {
          nLen=lstrlenA((char *)pDataSource) + 1;

          if (*wpData)
          {
            GlobalFree((HGLOBAL)*wpData);
            *wpData=NULL;
          }
          if (*pData)
          {
            GlobalFree((HGLOBAL)*pData);
            *pData=NULL;
          }

          if (*pData=(char *)GlobalAlloc(GMEM_FIXED, nLen))
          {
            xmemcpy(*pData, pDataSource, nLen);
          }
          GlobalUnlock(hDataSource);
        }
      }
    }
    CloseClipboard();
  }
}
/* Capture frame using clipboard.
 * Parameters and return value for this routine matches _camera_device_read_frame
 */
static int
_camera_device_read_frame_clipboard(WndCameraDevice* wcd,
                                    ClientFrameBuffer* framebuffers,
                                    int fbs_num,
                                    float r_scale,
                                    float g_scale,
                                    float b_scale,
                                    float exp_comp)
{
    HBITMAP bm_handle;

    /* Grab a frame, and post it to the clipboard. Not very effective, but this
     * is how capXxx API is operating. */
    if (!capGrabFrameNoStop(wcd->cap_window) ||
        !capEditCopy(wcd->cap_window) ||
        !OpenClipboard(wcd->cap_window)) {
        E("%s: Device '%s' is unable to save frame to the clipboard: %d",
          __FUNCTION__, wcd->window_name, GetLastError());
        return -1;
    }

    /* Get bitmap handle saved into clipboard. Note that bitmap is still
     * owned by the clipboard here! */
    bm_handle = (HBITMAP)GetClipboardData(CF_BITMAP);
    if (bm_handle == NULL) {
        E("%s: Device '%s' is unable to obtain frame from the clipboard: %d",
          __FUNCTION__, wcd->window_name, GetLastError());
        EmptyClipboard();
        CloseClipboard();
        return -1;
    }

    /* Get bitmap buffer. */
    if (wcd->gdi_bitmap->bmiHeader.biHeight > 0) {
        wcd->gdi_bitmap->bmiHeader.biHeight = -wcd->gdi_bitmap->bmiHeader.biHeight;
    }

    if (!GetDIBits(wcd->dc, bm_handle, 0, wcd->frame_bitmap->bmiHeader.biHeight,
                   wcd->framebuffer, wcd->gdi_bitmap, DIB_RGB_COLORS)) {
        E("%s: Device '%s' is unable to transfer frame to the framebuffer: %d",
          __FUNCTION__, wcd->window_name, GetLastError());
        EmptyClipboard();
        CloseClipboard();
        return -1;
    }

    if (wcd->gdi_bitmap->bmiHeader.biHeight < 0) {
        wcd->gdi_bitmap->bmiHeader.biHeight = -wcd->gdi_bitmap->bmiHeader.biHeight;
    }

    EmptyClipboard();
    CloseClipboard();

    /* Convert framebuffer. */
    return convert_frame(wcd->framebuffer,
                         wcd->pixel_format,
                         wcd->gdi_bitmap->bmiHeader.biSizeImage,
                         wcd->frame_bitmap->bmiHeader.biWidth,
                         wcd->frame_bitmap->bmiHeader.biHeight,
                         framebuffers, fbs_num,
                         r_scale, g_scale, b_scale, exp_comp);
}
Example #5
0
HANDLE Clipboard::GetClipboardDataTimeout(UINT uFormat)
// Same as GetClipboardData() except that it doesn't give up if the first call to GetClipboardData() fails.
// Instead, it continues to retry the operation for the number of milliseconds in g_ClipboardTimeout.
// This is necessary because GetClipboardData() has been observed to fail in repeatable situations (this
// is strange because our thread already has the clipboard locked open -- presumably it happens because the
// GetClipboardData() is unable to start a data stream from the application that actually serves up the data).
// If cases where the first call to GetClipboardData() fails, a subsequent call will often succeed if you give
// the owning application (such as Excel and Word) a little time to catch up.  This is especially necessary in
// the OnClipboardChange label, where sometimes a clipboard-change notification comes in before the owning
// app has finished preparing its data for subsequent readers of the clipboard.
{
#ifdef DEBUG_BY_LOGGING_CLIPBOARD_FORMATS  // Provides a convenient log of clipboard formats for analysis.
	static FILE *fp = fopen("c:\\debug_clipboard_formats.txt", "w");
#endif

	TCHAR format_name[MAX_PATH + 1]; // MSDN's RegisterClipboardFormat() doesn't document any max length, but the ones we're interested in certainly don't exceed MAX_PATH.
	if (uFormat < 0xC000 || uFormat > 0xFFFF) // It's a registered format (you're supposed to verify in-range before calling GetClipboardFormatName()).  Also helps performance.
		*format_name = '\0'; // Don't need the name if it's a standard/CF_* format.
	else
	{
		// v1.0.42.04:
		// Probably need to call GetClipboardFormatName() rather than comparing directly to uFormat because
		// MSDN implies that OwnerLink and other registered formats might not always have the same ID under
		// all OSes (past and future).
		GetClipboardFormatName(uFormat, format_name, MAX_PATH);
		// Since RegisterClipboardFormat() is case insensitive, the case might vary.  So use stricmp() when
		// comparing format_name to anything.
		// "Link Source", "Link Source Descriptor" , and anything else starting with "Link Source" is likely
		// to be data that should not be attempted to be retrieved because:
		// 1) It causes unwanted bookmark effects in various versions of MS Word.
		// 2) Tests show that these formats are on the clipboard only if MS Word is open at the time
		//    ClipboardAll is accessed.  That implies they're transitory formats that aren't as essential
		//    or well suited to ClipboardAll as the other formats (but if it weren't for #1 above, this
		//    wouldn't be enough reason to omit it).
		// 3) Although there is hardly any documentation to be found at MSDN or elsewhere about these formats,
		//    it seems they're related to OLE, with further implications that the data is transitory.
		// Here are the formats that Word 2002 removes from the clipboard when it the app closes:
		// 0xC002 ObjectLink  >>> Causes WORD bookmarking problem.
		// 0xC003 OwnerLink
		// 0xC00D Link Source  >>> Causes WORD bookmarking problem.
		// 0xC00F Link Source Descriptor  >>> Doesn't directly cause bookmarking, but probably goes with above.
		// 0xC0DC Hyperlink
		if (   !_tcsnicmp(format_name, _T("Link Source"), 11) || !_tcsicmp(format_name, _T("ObjectLink"))
			|| !_tcsicmp(format_name, _T("OwnerLink"))
			// v1.0.44.07: The following were added to solve interference with MS Outlook's MS Word editor.
			// If a hotkey like ^F1::ClipboardSave:=ClipboardAll is pressed after pressing Ctrl-C in that
			// editor (perhaps only when copying HTML), two of the following error dialogs would otherwise
			// be displayed (this occurs in Outlook 2002 and probably later versions):
			// "An outgoing call cannot be made since the application is dispatching an input-synchronous call."
			|| !_tcsicmp(format_name, _T("Native")) || !_tcsicmp(format_name, _T("Embed Source"))   )
			return NULL;
	}

#ifdef DEBUG_BY_LOGGING_CLIPBOARD_FORMATS
	_ftprintf(fp, _T("%04X\t%s\n"), uFormat, format_name);  // Since fclose() is never called, the program has to exit to close/release the file.
#endif

	HANDLE h;
	for (DWORD start_time = GetTickCount();;)
	{
		// Known failure conditions:
		// GetClipboardData() apparently fails when the text on the clipboard is greater than a certain size
		// (Even though GetLastError() reports "Operation completed successfully").  The data size at which
		// this occurs is somewhere between 20 to 96 MB (perhaps depending on system's memory and CPU speed).
		if (h = GetClipboardData(uFormat)) // Assign
			return h;

		// It failed, so act according to the type of format and the timeout that's in effect.
		// Certain standard (numerically constant) clipboard formats are known to validly yield NULL from a
		// call to GetClipboardData().  Never retry these because it would only cause unnecessary delays
		// (i.e. a failure until timeout).
		// v1.0.42.04: More importantly, retrying them appears to cause problems with saving a Word/Excel
		// clipboard via ClipboardAll.
		if (uFormat == CF_HDROP // This format can fail "normally" for the reasons described at "clipboard_contains_files".
			|| !_tcsicmp(format_name, _T("OwnerLink"))) // Known to validly yield NULL from a call to GetClipboardData(), so don't retry it to avoid having to wait the full timeout period.
			return NULL;

		if (g_ClipboardTimeout != -1) // We were not told to wait indefinitely and...
			if (!g_ClipboardTimeout   // ...we were told to make only one attempt, or ...
				|| (int)(g_ClipboardTimeout - (GetTickCount() - start_time)) <= SLEEP_INTERVAL_HALF) //...it timed out.
				// Above must cast to int or any negative result will be lost due to DWORD type.
				return NULL;

		// Use SLEEP_WITHOUT_INTERRUPTION to prevent MainWindowProc() from accepting new hotkeys
		// during our operation, since a new hotkey subroutine might interfere with
		// what we're doing here (e.g. if it tries to use the clipboard, or perhaps overwrites
		// the deref buffer if this object's caller gave it any pointers into that memory area):
		SLEEP_WITHOUT_INTERRUPTION(INTERVAL_UNSPECIFIED)
	}
}
Example #6
0
intptr_t CL_UISystemCalls( intptr_t *args ) {
	switch ( args[0] ) {
		//rww - alright, DO NOT EVER add a GAME/CGAME/UI generic call without adding a trap to match, and
		//all of these traps must be shared and have cases in sv_game, cl_cgame, and cl_ui. They must also
		//all be in the same order, and start at 100.
	case TRAP_MEMSET:
		Com_Memset( VMA(1), args[2], args[3] );
		return 0;

	case TRAP_MEMCPY:
		Com_Memcpy( VMA(1), VMA(2), args[3] );
		return 0;

	case TRAP_STRNCPY:
		strncpy( (char *)VMA(1), (const char *)VMA(2), args[3] );
		return args[1];

	case TRAP_SIN:
		return FloatAsInt( sin( VMF(1) ) );

	case TRAP_COS:
		return FloatAsInt( cos( VMF(1) ) );

	case TRAP_ATAN2:
		return FloatAsInt( atan2( VMF(1), VMF(2) ) );

	case TRAP_SQRT:
		return FloatAsInt( sqrt( VMF(1) ) );

	case TRAP_MATRIXMULTIPLY:
		MatrixMultiply( (vec3_t *)VMA(1), (vec3_t *)VMA(2), (vec3_t *)VMA(3) );
		return 0;

	case TRAP_ANGLEVECTORS:
		AngleVectors( (const float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4) );
		return 0;

	case TRAP_PERPENDICULARVECTOR:
		PerpendicularVector( (float *)VMA(1), (const float *)VMA(2) );
		return 0;

	case TRAP_FLOOR:
		return FloatAsInt( floor( VMF(1) ) );

	case TRAP_CEIL:
		return FloatAsInt( ceil( VMF(1) ) );

	case TRAP_TESTPRINTINT:
		return 0;

	case TRAP_TESTPRINTFLOAT:
		return 0;

	case TRAP_ACOS:
		return FloatAsInt( Q_acos( VMF(1) ) );

	case TRAP_ASIN:
		return FloatAsInt( Q_asin( VMF(1) ) );

	case UI_ERROR:
		Com_Error( ERR_DROP, "%s", VMA(1) );
		return 0;

	case UI_PRINT:
		Com_Printf( "%s", VMA(1) );
		return 0;

	case UI_MILLISECONDS:
		return Sys_Milliseconds();

	case UI_CVAR_REGISTER:
		Cvar_Register( (vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4] ); 
		return 0;

	case UI_CVAR_UPDATE:
		Cvar_Update( (vmCvar_t *)VMA(1) );
		return 0;

	case UI_CVAR_SET:
		Cvar_VM_Set( (const char *)VMA(1), (const char *)VMA(2), VM_UI );
		return 0;

	case UI_CVAR_VARIABLEVALUE:
		return FloatAsInt( Cvar_VariableValue( (const char *)VMA(1) ) );

	case UI_CVAR_VARIABLESTRINGBUFFER:
		Cvar_VariableStringBuffer( (const char *)VMA(1), (char *)VMA(2), args[3] );
		return 0;

	case UI_CVAR_SETVALUE:
		Cvar_VM_SetValue( (const char *)VMA(1), VMF(2), VM_UI );
		return 0;

	case UI_CVAR_RESET:
		Cvar_Reset( (const char *)VMA(1) );
		return 0;

	case UI_CVAR_CREATE:
		Cvar_Get( (const char *)VMA(1), (const char *)VMA(2), args[3] );
		return 0;

	case UI_CVAR_INFOSTRINGBUFFER:
		Cvar_InfoStringBuffer( args[1], (char *)VMA(2), args[3] );
		return 0;

	case UI_ARGC:
		return Cmd_Argc();

	case UI_ARGV:
		Cmd_ArgvBuffer( args[1], (char *)VMA(2), args[3] );
		return 0;

	case UI_CMD_EXECUTETEXT:
		Cbuf_ExecuteText( args[1], (const char *)VMA(2) );
		return 0;

	case UI_FS_FOPENFILE:
		return FS_FOpenFileByMode( (const char *)VMA(1), (int *)VMA(2), (fsMode_t)args[3] );

	case UI_FS_READ:
		FS_Read( VMA(1), args[2], args[3] );
		return 0;

	case UI_FS_WRITE:
		FS_Write( VMA(1), args[2], args[3] );
		return 0;

	case UI_FS_FCLOSEFILE:
		FS_FCloseFile( args[1] );
		return 0;

	case UI_FS_GETFILELIST:
		return FS_GetFileList( (const char *)VMA(1), (const char *)VMA(2), (char *)VMA(3), args[4] );

	case UI_R_REGISTERMODEL:
		return re->RegisterModel( (const char *)VMA(1) );

	case UI_R_REGISTERSKIN:
		return re->RegisterSkin( (const char *)VMA(1) );

	case UI_R_REGISTERSHADERNOMIP:
		return re->RegisterShaderNoMip( (const char *)VMA(1) );

	case UI_R_SHADERNAMEFROMINDEX:
		CL_R_ShaderNameFromIndex( (char *)VMA(1), args[2] );
		return 0;

	case UI_R_CLEARSCENE:
		re->ClearScene();
		return 0;

	case UI_R_ADDREFENTITYTOSCENE:
		re->AddRefEntityToScene( (const refEntity_t *)VMA(1) );
		return 0;

	case UI_R_ADDPOLYTOSCENE:
		re->AddPolyToScene( args[1], args[2], (const polyVert_t *)VMA(3), 1 );
		return 0;

	case UI_R_ADDLIGHTTOSCENE:
		re->AddLightToScene( (const float *)VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) );
		return 0;

	case UI_R_RENDERSCENE:
		re->RenderScene( (const refdef_t *)VMA(1) );
		return 0;

	case UI_R_SETCOLOR:
		re->SetColor( (const float *)VMA(1) );
		return 0;

	case UI_R_DRAWSTRETCHPIC:
		re->DrawStretchPic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9] );
		return 0;

	case UI_R_MODELBOUNDS:
		re->ModelBounds( args[1], (float *)VMA(2), (float *)VMA(3) );
		return 0;

	case UI_UPDATESCREEN:
		SCR_UpdateScreen();
		return 0;

	case UI_CM_LERPTAG:
		re->LerpTag( (orientation_t *)VMA(1), args[2], args[3], args[4], VMF(5), (const char *)VMA(6) );
		return 0;

	case UI_S_REGISTERSOUND:
		return S_RegisterSound( (const char *)VMA(1) );

	case UI_S_STARTLOCALSOUND:
		S_StartLocalSound( args[1], args[2] );
		return 0;

	case UI_KEY_KEYNUMTOSTRINGBUF:
		Key_KeynumToStringBuf( args[1], (char *)VMA(2), args[3] );
		return 0;

	case UI_KEY_GETBINDINGBUF:
		Key_GetBindingBuf( args[1], (char *)VMA(2), args[3] );
		return 0;

	case UI_KEY_SETBINDING:
		Key_SetBinding( args[1], (const char *)VMA(2) );
		return 0;

	case UI_KEY_ISDOWN:
		return Key_IsDown( args[1] );

	case UI_KEY_GETOVERSTRIKEMODE:
		return Key_GetOverstrikeMode();

	case UI_KEY_SETOVERSTRIKEMODE:
		Key_SetOverstrikeMode( (qboolean)args[1] );
		return 0;

	case UI_KEY_CLEARSTATES:
		Key_ClearStates();
		return 0;

	case UI_KEY_GETCATCHER:
		return Key_GetCatcher();

	case UI_KEY_SETCATCHER:
		CL_Key_SetCatcher( args[1] );
		return 0;

	case UI_GETCLIPBOARDDATA:
		GetClipboardData( (char *)VMA(1), args[2] );
		return 0;

	case UI_GETCLIENTSTATE:
		CL_GetClientState( (uiClientState_t *)VMA(1) );
		return 0;		

	case UI_GETGLCONFIG:
		CL_GetGlconfig( (glconfig_t *)VMA(1) );
		return 0;

	case UI_GETCONFIGSTRING:
		return GetConfigString( args[1], (char *)VMA(2), args[3] );

	case UI_LAN_LOADCACHEDSERVERS:
		LAN_LoadCachedServers();
		return 0;

	case UI_LAN_SAVECACHEDSERVERS:
		LAN_SaveServersToCache();
		return 0;

	case UI_LAN_ADDSERVER:
		return LAN_AddServer(args[1], (const char *)VMA(2), (const char *)VMA(3));

	case UI_LAN_REMOVESERVER:
		LAN_RemoveServer(args[1], (const char *)VMA(2));
		return 0;

	case UI_LAN_GETPINGQUEUECOUNT:
		return LAN_GetPingQueueCount();

	case UI_LAN_CLEARPING:
		LAN_ClearPing( args[1] );
		return 0;

	case UI_LAN_GETPING:
		LAN_GetPing( args[1], (char *)VMA(2), args[3], (int *)VMA(4) );
		return 0;

	case UI_LAN_GETPINGINFO:
		LAN_GetPingInfo( args[1], (char *)VMA(2), args[3] );
		return 0;

	case UI_LAN_GETSERVERCOUNT:
		return LAN_GetServerCount(args[1]);

	case UI_LAN_GETSERVERADDRESSSTRING:
		LAN_GetServerAddressString( args[1], args[2], (char *)VMA(3), args[4] );
		return 0;

	case UI_LAN_GETSERVERINFO:
		LAN_GetServerInfo( args[1], args[2], (char *)VMA(3), args[4] );
		return 0;

	case UI_LAN_GETSERVERPING:
		return LAN_GetServerPing( args[1], args[2] );

	case UI_LAN_MARKSERVERVISIBLE:
		LAN_MarkServerVisible( args[1], args[2], (qboolean)args[3] );
		return 0;

	case UI_LAN_SERVERISVISIBLE:
		return LAN_ServerIsVisible( args[1], args[2] );

	case UI_LAN_UPDATEVISIBLEPINGS:
		return LAN_UpdateVisiblePings( args[1] );

	case UI_LAN_RESETPINGS:
		LAN_ResetPings( args[1] );
		return 0;

	case UI_LAN_SERVERSTATUS:
		return LAN_GetServerStatus( (char *)VMA(1), (char *)VMA(2), args[3] );

	case UI_LAN_COMPARESERVERS:
		return LAN_CompareServers( args[1], args[2], args[3], args[4], args[5] );

	case UI_MEMORY_REMAINING:
		return Hunk_MemoryRemaining();

	case UI_R_REGISTERFONT:
		return re->RegisterFont( (const char *)VMA(1) );

	case UI_R_FONT_STRLENPIXELS:
		return re->Font_StrLenPixels( (const char *)VMA(1), args[2], VMF(3) );

	case UI_R_FONT_STRLENCHARS:
		return re->Font_StrLenChars( (const char *)VMA(1) );

	case UI_R_FONT_STRHEIGHTPIXELS:
		return re->Font_HeightPixels( args[1], VMF(2) );

	case UI_R_FONT_DRAWSTRING:
		re->Font_DrawString( args[1], args[2], (const char *)VMA(3), (const float *) VMA(4), args[5], args[6], VMF(7) );
		return 0;

	case UI_LANGUAGE_ISASIAN:
		return re->Language_IsAsian();

	case UI_LANGUAGE_USESSPACES:
		return re->Language_UsesSpaces();

	case UI_ANYLANGUAGE_READCHARFROMSTRING:
		return re->AnyLanguage_ReadCharFromString( (const char *)VMA(1), (int *) VMA(2), (qboolean *) VMA(3) );

	case UI_PC_ADD_GLOBAL_DEFINE:
		return botlib_export->PC_AddGlobalDefine( (char *)VMA(1) );

	case UI_PC_LOAD_SOURCE:
		return botlib_export->PC_LoadSourceHandle( (const char *)VMA(1) );

	case UI_PC_FREE_SOURCE:
		return botlib_export->PC_FreeSourceHandle( args[1] );

	case UI_PC_READ_TOKEN:
		return botlib_export->PC_ReadTokenHandle( args[1], (struct pc_token_s *)VMA(2) );

	case UI_PC_SOURCE_FILE_AND_LINE:
		return botlib_export->PC_SourceFileAndLine( args[1], (char *)VMA(2), (int *)VMA(3) );

	case UI_PC_LOAD_GLOBAL_DEFINES:
		return botlib_export->PC_LoadGlobalDefines ( (char *)VMA(1) );

	case UI_PC_REMOVE_ALL_GLOBAL_DEFINES:
		botlib_export->PC_RemoveAllGlobalDefines ( );
		return 0;

	case UI_S_STOPBACKGROUNDTRACK:
		S_StopBackgroundTrack();
		return 0;

	case UI_S_STARTBACKGROUNDTRACK:
		S_StartBackgroundTrack( (const char *)VMA(1), (const char *)VMA(2), qfalse );
		return 0;

	case UI_REAL_TIME:
		return Com_RealTime( (struct qtime_s *)VMA(1) );

	case UI_CIN_PLAYCINEMATIC:
		Com_DPrintf("UI_CIN_PlayCinematic\n");
		return CIN_PlayCinematic((const char *)VMA(1), args[2], args[3], args[4], args[5], args[6]);

	case UI_CIN_STOPCINEMATIC:
		return CIN_StopCinematic(args[1]);

	case UI_CIN_RUNCINEMATIC:
		return CIN_RunCinematic(args[1]);

	case UI_CIN_DRAWCINEMATIC:
		CIN_DrawCinematic(args[1]);
		return 0;

	case UI_CIN_SETEXTENTS:
		CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]);
		return 0;

	case UI_R_REMAP_SHADER:
		re->RemapShader( (const char *)VMA(1), (const char *)VMA(2), (const char *)VMA(3) );
		return 0;

	case UI_SP_GETNUMLANGUAGES:
		return SE_GetNumLanguages();

	case UI_SP_GETLANGUAGENAME:
		CL_SE_GetLanguageName( args[1], (char *)VMA(2) );
		return 0;

	case UI_SP_GETSTRINGTEXTSTRING:
		return CL_SE_GetStringTextString( (const char *)VMA(1), (char *)VMA(2), args[3] );

	case UI_G2_LISTSURFACES:
		re->G2API_ListSurfaces( (CGhoul2Info *) args[1] );
		return 0;

	case UI_G2_LISTBONES:
		re->G2API_ListBones( (CGhoul2Info *) args[1], args[2]);
		return 0;

	case UI_G2_HAVEWEGHOULMODELS:
		return re->G2API_HaveWeGhoul2Models( *((CGhoul2Info_v *)args[1]) );

	case UI_G2_SETMODELS:
		re->G2API_SetGhoul2ModelIndexes( *((CGhoul2Info_v *)args[1]),(qhandle_t *)VMA(2),(qhandle_t *)VMA(3));
		return 0;

	case UI_G2_GETBOLT:
		return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)args[1]), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9));

	case UI_G2_GETBOLT_NOREC:
		re->G2API_BoltMatrixReconstruction( qfalse );//gG2_GBMNoReconstruct = qtrue;
		return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)args[1]), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9));

	case UI_G2_GETBOLT_NOREC_NOROT:
		// cgame reconstructs bolt matrix, why is this different?
		re->G2API_BoltMatrixReconstruction( qfalse );//gG2_GBMNoReconstruct = qtrue;
		re->G2API_BoltMatrixSPMethod( qtrue );//gG2_GBMUseSPMethod = qtrue;
		return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)args[1]), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9));

	case UI_G2_INITGHOUL2MODEL:
#ifdef _FULL_G2_LEAK_CHECKING
		g_G2AllocServer = 0;
#endif
		return	re->G2API_InitGhoul2Model((CGhoul2Info_v **)VMA(1), (const char *)VMA(2), args[3], (qhandle_t) args[4], (qhandle_t) args[5], args[6], args[7]);

	case UI_G2_COLLISIONDETECT:
	case UI_G2_COLLISIONDETECTCACHE:
		return 0; //not supported for ui

	case UI_G2_ANGLEOVERRIDE:
		return re->G2API_SetBoneAngles(*((CGhoul2Info_v *)args[1]), args[2], (const char *)VMA(3), (float *)VMA(4), args[5], (const Eorientations) args[6], (const Eorientations) args[7], (const Eorientations) args[8], (qhandle_t *)VMA(9), args[10], args[11] );

	case UI_G2_CLEANMODELS:
#ifdef _FULL_G2_LEAK_CHECKING
		g_G2AllocServer = 0;
#endif
		re->G2API_CleanGhoul2Models((CGhoul2Info_v **)VMA(1));
		//	re->G2API_CleanGhoul2Models((CGhoul2Info_v **)args[1]);
		return 0;

	case UI_G2_PLAYANIM:
		return re->G2API_SetBoneAnim(*((CGhoul2Info_v *)args[1]), args[2], (const char *)VMA(3), args[4], args[5], args[6], VMF(7), args[8], VMF(9), args[10]);

	case UI_G2_GETBONEANIM:
		{
			CGhoul2Info_v &g2 = *((CGhoul2Info_v *)args[1]);
			int modelIndex = args[10];

			return re->G2API_GetBoneAnim(&g2[modelIndex], (const char*)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), (int *)VMA(6), (int *)VMA(7), (float *)VMA(8), (int *)VMA(9));
		}

	case UI_G2_GETBONEFRAME:
		{ //rwwFIXMEFIXME: Just make a G2API_GetBoneFrame func too. This is dirty.
			CGhoul2Info_v &g2 = *((CGhoul2Info_v *)args[1]);
			int modelIndex = args[6];
			int iDontCare1 = 0, iDontCare2 = 0, iDontCare3 = 0;
			float fDontCare1 = 0;

			return re->G2API_GetBoneAnim(&g2[modelIndex], (const char*)VMA(2), args[3], (float *)VMA(4), &iDontCare1, &iDontCare2, &iDontCare3, &fDontCare1, (int *)VMA(5));
		}

	case UI_G2_GETGLANAME:
		//	return (int)G2API_GetGLAName(*((CGhoul2Info_v *)VMA(1)), args[2]);
		{
			char *point = ((char *)VMA(3));
			char *local;
			local = re->G2API_GetGLAName(*((CGhoul2Info_v *)args[1]), args[2]);
			if (local)
			{
				strcpy(point, local);
			}
		}
		return 0;

	case UI_G2_COPYGHOUL2INSTANCE:
		return (int)re->G2API_CopyGhoul2Instance(*((CGhoul2Info_v *)args[1]), *((CGhoul2Info_v *)args[2]), args[3]);

	case UI_G2_COPYSPECIFICGHOUL2MODEL:
		re->G2API_CopySpecificG2Model(*((CGhoul2Info_v *)args[1]), args[2], *((CGhoul2Info_v *)args[3]), args[4]);
		return 0;

	case UI_G2_DUPLICATEGHOUL2INSTANCE:
#ifdef _FULL_G2_LEAK_CHECKING
		g_G2AllocServer = 0;
#endif
		re->G2API_DuplicateGhoul2Instance(*((CGhoul2Info_v *)args[1]), (CGhoul2Info_v **)VMA(2));
		return 0;

	case UI_G2_HASGHOUL2MODELONINDEX:
		return (int)re->G2API_HasGhoul2ModelOnIndex((CGhoul2Info_v **)VMA(1), args[2]);
		//return (int)G2API_HasGhoul2ModelOnIndex((CGhoul2Info_v **)args[1], args[2]);

	case UI_G2_REMOVEGHOUL2MODEL:
#ifdef _FULL_G2_LEAK_CHECKING
		g_G2AllocServer = 0;
#endif
		return (int)re->G2API_RemoveGhoul2Model((CGhoul2Info_v **)VMA(1), args[2]);
		//return (int)G2API_RemoveGhoul2Model((CGhoul2Info_v **)args[1], args[2]);

	case UI_G2_ADDBOLT:
		return re->G2API_AddBolt(*((CGhoul2Info_v *)args[1]), args[2], (const char *)VMA(3));

	case UI_G2_SETBOLTON:
		re->G2API_SetBoltInfo(*((CGhoul2Info_v *)args[1]), args[2], args[3]);
		return 0;

	case UI_G2_SETROOTSURFACE:
		return re->G2API_SetRootSurface(*((CGhoul2Info_v *)args[1]), args[2], (const char *)VMA(3));

	case UI_G2_SETSURFACEONOFF:
		return re->G2API_SetSurfaceOnOff(*((CGhoul2Info_v *)args[1]), (const char *)VMA(2), /*(const int)VMA(3)*/args[3]);

	case UI_G2_SETNEWORIGIN:
		return re->G2API_SetNewOrigin(*((CGhoul2Info_v *)args[1]), /*(const int)VMA(2)*/args[2]);

	case UI_G2_GETTIME:
		return re->G2API_GetTime(0);

	case UI_G2_SETTIME:
		re->G2API_SetTime(args[1], args[2]);
		return 0;

	case UI_G2_SETRAGDOLL:
		return 0; //not supported for ui
		break;

	case UI_G2_ANIMATEG2MODELS:
		return 0; //not supported for ui
		break;

	case UI_G2_SETBONEIKSTATE:
		return re->G2API_SetBoneIKState(*((CGhoul2Info_v *)args[1]), args[2], (const char *)VMA(3), args[4], (sharedSetBoneIKStateParams_t *)VMA(5));

	case UI_G2_IKMOVE:
		return re->G2API_IKMove(*((CGhoul2Info_v *)args[1]), args[2], (sharedIKMoveParams_t *)VMA(3));

	case UI_G2_GETSURFACENAME:
		{ //Since returning a pointer in such a way to a VM seems to cause MASSIVE FAILURE<tm>, we will shove data into the pointer the vm passes instead
			char *point = ((char *)VMA(4));
			char *local;
			int modelindex = args[3];

			CGhoul2Info_v &g2 = *((CGhoul2Info_v *)args[1]);

			local = re->G2API_GetSurfaceName(&g2[modelindex], args[2]);
			if (local)
			{
				strcpy(point, local);
			}
		}

		return 0;
	case UI_G2_SETSKIN:
		{
			CGhoul2Info_v &g2 = *((CGhoul2Info_v *)args[1]);
			int modelIndex = args[2];

			return re->G2API_SetSkin(&g2[modelIndex], args[3], args[4]);
		}

	case UI_G2_ATTACHG2MODEL:
		{
			CGhoul2Info_v *g2From = ((CGhoul2Info_v *)args[1]);
			CGhoul2Info_v *g2To = ((CGhoul2Info_v *)args[3]);

			return re->G2API_AttachG2Model(*g2From, args[2], *g2To, args[4], args[5]);
		}

	default:
		Com_Error( ERR_DROP, "Bad UI system trap: %ld", (long int) args[0] );

	}

	return 0;
}
Example #7
0
static int InputMenuPopup(WPARAM, LPARAM lParam)
{
	HMENU hSubMenu = NULL;
	int i = 0;
	MessageWindowPopupData * mwpd = (MessageWindowPopupData *)lParam;
	if (mwpd->uFlags == MSG_WINDOWPOPUP_LOG || !g_bQuickMenu || !QuickList->realCount) return 0;

	if (mwpd->uType == MSG_WINDOWPOPUP_SHOWING) {
		hSubMenu = CreatePopupMenu();

		InsertMenu((HMENU)mwpd->hMenu, 6, MF_STRING | MF_POPUP | MF_BYPOSITION, (UINT_PTR)hSubMenu, TranslateT("Quick Messages"));
		InsertMenu((HMENU)mwpd->hMenu, 7, MF_SEPARATOR | MF_BYPOSITION, 0, 0);
		qsort(QuickList->items, QuickList->realCount, sizeof(QuickData *), sstQuickSortButtons);
		for (i = 0; i < QuickList->realCount; i++) {
			QuickData* qd = (QuickData *)QuickList->items[i];
			if (qd->fEntryType&QMF_EX_SEPARATOR)
				AppendMenu(hSubMenu, MF_SEPARATOR, 0, NULL);
			else
				AppendMenu(hSubMenu, MF_STRING, qd->dwPos + 254, qd->ptszValueName);
		}
	}
	else if (mwpd->uType == MSG_WINDOWPOPUP_SELECTED&&mwpd->selection >= 254) {
		for (i = 0; i < QuickList->realCount; i++) {
			QuickData* qd = (QuickData *)QuickList->items[i];
			if ((qd->dwPos + 254) == mwpd->selection) {
				CHARRANGE cr;
				UINT textlenght = 0;
				TCHAR* pszText = NULL;
				TCHAR* ptszQValue = NULL;
				TCHAR* pszCBText = NULL;
				BOOL bIsService = 0;

				if (IsClipboardFormatAvailable(CF_TEXT)) {
					if (OpenClipboard(mwpd->hwnd)) {
						HANDLE hData = NULL;
						TCHAR* chBuffer = NULL;
						int textLength = 0;

						hData = GetClipboardData(CF_UNICODETEXT);

						chBuffer = (TCHAR*)GlobalLock(hData);
						textLength = (int)mir_tstrlen(chBuffer);
						pszCBText = mir_tstrdup(chBuffer);
						GlobalUnlock(hData);
						CloseClipboard();
					}
				}

				SendMessage(mwpd->hwnd, EM_EXGETSEL, 0, (LPARAM)&cr);
				textlenght = cr.cpMax - cr.cpMin;

				if (textlenght) {
					pszText = (TCHAR *)mir_alloc((textlenght + 10)*sizeof(TCHAR));
					memset(pszText, 0, ((textlenght + 10) * sizeof(TCHAR)));
					SendMessage(mwpd->hwnd, EM_GETSELTEXT, 0, (LPARAM)pszText);
				}
				if (qd->ptszValue) {
					ptszQValue = ParseString(mwpd->hContact, qd->ptszValue, pszText ? pszText : _T(""), pszCBText ? pszCBText : _T(""), (int)mir_tstrlen(qd->ptszValue), textlenght, pszCBText ? (int)mir_tstrlen(pszCBText) : 0);
					if ((bIsService = qd->bIsService) && ptszQValue)

						CallService(mir_u2a(ptszQValue), (WPARAM)mwpd->hContact, 0);

				}

				if (ptszQValue)
					SendMessage(mwpd->hwnd, EM_REPLACESEL, TRUE, (LPARAM)ptszQValue);

				if (pszText) mir_free(pszText);
				if (ptszQValue) free(ptszQValue);
				if (pszCBText) mir_free(pszCBText);
				break;
			}
		}
		return 1;
	}
	return 0;
}
Example #8
0
File: cdwclp.c Project: LuaDist/cd
/* 
%F cdPlay para Clipboard.
Interpreta os dados do clipboard, seja metafile ou bitmap.
*/
static int cdplay(cdCanvas* canvas, int xmin, int xmax, int ymin, int ymax, void *data)
{
  char filename[10240]; 
  HANDLE hFile;
  DWORD dwSize, nBytesWrite;
  int err;
  unsigned char* buffer;
  (void)data;
  
  if (IsClipboardFormatAvailable(CF_TEXT))
  {
    HANDLE Handle;
    
    if (!cdStrTmpFileName(filename))
      return CD_ERROR;
    
    OpenClipboard(NULL);
    Handle = GetClipboardData(CF_TEXT);
    if (Handle == NULL)
    {
      CloseClipboard();
      return CD_ERROR;
    }
    
    buffer = (unsigned char*)GlobalLock(Handle);
    dwSize = (DWORD)GlobalSize(Handle); 
    
    hFile = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    WriteFile(hFile, buffer, dwSize, &nBytesWrite, NULL);
    CloseHandle(hFile);
    
    GlobalUnlock(Handle);
    
    CloseClipboard();
    
    err = cdCanvasPlay(canvas, CD_METAFILE, xmin, xmax, ymin, ymax, filename);
    
    DeleteFile(filename);
    
    if (err == CD_OK)
      return err;
  }
  
  if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
  {
    HENHMETAFILE Handle;
    
    if (!cdStrTmpFileName(filename))
      return CD_ERROR;
    
    OpenClipboard(NULL);
    Handle = (HENHMETAFILE)GetClipboardData(CF_ENHMETAFILE);
    if (Handle == NULL)
    {
      CloseClipboard();
      return CD_ERROR;
    }
    
    dwSize = GetEnhMetaFileBits(Handle, 0, NULL);
    
    buffer = (unsigned char*)malloc(dwSize);
    
    GetEnhMetaFileBits(Handle, dwSize, buffer);
    
    hFile = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    WriteFile(hFile, buffer, dwSize, &nBytesWrite, NULL);
    CloseHandle(hFile);
    
    free(buffer);
    
    CloseClipboard();
    
    err = cdCanvasPlay(canvas, CD_EMF, xmin, xmax, ymin, ymax, filename);
    
    DeleteFile(filename);
    
    return err;
  }
  
  if (IsClipboardFormatAvailable(CF_METAFILEPICT))
  {
    HANDLE Handle;
    METAFILEPICT* lpMFP;
    
    if (!cdStrTmpFileName(filename))
      return CD_ERROR;
    
    OpenClipboard(NULL);
    Handle = GetClipboardData(CF_METAFILEPICT);
    if (Handle == NULL)
    {
      CloseClipboard();
      return CD_ERROR;
    }
    
    lpMFP = (METAFILEPICT*) GlobalLock(Handle);
    
    dwSize = GetMetaFileBitsEx(lpMFP->hMF, 0, NULL);
    buffer = (unsigned char*)malloc(dwSize);
    
    GetMetaFileBitsEx(lpMFP->hMF, dwSize, buffer);
    
    hFile = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    wmfWritePlacebleFile(hFile, buffer, dwSize, lpMFP->mm, lpMFP->xExt, lpMFP->yExt);
    CloseHandle(hFile);
    
    GlobalUnlock(Handle);
    free(buffer);
    
    CloseClipboard();
    
    err = cdCanvasPlay(canvas, CD_WMF, xmin, xmax, ymin, ymax, filename);
    
    DeleteFile(filename);
    
    return err;
  }
  
  if (IsClipboardFormatAvailable(CF_DIB))
  {
    HANDLE Handle;
    int size;
    cdwDIB dib;
    
    OpenClipboard(NULL);
    Handle = GetClipboardData(CF_DIB);
    if (Handle == NULL)
    {
      CloseClipboard();
      return CD_ERROR;
    }
    
    cdwDIBReference(&dib, (BYTE*) GlobalLock(Handle), NULL);
    
    if (dib.type == -1)
    {
      GlobalUnlock(Handle);
      CloseClipboard();
      return CD_ERROR;
    }
    
    if (cdsizecb)
    {
      int err;
      err = cdsizecb(canvas, dib.w, dib.h, dib.w, dib.h);
      if (err)
      {
        GlobalUnlock(Handle);
        CloseClipboard();
        return CD_ERROR;
      }
    }
    
    size = dib.w*dib.h;
    
    if (xmax == 0) xmax = dib.w + xmin - 1;
    if (ymax == 0) ymax = dib.h + ymin - 1;
      
    if (dib.type == 0)
    {
      unsigned char *r, *g, *b;
      
      r = (unsigned char*)malloc(size);
      g = (unsigned char*)malloc(size);
      b = (unsigned char*)malloc(size);
      
      cdwDIBDecodeRGB(&dib, r, g, b);

      cdCanvasPutImageRectRGB(canvas, dib.w, dib.h, r, g, b, xmin, ymin, xmax - xmin + 1, ymax - ymin + 1, 0, 0, 0, 0);
      
      free(r);
      free(g);
      free(b);
    }
    else
    {
      unsigned char *index;
      long *colors;
      
      index = (unsigned char*)malloc(size);
      colors = (long*)malloc(256*sizeof(long));
      
      cdwDIBDecodeMap(&dib, index, colors);
      
      cdCanvasPutImageRectMap(canvas, dib.w, dib.h, index, colors, xmin, ymin, xmax - xmin + 1, ymax - ymin + 1, 0, 0, 0, 0);
      
      free(index);
      free(colors);
    }
    
    GlobalUnlock(Handle);
    
    CloseClipboard();
    
    return CD_ERROR;
  }
  
  if (IsClipboardFormatAvailable(CF_BITMAP))
  {
    HBITMAP Handle;
    int size, type;
    cdwDIB dib;
    HDC ScreenDC;
    SIZE sz;
    
    OpenClipboard(NULL);
    Handle = GetClipboardData(CF_BITMAP);
    if (Handle == NULL)
    {
      CloseClipboard();
      return CD_ERROR;
    }
    
    GetBitmapDimensionEx(Handle, &sz);
    
    ScreenDC = GetDC(NULL);
    if (GetDeviceCaps(ScreenDC, BITSPIXEL) > 8)
      type = 0;
    else
      type = 1;
    
    dib.w = sz.cx;
    dib.h = sz.cy;
    dib.type = type; 
    
    if (cdsizecb)
    {
      int err;
      err = cdsizecb(canvas, dib.w, dib.h, dib.w, dib.h);
      if (err)
      {
        ReleaseDC(NULL, ScreenDC);
        CloseClipboard();
        return CD_ERROR;
      }
    }
    
    cdwCreateDIB(&dib);
    
    GetDIBits(ScreenDC, Handle, 0, sz.cy, dib.bits, dib.bmi, DIB_RGB_COLORS);	
    ReleaseDC(NULL, ScreenDC);
    
    size = dib.w*dib.h;
    
    if (dib.type == 0)
    {
      unsigned char *r, *g, *b;
      
      r = (unsigned char*)malloc(size);
      g = (unsigned char*)malloc(size);
      b = (unsigned char*)malloc(size);
      
      cdwDIBDecodeRGB(&dib, r, g, b);
      
      cdCanvasPutImageRectRGB(canvas, dib.w, dib.h, r, g, b, 0, 0, dib.w, dib.h, 0, 0, 0, 0);
      
      free(r);
      free(g);
      free(b);
    }
    else
    {
      unsigned char *index;
      long *colors;
      
      index = (unsigned char*)malloc(size);
      colors = (long*)malloc(256*sizeof(long));
      
      cdwDIBDecodeMap(&dib, index, colors);
      
      cdCanvasPutImageRectMap(canvas, dib.w, dib.h, index, colors, 0, 0, dib.w, dib.h, 0, 0, 0, 0);
      
      free(index);
      free(colors);
    }
    
    cdwKillDIB(&dib);
    
    CloseClipboard();
    
    return CD_ERROR;
  }
  
  return CD_ERROR;
}
static PyObject *
py_get_clipboard_data(PyObject* self, PyObject* args)
{

  PyObject *ret;

  // @pyparm int|format|CF_TEXT|Specifies a clipboard format. For a description of
  // the standard clipboard formats, see Standard Clipboard Formats.
  // In Unicode builds (ie, python 3k), the default is CF_UNICODETEXT.
#ifdef UNICODE
  int format = CF_UNICODETEXT;
#else
  int format = CF_TEXT;
#endif
  if (!PyArg_ParseTuple(args, "|i:GetClipboardData:",
                        &format)) {
    return NULL;
  }

  if (!IsClipboardFormatAvailable(format)){
      PyErr_SetString(PyExc_TypeError, "Specified clipboard format is not available");
      return NULL;
  }
  HANDLE handle;
  WCHAR *filename=NULL;
  PyObject* obfilename = NULL;
  UINT filecnt=0, fileind=0, filenamesize=0;
  HDROP hdrop;
  Py_BEGIN_ALLOW_THREADS;
  handle = GetClipboardData((UINT)format);
  Py_END_ALLOW_THREADS;


  if (!handle) {
    return ReturnAPIError("GetClipboardData");
  }

  void * cData = NULL;
  size_t size;
  DWORD dwordsize;
  switch (format) {
    case CF_BITMAP:
      break;
    case CF_HDROP:
		hdrop = (HDROP)GlobalLock(handle);
        break;
    case CF_ENHMETAFILE:
      dwordsize = GetEnhMetaFileBits((HENHMETAFILE)handle, 0, NULL);
      if (!dwordsize)
        return ReturnAPIError("GetClipboardData:GetEnhMetafileBits(NULL)");
      // allocate a temporary buffer for enhanced metafile
      cData = malloc(dwordsize);
      if (cData == NULL)
        return ReturnAPIError("GetClipboardData:malloc");
      // copy enhanced metafile into the temporary buffer
      if (0 == GetEnhMetaFileBits((HENHMETAFILE)handle, dwordsize, (LPBYTE)cData)) {
        free(cData);
        return ReturnAPIError("GetClipboardData:GetEnhMetafileBits");
      }
	  size=dwordsize;
      break;
    case CF_METAFILEPICT:
      // @todo CF_METAFILEPICT format returns a pointer to a METAFILEPICT struct which contains the metafile handle,
      //	rather than returning the handle directly.  This code currently fails with
      //	error: (6, 'GetClipboardData:GetMetafileBitsEx(NULL)', 'The handle is invalid.')
      dwordsize = GetMetaFileBitsEx((HMETAFILE)handle, 0, NULL);
      if (!dwordsize)
        return ReturnAPIError("GetClipboardData:GetMetafileBitsEx(NULL)");
      // allocate a temporary buffer for metafile
      cData = malloc(dwordsize);
      if (cData == NULL)
        return ReturnAPIError("GetClipboardData:malloc");
      // copy metafile into the temporary buffer
      if (0 == GetMetaFileBitsEx((HMETAFILE)handle, dwordsize, cData)) {
        free(cData);
        return ReturnAPIError("GetClipboardData:GetMetafileBitsEx");
      }
	  size=dwordsize;
      break;
    // All other formats simply return the data as a blob.
    default:
      cData = GlobalLock(handle);
      if (!cData) {
        GlobalUnlock(handle);
        return ReturnAPIError("GetClipboardData:GlobalLock");
      }
      size  = GlobalSize(cData);
      if (!size) {
        GlobalUnlock(handle);
        return ReturnAPIError("GetClipboardData:GlobalSize");
      }
      break;
  }
  switch (format) {
    case CF_BITMAP:
        ret = PyWinLong_FromHANDLE(handle);
        break;
    case CF_HDROP:
        filecnt = DragQueryFileW(hdrop, 0xFFFFFFFF, NULL, NULL);
        ret = PyTuple_New(filecnt);
        if (!ret) return PyErr_NoMemory();
        for (fileind=0;fileind<filecnt;fileind++){
            filenamesize = DragQueryFileW(hdrop, fileind, NULL, NULL);
            filename = (WCHAR *)malloc((filenamesize+1)*sizeof(WCHAR));
            if (!filename) {
                Py_DECREF(ret);
                return PyErr_NoMemory();
            }
            filenamesize = DragQueryFileW(hdrop, fileind, filename, filenamesize+1);
            obfilename=PyWinObject_FromWCHAR(filename);
            PyTuple_SetItem(ret,fileind,obfilename);
            free (filename);
        }
        GlobalUnlock(handle);
        break;
    case CF_UNICODETEXT:
      ret = PyUnicode_FromWideChar((wchar_t *)cData, (size / sizeof(wchar_t))-1);
      GlobalUnlock(handle);
      break;
    // For the text formats, strip the null!
    case CF_TEXT:
    case CF_OEMTEXT:
      ret = PyString_FromStringAndSize((char *)cData, size-1);
      GlobalUnlock(handle);
      break;
    default:
      assert(cData);
      if (!cData) {
          ret = Py_None;
          Py_INCREF(ret);
      } else
        ret = PyString_FromStringAndSize((char *)cData, size);
      GlobalUnlock(handle);
      break;
  }
  return ret;

  // @comm An application can enumerate the available formats in advance by
  // using the EnumClipboardFormats function.<nl>
  // The clipboard controls the handle that the GetClipboardData function
  // returns, not the application. The application should copy the data
  // immediately. The application cannot rely on being able to make long-term
  // use of the handle. The application must not free the handle nor leave it
  // locked.<nl>
  // The system performs implicit data format conversions between certain
  // clipboard formats when an application calls the GetClipboardData function.
  // For example, if the CF_OEMTEXT format is on the clipboard, a window can
  // retrieve data in the CF_TEXT format. The format on the clipboard is
  // converted to the requested format on demand. For more information, see
  // Synthesized Clipboard Formats. 

  // @pyseeapi GetClipboardData
  // @pyseeapi Standard Clipboard Formats

  // @rdesc If the function fails, the standard win32api.error exception 
  // is raised.  If the function succeeds, the return value is as 
  // described in the following table:
  // @flagh Format|Result type
  // @flag CF_HDROP|A tuple of Unicode filenames.
  // @flag CF_UNICODETEXT|A unicode object.
  // @flag CF_OEMTEXT|A string object.
  // @flag CF_TEXT|A string object.
  // @flag CF_ENHMETAFILE|A string with binary data obtained from GetEnhMetaFileBits
  // @flag CF_METAFILEPICT|A string with binary data obtained from GetMetaFileBitsEx (currently broken)
  // @flag CF_BITMAP|An integer handle to the bitmap.
  // @flag All other formats|A string with binary data obtained directly from the 
  // global memory referenced by the handle.
}
Example #10
0
INT_PTR ACheatInfoDlg::OnNotify(LPNMHDR phdr)
{
	if(phdr->idFrom == m_CheatsList->GetCtrlID()){
		if(phdr->code == LVN_BEGINDRAG){
			int iItem = ((NMLISTVIEW*)phdr)->iItem;
			POINT ptStart;
			HIMAGELIST hImg = ListView_CreateDragImage(m_CheatsList->GetHwnd(),iItem,&ptStart);
			ImageList_BeginDrag(hImg,0,0,0);
			ImageList_DragEnter(m_CheatsList->GetHwnd(),ptStart.x,ptStart.y);
			m_iDraggingItem = iItem;
			SetCapture(this->GetHwnd());
			m_bDragging = true;
			return SetDlgResult(0);
		}else if(phdr->code == NM_DBLCLK){
			int isel = m_CheatsList->GetNextItem(-1,LVNI_SELECTED);
			if(isel==-1) return SetDlgResult(0);
			SendMessage(WM_COMMAND,MAKEWPARAM(IDC_CHEAT_EXECLUA,BN_CLICKED),
				(LPARAM)GetDlgItem(this->GetHwnd(),IDC_CHEAT_EXECLUA));
			return SetDlgResult(0);
		}else if(phdr->code == NM_RCLICK){
			//std::vector<int> selection;
			POINT pt;
			::GetCursorPos(&pt);
			HMENU hMenu = ::GetSubMenu(::LoadMenu(theApp->GetAppInstance(),MAKEINTRESOURCE(IDR_MENU_CHEATVALUES)),0);

			int i = m_CheatsList->GetNextItem(-1,LVNI_SELECTED);
			::EnableMenuItem(hMenu,IDM_CHEATVALUES_COPY,MF_BYCOMMAND|(i!=-1?MF_ENABLED:MF_DISABLED|MF_GRAYED));
			::EnableMenuItem(hMenu,IDM_CHEATVALUES_CUT,MF_BYCOMMAND|(i!=-1?MF_ENABLED:MF_DISABLED|MF_GRAYED));
			::EnableMenuItem(hMenu,IDM_CHEATVALUES_PASTE,MF_BYCOMMAND|(clip.IsAvailable()?MF_ENABLED:MF_DISABLED|MF_GRAYED));

			UINT id = ::TrackPopupMenu(hMenu,TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_NONOTIFY|TPM_RETURNCMD,pt.x,pt.y,0,this->GetHwnd(),NULL);
			switch(id)
			{
			case IDM_CHEATVALUES_COPY:
			case IDM_CHEATVALUES_CUT:
				{
					std::vector<ACheatEntry::VALUE*> values;
					values.push_back((ACheatEntry::VALUE*)this->GetHwnd());
					int isel;
					ACheatEntry::VALUE* pnewva=0;
					for(isel=-1;(isel=m_CheatsList->GetNextItem(isel,LVNI_SELECTED))!=-1;){
						if(id==IDM_CHEATVALUES_COPY){
							ACheatEntry::VALUE* pvalue = m_pEntry->item.values[isel];
							pnewva = new ACheatEntry::VALUE;
							*pnewva = *pvalue;
						}else if(id==IDM_CHEATVALUES_CUT){
							auto& vs = m_pEntry->item.values;
							pnewva = vs[isel];
							auto s = vs.begin();
							for(; *s!=pnewva; ++s)
								;
							vs.erase(s);
							m_CheatsList->DeleteItem(isel);
							isel--;
						}
						values.push_back(pnewva);
					}
					values.push_back(0);

					try{
						if(!OpenClipboard(this->GetHwnd()))
							throw "Open";
						EmptyClipboard();

						size_t size = values.size()*sizeof(values[0]);

						HGLOBAL hglo = ::GlobalAlloc(GMEM_MOVEABLE,size);
						if(!hglo) throw "GlobalAlloc";

						void* pv = ::GlobalLock(hglo);
						if(!pv) throw "lock";

						memcpy(pv,&values[0],size);

						::SetClipboardData(clip.GetID(),pv);

						::GlobalUnlock(hglo);

						CloseClipboard();
					}
					catch(const char* s){
						MessageBox(s,0,MB_ICONERROR);
					}
					if(id==IDM_CHEATVALUES_CUT)
						m_pFile->bNeedSaving=true;
					return SetDlgResult(TRUE);
				}
			case IDM_CHEATVALUES_PASTE:
				{
					try{
						if(!OpenClipboard(this->GetHwnd()))
							throw "open";
						void* pv = (void*)GetClipboardData(clip.GetID());
						if(!pv) throw "Get";
						ACheatEntry::VALUE** pp = (ACheatEntry::VALUE**)pv;
						HWND hwnd = (HWND)*pp++;
						if(hwnd != this->GetHwnd())
							throw "抱歉, 当前不支持跨进程操作金手指~";
						while(*pp){
							ACheatEntry::VALUE* p = new ACheatEntry::VALUE;
							*p = **pp;
							m_pEntry->item.values.push_back(p);
							AddListItem(p->name.c_str(),0);

							pp++;
						}
						CloseClipboard();
						m_pFile->bNeedSaving = true;
					}
					catch(const char* s){
						CloseClipboard();
						MessageBox(s,0,MB_ICONERROR);
					}
					return SetDlgResult(TRUE);
				}
			default:
				break;
			}
			return SetDlgResult(0);
		}
	}
	return 0;
}
Example #11
0
LRESULT CALLBACK MainDlg(HWND hwnd,UINT message,WPARAM wparam,LPARAM lparam)
{
	PAINTSTRUCT ps;
	BITMAPINFO bmi;
	char str[255];
	static int timer=FALSE;
	static int xpos=0,ypos=0,LMB=FALSE,dx=0,dy=0;
	static HWND hview=0;
	static HGLRC hglrc=0;
	static HDC hdc=0;
	int i;

#ifdef _DEBUG
//	if(message!=0x200&&message!=0x84&&message!=0x20&&message!=WM_ENTERIDLE)
//		debug_printf("message=%08X wparam=%08X lparam=%08X\n",message,wparam,lparam);
#endif	
	switch(message)
	{
	case WM_INITDIALOG:
		bufA=malloc(bwidth*bheight*bdepth);
		bufB=malloc(bwidth*bheight*bdepth);
		if(bufA==0 || bufB==0)
			MessageBox(hwnd,"malloc failed","error",MB_OK);
		else{
			memset(bufB,0,bwidth*bheight*bdepth);
			rand_fill(bufA,bwidth,bheight,bdepth);
		}
		create_grippy(hwnd);
		BringWindowToTop(hwnd);
		BringWindowToTop(hwnd);
		update_title(hwnd);
		SendMessage(hwnd,WM_KEYDOWN,VK_TAB,0);
		SendMessage(hwnd,WM_LBUTTONDOWN,0,0);
		create_view_windows(hwnd,&hview);
		init_ogl(hview,&hglrc,&hdc);
		resize_view(hwnd,hview);
		break;
	case WM_SIZE:
		{
			int w,h;
			w=LOWORD(lparam);
			h=HIWORD(lparam);
			grippy_move(hwnd);
			resize_view(hwnd,hview);
			reshape(w,h);
		}
		break;
	case WM_TIMER:
		if(LMB)
			handle_click(xpos,ypos);
		display_view1(hview,hglrc);
		break;
	case WM_COMMAND:

		switch(LOWORD(wparam))
		{
		case IDC_ONTOP:
			SetWindowPos(hwnd,IsDlgButtonChecked(hwnd,LOWORD(wparam))? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
			break;
		case WM_DESTROY:
		#ifndef _DEBUG
			if(MessageBox(hwnd,"Sure you want to quit?","QUIT",MB_OKCANCEL)!=IDOK)
				break;
		#endif
			PostQuitMessage(0);
			break;
		}
		break;
	case WM_PAINT:
	/*
		hdc=BeginPaint(hwnd,&ps);
		memset(&bmi,0,sizeof(BITMAPINFO));
		bmi.bmiHeader.biBitCount=24;
		bmi.bmiHeader.biWidth=BUF_WIDTH;
		bmi.bmiHeader.biHeight=BUF_HEIGHT;
		bmi.bmiHeader.biPlanes=1;
		bmi.bmiHeader.biSize=40;
		if(stretch)
			StretchDIBits(hdc,0,0,client_rect.right,client_rect.bottom,0,0,BUF_WIDTH,BUF_HEIGHT,buffer,&bmi,DIB_RGB_COLORS,SRCCOPY);
		else
			SetDIBitsToDevice(hdc,0,0,BUF_WIDTH,BUF_HEIGHT,0,0,0,BUF_WIDTH,buffer,&bmi,DIB_RGB_COLORS);
		screen_updated=TRUE;
		EndPaint(hwnd,&ps);
		*/
		break;
	case WM_CLOSE:
	case WM_QUIT:
		PostQuitMessage(0);
		break;
	case WM_DROPFILES:
		break;
	case WM_RBUTTONDOWN:
	case WM_LBUTTONDOWN:
	case WM_MBUTTONDOWN:
		xpos=LOWORD(lparam);
		ypos=HIWORD(lparam);
		break;
	case WM_MOUSEMOVE:
		{
			int x,y;
			int key=wparam;
			x=LOWORD(lparam);
			y=HIWORD(lparam);
			if(key&MK_LBUTTON){
				x=xpos-x;
				ry=x;
				y=ypos-y;
				rx=y;
				printf("rz=%.1f ry=%.1f\n",rx,ry);
			}
			if(key&MK_RBUTTON){
				x=xpos-x;
				rz=-x;
				printf("z=%.1f\n",rz);
			}
			update_title(hwnd);
		}
		break;
	case WM_MOUSEWHEEL:
		if(wparam&0x80000000)
			SendMessage(hwnd,WM_KEYDOWN,VK_NEXT,0);
		else
			SendMessage(hwnd,WM_KEYDOWN,VK_PRIOR,0);
		break;
	case WM_KEYUP:
		break;
	case WM_KEYDOWN:
		{
			int ctrl=GetKeyState(VK_CONTROL)&0x8000;
			int shift=GetKeyState(VK_SHIFT)&0x8000;

#ifdef _DEBUG
//		debug_printf("message=%08X wparam=%08X lparam=%08X\n",message,wparam,lparam);
#endif
		switch(wparam)
		{
		case VK_INSERT:
			clear_screen();
			break;
		case 0xBD:
		case 0xBB:
			break;
		case 'Q':
			rx=ry=rz=0;
			printf("angles reset\n");
			break;
		case 'W':
			break;
		case 0xC0:
			rand_fill(swap?bufB:bufA,bwidth,bheight,bdepth);
			break;
		case 'K':
			set_offsety(1);
			break;
		case 'L':
			set_offsety(-1);
			break;
		case 'X':
			if(shift)
				scale+=10;
			else
				scale++;
			printf("scale=%i\n",scale);
			break;
		case 'Z':
			if(shift)
				scale-=10;
			else
				scale--;
			printf("scale=%i\n",scale);
			break;
		//case 0xC0:
			change_direction(0);
			rx=ry=rz=0;
			break;
		case '0':
		case '1':
			//tube();
			frame_step=1;
			break;
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			change_direction(wparam-'0');
			break;

		case VK_SPACE:
			break;
		case VK_TAB:
			if(timer)
				KillTimer(hwnd,1);
			else
				SetTimer(hwnd,1,60,NULL);
			timer=!timer;
			break;
		case VK_F1:
			display_help(hwnd);
			break;
/*		case VK_F2:
			i=CreateDialog(ghInstance,MAKEINTRESOURCE(IDD_DIALOG2),hwnd,request_value);
			ShowWindow(i,SW_SHOWNORMAL);
			debug_printf("return =%i\r\n",i);
			break;*/
		case VK_F5:
			break;
		case VK_F9:
			stretch=!stretch;
			break;
		case 0xDEADBEEF:
			break;
		case VK_DOWN:
			if(GetKeyState(VK_CONTROL)&0x8000)
				move_center(3);
			else if(GetKeyState(VK_SHIFT)&0x8000)
				change_direction(12);
			else
				change_direction(2);
			break;
		case VK_UP:
			if(GetKeyState(VK_CONTROL)&0x8000)
				move_center(4);
			else if(GetKeyState(VK_SHIFT)&0x8000)
				change_direction(11);
			else
				change_direction(1);
			break;
		case VK_LEFT:
			if(GetKeyState(VK_CONTROL)&0x8000)
				move_center(1);
			else if(GetKeyState(VK_SHIFT)&0x8000)
				change_direction(14);
			else
				change_direction(4);
			break;
		case VK_RIGHT:
			if(GetKeyState(VK_CONTROL)&0x8000)
				move_center(2);
			else if(GetKeyState(VK_SHIFT)&0x8000)
				change_direction(13);
			else
				change_direction(3);
			break;
		case VK_ADD:
			break;
		case VK_SUBTRACT:
			break;
		case VK_NEXT: //page key
			if(GetKeyState(VK_CONTROL)&0x8000)
				;
			else if(GetKeyState(VK_SHIFT)&0x8000)
				;
			change_direction(100);
			break;
		case VK_PRIOR: //page key
			if(GetKeyState(VK_CONTROL)&0x8000)
				;
			else if(GetKeyState(VK_SHIFT)&0x8000)
				;
			change_direction(100);
			break;
		case VK_HOME:
			change_direction(5);
			break;
		case VK_END:
			;
			break;
		case ZOOM_IN_KEY: //[
			if(GetKeyState(VK_SHIFT)&0x8000){
				if(GetKeyState(VK_CONTROL)&0x8000)
					;
				else
					;
			}
			else
				;
			break;
		case ZOOM_OUT_KEY: //]
			if(GetKeyState(VK_SHIFT)&0x8000){
				if(GetKeyState(VK_CONTROL)&0x8000)
					;
				else
					;
			}
			else
				;
			break;
		case 0xBE:  //>
			if(GetKeyState(VK_SHIFT)&0x8000){
				if(GetKeyState(VK_CONTROL)&0x8000)
					;
				else
					;
			}
			else
				;
			break;
		case 0xBC:  //<
			if(GetKeyState(VK_SHIFT)&0x8000){
				if(GetKeyState(VK_CONTROL)&0x8000)
					;
				else
					;
			}
			else
				;
			break;
		case 'V':
			if(GetKeyState(VK_CONTROL)&0x8000){
				if(OpenClipboard(NULL)){
					char *p=GetClipboardData(CF_TEXT);
					if(p!=0){
						strncpy(str,p,sizeof(str));
						SetDlgItemText(hwnd,IDC_EDIT1,str);
					}
					CloseClipboard();
				}
			}
			break;
		case VK_ESCAPE:
			if(MessageBox(hwnd,"Sure you want to quit?","QUIT",MB_OKCANCEL)==IDOK)
				PostQuitMessage(0);
			break;
		}
		update_title(hwnd);
		}
		break;
	}
	return 0;
}
Example #12
0
int WDL_CursesEditor::onChar(int c)
{
  if (m_state == -3 || m_state == -4)
  {
    switch (c)
    {
       case '\r': case '\n':
         m_state=0;
         runSearch();
       break;
       case 27: 
         m_state=0; 
         draw();
         draw_message("Find cancelled.");
         setCursor();
       break;
       case KEY_BACKSPACE: if (s_search_string[0]) s_search_string[strlen(s_search_string)-1]=0; m_state=-4; break;
       default: 
         if (VALIDATE_TEXT_CHAR(c)) 
         { 
           int l=m_state == -3 ? 0 : strlen(s_search_string); 
           m_state = -4;
           if (l < (int)sizeof(s_search_string)-1) { s_search_string[l]=c; s_search_string[l+1]=0; } 
         } 
        break;
     }
     if (m_state)
     {
       attrset(m_color_message);
       bkgdset(m_color_message);
       mvaddstr(LINES-1,29,s_search_string);
       clrtoeol(); 
       attrset(0);
       bkgdset(0);
     }
     return 0;
  }
  if (c==KEY_DOWN || c==KEY_UP || c==KEY_PPAGE||c==KEY_NPAGE || c==KEY_RIGHT||c==KEY_LEFT||c==KEY_HOME||c==KEY_END)
  {
    if (GetAsyncKeyState(VK_SHIFT)&0x8000)      
    {
      if (!m_selecting)
      {
        m_select_x2=m_select_x1=m_curs_x; m_select_y2=m_select_y1=m_curs_y;
        m_selecting=1;
      }
    }
    else if (m_selecting) { m_selecting=0; draw(); }
  }

  switch(c)
  {
    case 407:
    case 'Z'-'A'+1:
      if (!(GetAsyncKeyState(VK_SHIFT)&0x8000))
      {
        if (m_undoStack_pos > 0)
        {
           m_undoStack_pos--;
           loadUndoState(m_undoStack.Get(m_undoStack_pos));
           draw();
           char buf[512];
           snprintf(buf,sizeof(buf),"Undid action -- %d items in undo buffer",m_undoStack_pos);
           draw_message(buf);
           setCursor();
        }
        else draw_message("Can't Undo");

        break;
      }
      // fall through
    case 'Y'-'A'+1:
      if (m_undoStack_pos < m_undoStack.GetSize()-1)
      {
        m_undoStack_pos++;
        loadUndoState(m_undoStack.Get(m_undoStack_pos));
        draw();
        char buf[512];
        snprintf(buf,sizeof(buf),"Redid action -- %d items in redo buffer",m_undoStack.GetSize()-m_undoStack_pos-1);
        draw_message(buf);
        setCursor();
      }
      else draw_message("Can't Redo");  
    break;
    case KEY_IC:
      if (!(GetAsyncKeyState(VK_SHIFT)&0x8000))
      {
        s_overwrite=!s_overwrite;
        setCursor();
        break;
      }
      // fqll through
    case 'V'-'A'+1:
      {
        // generate a m_clipboard using win32 clipboard data
        WDL_PtrList<const char> lines;
        WDL_String buf;
#ifdef WDL_IS_FAKE_CURSES
        if (CURSES_INSTANCE)
        {
          OpenClipboard(CURSES_INSTANCE->m_hwnd);
          HANDLE h=GetClipboardData(CF_TEXT);
          if (h)
          {
            char *t=(char *)GlobalLock(h);
            int s=GlobalSize(h);
            buf.Set(t,s);
            GlobalUnlock(t);        
          }
          CloseClipboard();
        }
        else
#endif
        {
          buf.Set(s_fake_clipboard.Get());
        }

        if (buf.Get() && buf.Get()[0])
        {
          char *src=buf.Get();
          while (*src)
          {
            char *seek=src;
            while (*seek && *seek != '\r' && *seek != '\n') seek++;
            char hadclr=*seek;
            if (*seek) *seek++=0;
            lines.Add(src);

            if (hadclr == '\r' && *seek == '\n') seek++;

            if (hadclr && !*seek)
            {
              lines.Add("");
            }
            src=seek;
          }
        }
        if (lines.GetSize())
        {
          removeSelect();
          // insert lines at m_curs_y,m_curs_x
          if (m_curs_y >= m_text.GetSize()) m_curs_y=m_text.GetSize()-1;
          if (m_curs_y < 0) m_curs_y=0;

          preSaveUndoState();
          WDL_FastString poststr;
          int x;
          int indent_to_pos = -1;
          for (x = 0; x < lines.GetSize(); x ++)
          {
            WDL_FastString *str=m_text.Get(m_curs_y);
            const char *tstr=lines.Get(x);
            if (!tstr) tstr="";
            if (!x)
            {
              if (str)
              {
                if (m_curs_x < 0) m_curs_x=0;
                int tmp=str->GetLength();
                if (m_curs_x > tmp) m_curs_x=tmp;
  
                poststr.Set(str->Get()+m_curs_x);
                str->SetLen(m_curs_x);

                const char *p = str->Get();
                while (*p == ' ' || *p == '\t') p++;
                if (!*p && p > str->Get())
                {
                  if (lines.GetSize()>1)
                  {
                    while (*tstr == ' ' || *tstr == '\t') tstr++;
                  }
                  indent_to_pos = m_curs_x;
                }

                str->Append(tstr);
              }
              else
              {
                m_text.Insert(m_curs_y,(str=new WDL_FastString(tstr)));
              }
              if (lines.GetSize() > 1)
              {
                m_curs_y++;
              }
              else
              {
                m_curs_x = str->GetLength();
                str->Append(poststr.Get());
              }
           }
           else if (x == lines.GetSize()-1)
           {
             WDL_FastString *s=newIndentedFastString(tstr,indent_to_pos);
             m_curs_x = s->GetLength();
             s->Append(poststr.Get());
             m_text.Insert(m_curs_y,s);
           }
           else
           {
             m_text.Insert(m_curs_y,newIndentedFastString(tstr,indent_to_pos));
             m_curs_y++;
           }
         }
         draw();
         draw_message("Pasted");
         saveUndoState();
         setCursor();
       }
       else 
       {
         draw_message("Clipboard empty");
         setCursor();
       }
     }
  break;

  case KEY_DC:
    if (!(GetAsyncKeyState(VK_SHIFT)&0x8000))
    {
      WDL_FastString *s;
      if (m_selecting)
      {
        preSaveUndoState();
        removeSelect();
        draw();
        saveUndoState();
        setCursor();
      }
      else if ((s=m_text.Get(m_curs_y)))
      {
        if (m_curs_x < s->GetLength())
        {
          preSaveUndoState();

          bool hadCom = LineCanAffectOtherLines(s->Get(),m_curs_x,1); 
          s->DeleteSub(m_curs_x,1);
          if (!hadCom) hadCom = LineCanAffectOtherLines(s->Get(),-1,-1);
          draw(hadCom ? -1 : m_curs_y);
          saveUndoState();
          setCursor();
        }
        else // append next line to us
        {
          if (m_curs_y < m_text.GetSize()-1)
          {
            preSaveUndoState();

            WDL_FastString *nl=m_text.Get(m_curs_y+1);
            if (nl)
            {
              s->Append(nl->Get());
            }
            m_text.Delete(m_curs_y+1,true);

            draw();
            saveUndoState();
            setCursor();
          }
        }
      }
      break;
    }
  case 'C'-'A'+1:
  case 'X'-'A'+1:
    if (m_selecting)
    {
      if (c!= 'C'-'A'+1) m_selecting=0;
      int miny,maxy,minx,maxx;
      int x;
      getselectregion(minx,miny,maxx,maxy);
      const char *status="";
      char statusbuf[512];

      if (minx != maxx|| miny != maxy) 
      {
        int bytescopied=0;
        s_fake_clipboard.Set("");

        int lht=0,fht=0;
        if (c != 'C'-'A'+1) preSaveUndoState();

        for (x = miny; x <= maxy; x ++)
        {
          WDL_FastString *s=m_text.Get(x);
          if (s) 
          {
            const char *str=s->Get();
            int sx,ex;
            if (x == miny) sx=max(minx,0);
            else sx=0;
            int tmp=s->GetLength();
            if (sx > tmp) sx=tmp;
      
            if (x == maxy) ex=min(maxx,tmp);
            else ex=tmp;
      
            bytescopied += ex-sx + (x!=maxy);
            if (s_fake_clipboard.Get() && s_fake_clipboard.Get()[0]) s_fake_clipboard.Append("\r\n");
            s_fake_clipboard.Append(ex-sx?str+sx:"",ex-sx);

            if (c != 'C'-'A'+1)
            {
              if (sx == 0 && ex == tmp) // remove entire line
              {
                m_text.Delete(x,true);
                if (x==miny) miny--;
                x--;
                maxy--;
              }
              else { if (x==miny) fht=1; if (x == maxy) lht=1; s->DeleteSub(sx,ex-sx); }
            }
          }
        }
        if (fht && lht && miny+1 == maxy)
        {
          m_text.Get(miny)->Append(m_text.Get(maxy)->Get());
          m_text.Delete(maxy,true);
        }
        if (c != 'C'-'A'+1)
        {
          m_curs_y=miny;
          if (m_curs_y < 0) m_curs_y=0;
          m_curs_x=minx;
          saveUndoState();
          snprintf(statusbuf,sizeof(statusbuf),"Cut %d bytes",bytescopied);
        }
        else
          snprintf(statusbuf,sizeof(statusbuf),"Copied %d bytes",bytescopied);

#ifdef WDL_IS_FAKE_CURSES
        if (CURSES_INSTANCE)
        {
          int l=s_fake_clipboard.GetLength()+1;
          HANDLE h=GlobalAlloc(GMEM_MOVEABLE,l);
          void *t=GlobalLock(h);
          memcpy(t,s_fake_clipboard.Get(),l);
          GlobalUnlock(h);
          OpenClipboard(CURSES_INSTANCE->m_hwnd);
          EmptyClipboard();
          SetClipboardData(CF_TEXT,h);
          CloseClipboard();
        }
#endif

        status=statusbuf;
      }
      else status="No selection";

      draw();
      draw_message(status);
      setCursor();
    }
  break;
  case 'A'-'A'+1:
    m_selecting=1;
    m_select_x1=0;
    m_select_y1=0;
    m_select_y2=m_text.GetSize()-1;
    m_select_x2=0;
    if (m_text.Get(m_select_y2))
      m_select_x2=m_text.Get(m_select_y2)->GetLength();
    draw();
    setCursor();
  break;
  case 27:
    if (m_selecting)
    {
      m_selecting=0;
      draw();
      setCursor();
      break;
    }
  return 0;
  case KEY_F3:
  case 'G'-'A'+1:
    if (s_search_string[0])
    {
      runSearch();
      return 0;
    }
  case 'F'-'A'+1:
    draw_message("");
    attrset(m_color_message);
    bkgdset(m_color_message);
    mvaddstr(LINES-1,0,"Find string (ESC to cancel): ");
    addstr(s_search_string);
    clrtoeol();
    attrset(0);
    bkgdset(0);
    m_state=-3; // find, initial (m_state=4 when we've typed something)
  return 0;
  case KEY_DOWN:
    {
      if (GetAsyncKeyState(VK_CONTROL)&0x8000)      
      {
        if (m_offs_y < m_text.GetSize() - 4) 
        {
          m_offs_y++;
          if (m_curs_y < m_offs_y) m_curs_y = m_offs_y;
          draw();
        }
      }
      else
      {
        m_curs_y++;
        if(m_curs_y>=m_text.GetSize()) m_curs_y=m_text.GetSize()-1;
        if(m_curs_y < 0) m_curs_y=0;
      }
      if (m_selecting) { setCursor(1); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor(1);
    }
  break;
  case KEY_UP:
    {
      if (GetAsyncKeyState(VK_CONTROL)&0x8000)      
      {
        if (m_offs_y>0) 
        {
          m_offs_y--;
          if (m_curs_y>m_offs_y + getVisibleLines() - 1) m_curs_y = m_offs_y + getVisibleLines() - 1;
          if (m_curs_y < 0) m_curs_y=0;
          draw();
        }
      }
      else
      {
        if(m_curs_y>0) m_curs_y--;
      }
      if (m_selecting) { setCursor(1); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor(1);
    }
  break;
  case KEY_PPAGE:
    {
      if (m_curs_y > m_offs_y) 
      {
        m_curs_y=m_offs_y;
        if (m_curs_y < 0) m_curs_y=0;
      }
      else 
      {
        m_curs_y -= getVisibleLines();
        if (m_curs_y < 0) m_curs_y=0;
        m_offs_y=m_curs_y;
      }
      if (m_selecting) { setCursor(1); m_select_x2=m_curs_x; m_select_y2=m_curs_y; }
      draw();
      setCursor(1);
    }
  break;
  case KEY_NPAGE:
    {
      if (m_curs_y >= m_offs_y+getVisibleLines() - 1) m_offs_y=m_curs_y+1;
      m_curs_y = m_offs_y+getVisibleLines() - 1;
      if (m_curs_y >= m_text.GetSize()) m_curs_y=m_text.GetSize()-1;
      if (m_curs_y < 0) m_curs_y=0;
      if (m_selecting) { setCursor(1); m_select_x2=m_curs_x; m_select_y2=m_curs_y; }
      draw();
      setCursor(1);
    }
  break;
  case KEY_RIGHT:
    {
      if (1) // wrap across lines
      {
        WDL_FastString *s = m_text.Get(m_curs_y);
        if (s && m_curs_x >= s->GetLength() && m_curs_y < m_text.GetSize()) { m_curs_y++; m_curs_x = -1; }
      }

      if(m_curs_x<0) 
      {
        m_curs_x=0;
      }
      else
      {
        if (GetAsyncKeyState(VK_CONTROL)&0x8000)      
        {
          WDL_FastString *s = m_text.Get(m_curs_y);
          if (!s||m_curs_x >= s->GetLength()) break;
          int lastType = categorizeCharForWordNess(s->Get()[m_curs_x++]);
          while (m_curs_x < s->GetLength())
          {
            int thisType = categorizeCharForWordNess(s->Get()[m_curs_x]);
            if (thisType != lastType && thisType != 0) break;
            lastType=thisType;
            m_curs_x++;
          }
        }
        else 
        {
          m_curs_x++;
        }
      }
      if (m_selecting) { setCursor(); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor();
    }
  break;
  case KEY_LEFT:
    {
      bool doMove=true;
      if (1) // wrap across lines
      {
        WDL_FastString *s = m_text.Get(m_curs_y);
        if (s && m_curs_y>0 && m_curs_x == 0) 
        { 
          s = m_text.Get(--m_curs_y);
          if (s) 
          {
            m_curs_x = s->GetLength(); 
            doMove=false;
          }
        }
      }

      if(m_curs_x>0 && doMove) 
      {
        if (GetAsyncKeyState(VK_CONTROL)&0x8000)      
        {
          WDL_FastString *s = m_text.Get(m_curs_y);
          if (!s) break;
          if (m_curs_x > s->GetLength()) m_curs_x = s->GetLength();
          m_curs_x--;

          int lastType = categorizeCharForWordNess(s->Get()[m_curs_x--]);
          while (m_curs_x >= 0)
          {
            int thisType = categorizeCharForWordNess(s->Get()[m_curs_x]);
            if (thisType != lastType && lastType != 0) break;
            lastType=thisType;
            m_curs_x--;
          }
          m_curs_x++;
        }
        else 
        {
          m_curs_x--;
        }
      }
      if (m_selecting) { setCursor(); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor();
    }
  break;
  case KEY_HOME:
    {
      m_curs_x=0;
      if (m_selecting) { setCursor(); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor();
    }
  break;
  case KEY_END:
    {
      if (m_text.Get(m_curs_y)) m_curs_x=m_text.Get(m_curs_y)->GetLength();
      if (m_selecting) { setCursor(); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor();
    }
  break;
  case KEY_BACKSPACE: // backspace, baby
    if (m_selecting)
    {
      preSaveUndoState();
      removeSelect();
      draw();
      saveUndoState();
      setCursor();
    }
    else if (m_curs_x > 0)
    {
      WDL_FastString *tl=m_text.Get(m_curs_y);
      if (tl)
      {
        preSaveUndoState();

        bool hadCom = LineCanAffectOtherLines(tl->Get(), m_curs_x-1,1);
        tl->DeleteSub(--m_curs_x,1);
        if (!hadCom) hadCom = LineCanAffectOtherLines(tl->Get(),-1,-1);
        draw(hadCom?-1:m_curs_y);
        saveUndoState();
        setCursor();
      }
    }
    else // append current line to previous line
    {
      WDL_FastString *fl=m_text.Get(m_curs_y-1), *tl=m_text.Get(m_curs_y);
      if (!tl) 
      {
        m_curs_y--;
        if (fl) m_curs_x=fl->GetLength();
        draw();
        saveUndoState();
        setCursor();
      }
      else if (fl)
      {
        preSaveUndoState();
        m_curs_x=fl->GetLength();
        fl->Append(tl->Get());

        m_text.Delete(m_curs_y--,true);
        draw();
        saveUndoState();
        setCursor();
      }
    }
  break;
  case 'L'-'A'+1:
    draw();
    setCursor();
  break;
  case 13: //KEY_ENTER:
    //insert newline
    preSaveUndoState();

    if (m_selecting) { removeSelect(); draw(); setCursor(); }
    if (m_curs_y >= m_text.GetSize())
    {
      m_curs_y=m_text.GetSize();
      m_text.Add(new WDL_FastString);
    }
    if (s_overwrite)
    {
      WDL_FastString *s = m_text.Get(m_curs_y);
      int plen=0;
      const char *pb=NULL;
      if (s)
      {
        pb = s->Get();
        while (plen < m_curs_x && (pb[plen]== ' ' || pb[plen] == '\t')) plen++;
      }
      if (++m_curs_y >= m_text.GetSize())
      {
        m_curs_y = m_text.GetSize();
        WDL_FastString *ns=new WDL_FastString;
        if (plen>0) ns->Set(pb,plen);
        m_text.Insert(m_curs_y,ns);
      }
      s = m_text.Get(m_curs_y);
      if (s && plen > s->GetLength()) plen=s->GetLength();
      m_curs_x=plen;
    }
    else 
    {
      WDL_FastString *s = m_text.Get(m_curs_y);
      if (s)
      {
        if (m_curs_x > s->GetLength()) m_curs_x = s->GetLength();
        WDL_FastString *nl = new WDL_FastString();
        int plen=0;
        const char *pb = s->Get();
        while (plen < m_curs_x && (pb[plen]== ' ' || pb[plen] == '\t')) plen++;

        if (plen>0) nl->Set(pb,plen);

        nl->Append(pb+m_curs_x);
        m_text.Insert(++m_curs_y,nl);
        s->SetLen(m_curs_x);
        m_curs_x=plen;
      }
    }
    m_offs_x=0;

    draw();
    saveUndoState();
    setCursor();
  break;
  case '\t':
    if (m_selecting)
    {
      preSaveUndoState();

      bool isRev = !!(GetAsyncKeyState(VK_SHIFT)&0x8000);
      indentSelect(isRev?-m_indent_size:m_indent_size);
      // indent selection:
      draw();
      setCursor();
      saveUndoState();
      break;
    }
  default:
    //insert char
    if(VALIDATE_TEXT_CHAR(c))
    { 
      preSaveUndoState();

      if (m_selecting) { removeSelect(); draw(); setCursor(); }
      if (!m_text.Get(m_curs_y)) m_text.Insert(m_curs_y,new WDL_FastString);

      WDL_FastString *ss;
      if ((ss=m_text.Get(m_curs_y)))
      {
        char str[64];
        int slen ;
        if (c == '\t') 
        {
          slen = min(m_indent_size,64);
          if (slen<1) slen=1;
          int x; 
          for(x=0;x<slen;x++) str[x]=' ';
        }
        else
        {
          str[0]=c;
          slen = 1;
        }


        bool hadCom = LineCanAffectOtherLines(ss->Get(),-1,-1);
        if (s_overwrite)
        {
          if (!hadCom) hadCom = LineCanAffectOtherLines(ss->Get(),m_curs_x,slen);
          ss->DeleteSub(m_curs_x,slen);
        }
        ss->Insert(str,m_curs_x,slen);
        if (!hadCom) hadCom = LineCanAffectOtherLines(ss->Get(),m_curs_x,slen);

        m_curs_x += slen;
        draw(hadCom ? -1 : m_curs_y);
      }
      saveUndoState();
      setCursor();
    }
    break;
  }
  return 0;
}
Example #13
0
/*
====================
CL_UISystemCalls

The ui module is making a system call
====================
*/
intptr_t CL_UISystemCalls(intptr_t *args)
{
	switch (args[0])
	{
	case UI_ERROR:
		Com_Error(ERR_DROP, "%s", (char *)VMA(1));
		return 0;
	case UI_PRINT:
		Com_Printf("%s", (char *)VMA(1));
		return 0;
	case UI_MILLISECONDS:
		return Sys_Milliseconds();
	case UI_CVAR_REGISTER:
		Cvar_Register(VMA(1), VMA(2), VMA(3), args[4]);
		return 0;
	case UI_CVAR_UPDATE:
		Cvar_Update(VMA(1));
		return 0;
	case UI_CVAR_SET:
		Cvar_SetSafe(VMA(1), VMA(2));
		return 0;
	case UI_CVAR_VARIABLEVALUE:
		return FloatAsInt(Cvar_VariableValue(VMA(1)));
	case UI_CVAR_VARIABLESTRINGBUFFER:
		Cvar_VariableStringBuffer(VMA(1), VMA(2), args[3]);
		return 0;
	case UI_CVAR_LATCHEDVARIABLESTRINGBUFFER:
		Cvar_LatchedVariableStringBuffer(VMA(1), VMA(2), args[3]);
		return 0;
	case UI_CVAR_SETVALUE:
		Cvar_SetValueSafe(VMA(1), VMF(2));
		return 0;
	case UI_CVAR_RESET:
		Cvar_Reset(VMA(1));
		return 0;
	case UI_CVAR_CREATE:
		Cvar_Register(NULL, VMA(1), VMA(2), args[3]);
		return 0;
	case UI_CVAR_INFOSTRINGBUFFER:
		Cvar_InfoStringBuffer(args[1], VMA(2), args[3]);
		return 0;
	case UI_ARGC:
		return Cmd_Argc();
	case UI_ARGV:
		Cmd_ArgvBuffer(args[1], VMA(2), args[3]);
		return 0;
	case UI_CMD_EXECUTETEXT:
		if (args[1] == EXEC_NOW
		    && (!strncmp(VMA(2), "snd_restart", 11)
		        || !strncmp(VMA(2), "vid_restart", 11)
		        || !strncmp(VMA(2), "quit", 5)))
		{
			Com_Printf(S_COLOR_YELLOW "turning EXEC_NOW '%.11s' into EXEC_INSERT\n", (const char *)VMA(2));
			args[1] = EXEC_INSERT;
		}
		Cbuf_ExecuteText(args[1], VMA(2));
		return 0;
	case UI_ADDCOMMAND:
		Cmd_AddCommand(VMA(1), NULL);
		return 0;
	case UI_FS_FOPENFILE:
		return FS_FOpenFileByMode(VMA(1), VMA(2), args[3]);
	case UI_FS_READ:
		FS_Read(VMA(1), args[2], args[3]);
		return 0;
	case UI_FS_WRITE:
		FS_Write(VMA(1), args[2], args[3]);
		return 0;
	case UI_FS_FCLOSEFILE:
		FS_FCloseFile(args[1]);
		return 0;
	case UI_FS_DELETEFILE:
		return FS_Delete(VMA(1));
	case UI_FS_GETFILELIST:
		return FS_GetFileList(VMA(1), VMA(2), VMA(3), args[4]);
	case UI_R_REGISTERMODEL:
		return re.RegisterModel(VMA(1));
	case UI_R_REGISTERSKIN:
		return re.RegisterSkin(VMA(1));
	case UI_R_REGISTERSHADERNOMIP:
		return re.RegisterShaderNoMip(VMA(1));
	case UI_R_CLEARSCENE:
		re.ClearScene();
		return 0;
	case UI_R_ADDREFENTITYTOSCENE:
		re.AddRefEntityToScene(VMA(1));
		return 0;
	case UI_R_ADDPOLYTOSCENE:
		re.AddPolyToScene(args[1], args[2], VMA(3));
		return 0;
	case UI_R_ADDPOLYSTOSCENE:
		re.AddPolysToScene(args[1], args[2], VMA(3), args[4]);
		return 0;
	case UI_R_ADDLIGHTTOSCENE:
		// new dlight code
		re.AddLightToScene(VMA(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), args[7], args[8]);
		return 0;
	case UI_R_ADDCORONATOSCENE:
		re.AddCoronaToScene(VMA(1), VMF(2), VMF(3), VMF(4), VMF(5), args[6], args[7]);
		return 0;
	case UI_R_RENDERSCENE:
		re.RenderScene(VMA(1));
		return 0;
	case UI_R_SETCOLOR:
		re.SetColor(VMA(1));
		return 0;
	case UI_R_DRAW2DPOLYS:
		re.Add2dPolys(VMA(1), args[2], args[3]);
		return 0;
	case UI_R_DRAWSTRETCHPIC:
		re.DrawStretchPic(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9]);
		return 0;
	case UI_R_DRAWROTATEDPIC:
		re.DrawRotatedPic(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9], VMF(10));
		return 0;
	case UI_R_MODELBOUNDS:
		re.ModelBounds(args[1], VMA(2), VMA(3));
		return 0;
	case UI_UPDATESCREEN:
		SCR_UpdateScreen();
		return 0;
	case UI_CM_LERPTAG:
		return re.LerpTag(VMA(1), VMA(2), VMA(3), args[4]);
	case UI_S_REGISTERSOUND:
		return S_RegisterSound(VMA(1), args[2]);
	case UI_S_STARTLOCALSOUND:
		S_StartLocalSound(args[1], args[2], args[3]);
		return 0;
	case UI_S_FADESTREAMINGSOUND:
		S_FadeStreamingSound(VMF(1), args[2], args[3]);
		return 0;
	case UI_S_FADEALLSOUNDS:
		S_FadeAllSounds(VMF(1), args[2], args[3]);
		return 0;
	case UI_KEY_KEYNUMTOSTRINGBUF:
		Key_KeynumToStringBuf(args[1], VMA(2), args[3]);
		return 0;
	case UI_KEY_GETBINDINGBUF:
		Key_GetBindingBuf(args[1], VMA(2), args[3]);
		return 0;
	case UI_KEY_SETBINDING:
		Key_SetBinding(args[1], VMA(2));
		return 0;
	case UI_KEY_BINDINGTOKEYS:
		Key_GetBindingByString(VMA(1), VMA(2), VMA(3));
		return 0;
	case UI_KEY_ISDOWN:
		return Key_IsDown(args[1]);
	case UI_KEY_GETOVERSTRIKEMODE:
		return Key_GetOverstrikeMode();
	case UI_KEY_SETOVERSTRIKEMODE:
		Key_SetOverstrikeMode(args[1]);
		return 0;
	case UI_KEY_CLEARSTATES:
		Key_ClearStates();
		return 0;
	case UI_KEY_GETCATCHER:
		return Key_GetCatcher();
	case UI_KEY_SETCATCHER:
		// Don't allow the ui module to close the console
		Key_SetCatcher(args[1] | (Key_GetCatcher() & KEYCATCH_CONSOLE));
		return 0;
	case UI_GETCLIPBOARDDATA:
		GetClipboardData(VMA(1), args[2]);
		return 0;
	case UI_GETCLIENTSTATE:
		GetClientState(VMA(1));
		return 0;
	case UI_GETGLCONFIG:
		CL_GetGlconfig(VMA(1));
		return 0;
	case UI_GETCONFIGSTRING:
		return GetConfigString(args[1], VMA(2), args[3]);
	case UI_LAN_LOADCACHEDSERVERS:
		LAN_LoadCachedServers();
		return 0;
	case UI_LAN_SAVECACHEDSERVERS:
		//LAN_SaveServersToFile(); // now done on add/remove fav server so we no longer save LAN favs on shutdown & restart
		return 0;
	case UI_LAN_ADDSERVER:
		return LAN_AddServer(args[1], VMA(2), VMA(3));
	case UI_LAN_REMOVESERVER:
		LAN_RemoveServer(args[1], VMA(2));
		return 0;
	case UI_LAN_GETPINGQUEUECOUNT:
		return LAN_GetPingQueueCount();
	case UI_LAN_CLEARPING:
		LAN_ClearPing(args[1]);
		return 0;
	case UI_LAN_GETPING:
		LAN_GetPing(args[1], VMA(2), args[3], VMA(4));
		return 0;
	case UI_LAN_GETPINGINFO:
		LAN_GetPingInfo(args[1], VMA(2), args[3]);
		return 0;
	case UI_LAN_GETSERVERCOUNT:
		return LAN_GetServerCount(args[1]);
	case UI_LAN_GETSERVERADDRESSSTRING:
		LAN_GetServerAddressString(args[1], args[2], VMA(3), args[4]);
		return 0;
	case UI_LAN_GETSERVERINFO:
		LAN_GetServerInfo(args[1], args[2], VMA(3), args[4]);
		return 0;
	case UI_LAN_GETSERVERPING:
		return LAN_GetServerPing(args[1], args[2]);
	case UI_LAN_MARKSERVERVISIBLE:
		LAN_MarkServerVisible(args[1], args[2], args[3]);
		return 0;
	case UI_LAN_SERVERISVISIBLE:
		return LAN_ServerIsVisible(args[1], args[2]);
	case UI_LAN_UPDATEVISIBLEPINGS:
		return LAN_UpdateVisiblePings(args[1]);
	case UI_LAN_RESETPINGS:
		LAN_ResetPings(args[1]);
		return 0;
	case UI_LAN_SERVERSTATUS:
		return LAN_GetServerStatus(VMA(1), VMA(2), args[3]);
	case UI_LAN_SERVERISINFAVORITELIST:
		return LAN_ServerIsInFavoriteList(args[1], args[2]);
	case UI_LAN_COMPARESERVERS:
		return LAN_CompareServers(args[1], args[2], args[3], args[4], args[5]);
	case UI_MEMORY_REMAINING:
		return Hunk_MemoryRemaining();
	case UI_R_REGISTERFONT:
		re.RegisterFont(VMA(1), args[2], VMA(3));
		return 0;
	case UI_MEMSET:
		return (intptr_t)memset(VMA(1), args[2], args[3]);
	case UI_MEMCPY:
		return (intptr_t)memcpy(VMA(1), VMA(2), args[3]);
	case UI_STRNCPY:
		return (intptr_t)strncpy(VMA(1), VMA(2), args[3]);
	case UI_SIN:
		return FloatAsInt(sin(VMF(1)));
	case UI_COS:
		return FloatAsInt(cos(VMF(1)));
	case UI_ATAN2:
		return FloatAsInt(atan2(VMF(1), VMF(2)));
	case UI_SQRT:
		return FloatAsInt(sqrt(VMF(1)));
	case UI_FLOOR:
		return FloatAsInt(floor(VMF(1)));
	case UI_CEIL:
		return FloatAsInt(ceil(VMF(1)));
	case UI_PC_ADD_GLOBAL_DEFINE:
		return botlib_export->PC_AddGlobalDefine(VMA(1));
	case UI_PC_REMOVE_ALL_GLOBAL_DEFINES:
		botlib_export->PC_RemoveAllGlobalDefines();
		return 0;
	case UI_PC_LOAD_SOURCE:
		return botlib_export->PC_LoadSourceHandle(VMA(1));
	case UI_PC_FREE_SOURCE:
		return botlib_export->PC_FreeSourceHandle(args[1]);
	case UI_PC_READ_TOKEN:
		return botlib_export->PC_ReadTokenHandle(args[1], VMA(2));
	case UI_PC_SOURCE_FILE_AND_LINE:
		return botlib_export->PC_SourceFileAndLine(args[1], VMA(2), VMA(3));
	case UI_PC_UNREAD_TOKEN:
		botlib_export->PC_UnreadLastTokenHandle(args[1]);
		return 0;
	case UI_S_STOPBACKGROUNDTRACK:
		S_StopBackgroundTrack();
		return 0;
	case UI_S_STARTBACKGROUNDTRACK:
		S_StartBackgroundTrack(VMA(1), VMA(2), args[3]); // added fadeup time
		return 0;
	case UI_REAL_TIME:
		return Com_RealTime(VMA(1));
	case UI_CIN_PLAYCINEMATIC:
		Com_DPrintf("UI_CIN_PlayCinematic\n");
		return CIN_PlayCinematic(VMA(1), args[2], args[3], args[4], args[5], args[6]);
	case UI_CIN_STOPCINEMATIC:
		return CIN_StopCinematic(args[1]);
	case UI_CIN_RUNCINEMATIC:
		return CIN_RunCinematic(args[1]);
	case UI_CIN_DRAWCINEMATIC:
		CIN_DrawCinematic(args[1]);
		return 0;
	case UI_CIN_SETEXTENTS:
		CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]);
		return 0;
	case UI_R_REMAP_SHADER:
		re.RemapShader(VMA(1), VMA(2), VMA(3));
		return 0;
	case UI_CL_GETLIMBOSTRING:
		return CL_GetLimboString(args[1], VMA(2));
	case UI_CL_TRANSLATE_STRING:
		CL_TranslateStringMod(VMA(1), VMA(2));
		return 0;
	case UI_CHECKAUTOUPDATE:
		CL_RequestMasterData(qfalse);
		return 0;
	case UI_GET_AUTOUPDATE:
		Com_GetAutoUpdate();
		return 0;
	case UI_OPENURL:
		CL_OpenURL((const char *)VMA(1));
		return 0;
	case UI_GETHUNKDATA:
		Com_GetHunkInfo(VMA(1), VMA(2));
		return 0;
	// obsolete
	case UI_SET_PBCLSTATUS:
	case UI_SET_PBSVSTATUS:
		return 0;
	default:
		Com_Error(ERR_DROP, "Bad UI system trap: %ld", (long int) args[0]);
		break;
	}

	return 0;
}
Example #14
0
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     static PTSTR pText ;
     BOOL         bEnable ;
     HGLOBAL      hGlobal ;
     HDC          hdc ;
     PTSTR        pGlobal ;
     PAINTSTRUCT  ps ;
     RECT         rect ;
     
     switch (message)
     {
     case WM_CREATE:
          SendMessage (hwnd, WM_COMMAND, IDM_EDIT_RESET, 0) ;
          return 0 ;

    case WM_INITMENUPOPUP:
          EnableMenuItem ((HMENU) wParam, IDM_EDIT_PASTE,
               IsClipboardFormatAvailable (CF_TCHAR) ? MF_ENABLED : MF_GRAYED) ;

          bEnable = pText ? MF_ENABLED : MF_GRAYED ;

          EnableMenuItem ((HMENU) wParam, IDM_EDIT_CUT,   bEnable) ;
          EnableMenuItem ((HMENU) wParam, IDM_EDIT_COPY,  bEnable) ;
          EnableMenuItem ((HMENU) wParam, IDM_EDIT_CLEAR, bEnable) ;
          break ;
          
     case WM_COMMAND:
          switch (LOWORD (wParam))
          {
          case IDM_EDIT_PASTE:
               OpenClipboard (hwnd) ;

               if (hGlobal = GetClipboardData (CF_TCHAR))
               {
                    pGlobal = GlobalLock (hGlobal) ;

                    if (pText)
                    {
                         free (pText) ;
                         pText = NULL ;
                    }
                    pText = malloc (GlobalSize (hGlobal)) ;
                    lstrcpy (pText, pGlobal) ;
                    InvalidateRect (hwnd, NULL, TRUE) ;
               }
               CloseClipboard () ;
               return 0 ;

          case IDM_EDIT_CUT:
          case IDM_EDIT_COPY:
               if (!pText)
                    return 0 ;

               hGlobal = GlobalAlloc (GHND | GMEM_SHARE, 
                                      (lstrlen (pText) + 1) * sizeof (TCHAR)) ;
               pGlobal = GlobalLock (hGlobal) ;
               lstrcpy (pGlobal, pText) ;
               GlobalUnlock (hGlobal) ;

               OpenClipboard (hwnd) ;
               EmptyClipboard () ;
               SetClipboardData (CF_TCHAR, hGlobal) ;
               CloseClipboard () ;

               if (LOWORD (wParam) == IDM_EDIT_COPY)
                    return 0 ;        
                                             // fall through for IDM_EDIT_CUT
          case IDM_EDIT_CLEAR:
               if (pText)
               {
                    free (pText) ;
                    pText = NULL ;
               }
               InvalidateRect (hwnd, NULL, TRUE) ;
               return 0 ;

          case IDM_EDIT_RESET:
               if (pText)
               {
                    free (pText) ;
                    pText = NULL ;
               }

               pText = malloc ((lstrlen (szDefaultText) + 1) * sizeof (TCHAR)) ;
               lstrcpy (pText, szDefaultText) ;
               InvalidateRect (hwnd, NULL, TRUE) ;
               return 0 ;
          }
          break ;

     case WM_PAINT:
          hdc = BeginPaint (hwnd, &ps) ;

          GetClientRect (hwnd, &rect) ;
          
          if (pText != NULL)
               DrawText (hdc, pText, -1, &rect, DT_EXPANDTABS | DT_WORDBREAK) ;

          EndPaint (hwnd, &ps) ;
          return 0 ;
          
     case WM_DESTROY:
          if (pText)
               free (pText) ;

          PostQuitMessage (0) ;
          return 0 ;
     }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Example #15
0
VOID
DoPaste(
    IN PCONSOLE_INFORMATION Console
    )

/*++

  Perform paste request into old app by sucking out clipboard
        contents and writing them to the console's input buffer

--*/

{
    BOOL Success;
    HANDLE ClipboardDataHandle;

    if (Console->Flags & CONSOLE_SCROLLING) {
        return;
    }

    //
    // Get paste data from clipboard
    //

    Success = OpenClipboard(Console->hWnd);
    if (!Success)
        return;

    if (Console->CurrentScreenBuffer->Flags & CONSOLE_TEXTMODE_BUFFER) {
        PWCHAR pwstr;

        ClipboardDataHandle = GetClipboardData(CF_UNICODETEXT);
        if (ClipboardDataHandle == NULL) {
            CloseClipboard();   // Close clipboard
            return;
        }
        pwstr = GlobalLock(ClipboardDataHandle);
        DoStringPaste(Console,pwstr,GlobalSize(ClipboardDataHandle));
        GlobalUnlock(ClipboardDataHandle);

    } else {
        HBITMAP hBitmapSource,hBitmapTarget;
        HDC hDCMemSource,hDCMemTarget;
        BITMAP bm;
        PSCREEN_INFORMATION ScreenInfo;

        hBitmapSource = GetClipboardData(CF_BITMAP);
        if (hBitmapSource) {

            ScreenInfo = Console->CurrentScreenBuffer;
            NtWaitForSingleObject(ScreenInfo->BufferInfo.GraphicsInfo.hMutex,
                                  FALSE, NULL);

            hBitmapTarget = CreateDIBitmap(ScreenInfo->Console->hDC,
                                     &ScreenInfo->BufferInfo.GraphicsInfo.lpBitMapInfo->bmiHeader,
                                     CBM_INIT,
                                     ScreenInfo->BufferInfo.GraphicsInfo.BitMap,
                                     ScreenInfo->BufferInfo.GraphicsInfo.lpBitMapInfo,
                                     ScreenInfo->BufferInfo.GraphicsInfo.dwUsage
                                    );
            if (hBitmapTarget) {
                hDCMemTarget = CreateCompatibleDC ( Console->hDC );
                hDCMemSource = CreateCompatibleDC ( Console->hDC );
                SelectObject( hDCMemTarget, hBitmapTarget );
                SelectObject( hDCMemSource, hBitmapSource );
                GetObjectW(hBitmapSource, sizeof (BITMAP), (LPSTR) &bm);
                BitBlt ( hDCMemTarget, 0, 0, bm.bmWidth, bm.bmHeight,
                     hDCMemSource, 0, 0, SRCCOPY);
                GetObjectW(hBitmapTarget, sizeof (BITMAP), (LPSTR) &bm);

                // copy the bits from the DC to memory

                GetDIBits(hDCMemTarget, hBitmapTarget, 0, bm.bmHeight,
                          ScreenInfo->BufferInfo.GraphicsInfo.BitMap,
                          ScreenInfo->BufferInfo.GraphicsInfo.lpBitMapInfo,
                          ScreenInfo->BufferInfo.GraphicsInfo.dwUsage);
                DeleteDC(hDCMemSource);
                DeleteDC(hDCMemTarget);
                DeleteObject(hBitmapTarget);
                InvalidateRect(Console->hWnd,NULL,FALSE); // force repaint
            }
            NtReleaseMutant(ScreenInfo->BufferInfo.GraphicsInfo.hMutex, NULL);
        }
    }
    CloseClipboard();
    return;
}
Example #16
0
PUBLIC LONGINT
GetScrapX (LONGINT type, char **h)
{
  UINT format;
  LONGINT retval;

  retval = -1;
  switch (type)
    {
    case T ('T', 'E', 'X', 'T'):
      format = CF_TEXT;
      break;
    default:
      format = ROMlib_executor_format (type);
      if (type == T('P','I','C','T'))
	{
	  typeof (format) newval;
	  UINT formats[2] = { format, CF_DIB };
	  
	  newval = GetPriorityClipboardFormat (formats, NELEM (formats));
	  if (newval != 0 && newval != (UINT) -1)
	    format = newval;
 	  }
      break;
    }
  if (IsClipboardFormatAvailable (format) && OpenClipboard (cygwin_sdlwindow ()))
    {
      HANDLE data;

      data = GetClipboardData (format);
      if (data)
	{
	  LPVOID lp;

	  lp = GlobalLock (data);
	  switch (type)
	    {
	    case T ('T', 'E', 'X', 'T'):
	      {
		int len;

		len = strlen (lp);
		retval = get_scrap_helper (h, lp, len, TRUE);
	      }
	    break;
	    default:
	      {
#if defined (SDL)
		if (format == CF_DIB)
		  retval = get_scrap_helper_dib (h, lp);
		else
#endif
		  {
		    int32 len;
		    len = *(int32 *)lp;

		    retval = get_scrap_helper (h, lp+sizeof(int32),
					       len, FALSE);
		  }
	      }
	      break;
	    }
	  GlobalUnlock (data);
	  CloseClipboard ();
	}
    }
  return retval;
}
Example #17
0
static Image *ReadCLIPBOARDImage(const ImageInfo *image_info,
                                 ExceptionInfo *exception)
{
    Image
    *image;

    MagickBooleanType
    status;

    register ssize_t
    x;

    register PixelPacket
    *q;

    ssize_t
    y;

    assert(image_info != (const ImageInfo *) NULL);
    assert(image_info->signature == MagickSignature);
    if (image_info->debug != MagickFalse)
        (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
                              image_info->filename);
    assert(exception != (ExceptionInfo *) NULL);
    assert(exception->signature == MagickSignature);
    image=AcquireImage(image_info);
    {
        HBITMAP
        bitmapH;

        HPALETTE
        hPal;

        OpenClipboard(NULL);
        bitmapH=(HBITMAP) GetClipboardData(CF_BITMAP);
        hPal=(HPALETTE) GetClipboardData(CF_PALETTE);
        CloseClipboard();
        if (bitmapH == NULL)
            ThrowReaderException(CoderError,"NoBitmapOnClipboard");
        {
            BITMAPINFO
            DIBinfo;

            BITMAP
            bitmap;

            HBITMAP
            hBitmap,
            hOldBitmap;

            HDC
            hDC,
            hMemDC;

            RGBQUAD
            *pBits,
            *ppBits;

            /* create an offscreen DC for the source */
            hMemDC=CreateCompatibleDC(NULL);
            hOldBitmap=(HBITMAP) SelectObject(hMemDC,bitmapH);
            GetObject(bitmapH,sizeof(BITMAP),(LPSTR) &bitmap);
            if ((image->columns == 0) || (image->rows == 0))
            {
                image->columns=bitmap.bmWidth;
                image->rows=bitmap.bmHeight;
            }
            status=SetImageExtent(image,image->columns,image->rows);
            if (status == MagickFalse)
            {
                InheritException(exception,&image->exception);
                return(DestroyImageList(image));
            }
            /*
              Initialize the bitmap header info.
            */
            (void) ResetMagickMemory(&DIBinfo,0,sizeof(BITMAPINFO));
            DIBinfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
            DIBinfo.bmiHeader.biWidth=(LONG) image->columns;
            DIBinfo.bmiHeader.biHeight=(-1)*(LONG) image->rows;
            DIBinfo.bmiHeader.biPlanes=1;
            DIBinfo.bmiHeader.biBitCount=32;
            DIBinfo.bmiHeader.biCompression=BI_RGB;
            hDC=GetDC(NULL);
            if (hDC == 0)
                ThrowReaderException(CoderError,"UnableToCreateADC");
            hBitmap=CreateDIBSection(hDC,&DIBinfo,DIB_RGB_COLORS,(void **) &ppBits,
                                     NULL,0);
            ReleaseDC(NULL,hDC);
            if (hBitmap == 0)
                ThrowReaderException(CoderError,"UnableToCreateBitmap");
            /* create an offscreen DC */
            hDC=CreateCompatibleDC(NULL);
            if (hDC == 0)
            {
                DeleteObject(hBitmap);
                ThrowReaderException(CoderError,"UnableToCreateADC");
            }
            hOldBitmap=(HBITMAP) SelectObject(hDC,hBitmap);
            if (hOldBitmap == 0)
            {
                DeleteDC(hDC);
                DeleteObject(hBitmap);
                ThrowReaderException(CoderError,"UnableToCreateBitmap");
            }
            if (hPal != NULL)
            {
                /* Kenichi Masuko says this needed */
                SelectPalette(hDC, hPal, FALSE);
                RealizePalette(hDC);
            }
            /* bitblt from the memory to the DIB-based one */
            BitBlt(hDC,0,0,(int) image->columns,(int) image->rows,hMemDC,0,0,SRCCOPY);
            /* finally copy the pixels! */
            pBits=ppBits;
            for (y=0; y < (ssize_t) image->rows; y++)
            {
                q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
                if (q == (PixelPacket *) NULL)
                    break;
                for (x=0; x < (ssize_t) image->columns; x++)
                {
                    SetPixelRed(q,ScaleCharToQuantum(pBits->rgbRed));
                    SetPixelGreen(q,ScaleCharToQuantum(pBits->rgbGreen));
                    SetPixelBlue(q,ScaleCharToQuantum(pBits->rgbBlue));
                    SetPixelOpacity(q,OpaqueOpacity);
                    pBits++;
                    q++;
                }
                if (SyncAuthenticPixels(image,exception) == MagickFalse)
                    break;
            }
            DeleteDC(hDC);
            DeleteObject(hBitmap);
        }
    }
    (void) CloseBlob(image);
    return(GetFirstImageInList(image));
}
Example #18
0
void CUSBLogView::OnEditPaste(void) 
{
    if(!IsClipboardFormatAvailable(GetApp().m_uClipboardFormat))
    {
        TRACE("OnEditPaste(): no suitable clipboard format available!\n");
        return;
    }

    // we need a focused URB as well...
    int nFocusedURB = m_Log.FindFocusedURB();
    if(-1 == nFocusedURB)
    {
        nFocusedURB = 0;
    }

    if(!AfxGetMainWnd()->OpenClipboard())
    {
        TRACE("Error while opening clipboard!\n");
        return;
    }
    // from here on, we have to close the clipboard
    // before exiting this function, otherwise other
    // applications might not get a chance to copy/paste
    // stuff!
    HANDLE hBinary = NULL;
    PVOID pData = NULL;
    try
    {
        hBinary = GetClipboardData(GetApp().m_uClipboardFormat);
        if(NULL == hBinary)
        {
            AfxThrowNotSupportedException();
        }

        pData = GlobalLock(hBinary);
        {
            CMyMemFile memFile(pData);
            CArchive ar(&memFile, CArchive::load);
            DWORD dwVersion = ar.ReadCount();
            if(_VERSION_DWORD_ != dwVersion)
            {
                AfxThrowNotSupportedException();
            }

            DWORD nURBCnt = ar.ReadCount();
            TRACE("Pasting %d URBs...\n", nURBCnt);
            
            CUSBLogDoc *pDoc = GetDocument();
            int nInsertLocation = nFocusedURB;
            while(0 < nURBCnt)
            {
                CRuntimeClass *pClass = ar.ReadClass();
                if(!pClass->IsDerivedFrom(RUNTIME_CLASS(CURB)))
                {
                    TRACE("unknown runtime class!\n");
                    AfxThrowArchiveException(CArchiveException::badClass);
                }

                CURB *pURB = (CURB*) pClass->CreateObject();
                ASSERT(NULL != pURB);
                pURB->SetChunkAllocator(&pDoc->m_arURB.m_ChunkAllocator);
                pURB->Serialize(ar);
                pDoc->m_arURB.InsertAt(nInsertLocation, pURB);
                nInsertLocation++;
                --nURBCnt;
            }
            pDoc->UpdateAllViews(NULL, 1);
            OnEditSelectNone();
            m_Log.SetFocusedURB(nFocusedURB);            
        }

        GlobalUnlock(hBinary);
        hBinary = NULL;

        CloseClipboard();
    }
    catch(...)
    {
        if((NULL != pData) && (NULL != hBinary))
        {
            GlobalUnlock(hBinary);
        }
        CloseClipboard();
        throw;
    }
}
Example #19
0
static int CustomButtonPressed(WPARAM, LPARAM lParam)
{
	CustomButtonClickData *cbcd = (CustomButtonClickData *)lParam;

	CHARRANGE cr;
	HWND hEdit = NULL;
	BOOL bCTRL = 0;
	BOOL bIsService = 0;
	TCHAR* pszText = NULL;
	TCHAR* pszCBText = NULL;
	TCHAR* ptszQValue = NULL;
	UINT textlenght = 0;
	SortedList* sl = NULL;
	int state = 0;

	if (mir_strcmp(cbcd->pszModule, PLGNAME)) return 0;

	if (!ButtonsList[cbcd->dwButtonId]) return 1;

	sl = ButtonsList[cbcd->dwButtonId]->sl;

	if (!sl) return 1;

	if (IsClipboardFormatAvailable(CF_TEXT)) {
		if (OpenClipboard(cbcd->hwndFrom)) {
			HANDLE hData = NULL;
			TCHAR* chBuffer = NULL;
			int textLength = 0;

			hData = GetClipboardData(CF_UNICODETEXT);

			chBuffer = (TCHAR*)GlobalLock(hData);
			textLength = (int)mir_tstrlen(chBuffer);
			pszCBText = mir_tstrdup(chBuffer);
			GlobalUnlock(hData);
			CloseClipboard();
		}
	}

	qsort(sl->items, sl->realCount, sizeof(ButtonData *), sstSortButtons);

	hEdit = GetDlgItem(cbcd->hwndFrom, IDC_MESSAGE);
	if (!hEdit) hEdit = GetDlgItem(cbcd->hwndFrom, IDC_CHATMESSAGE);

	cr.cpMin = cr.cpMax = 0;
	SendMessage(hEdit, EM_EXGETSEL, 0, (LPARAM)&cr);

	textlenght = cr.cpMax - cr.cpMin;
	if (textlenght) {
		pszText = (TCHAR *)mir_alloc((textlenght + 10)*sizeof(TCHAR));
		memset(pszText, 0, ((textlenght + 10) * sizeof(TCHAR)));
		SendMessage(hEdit, EM_GETSELTEXT, 0, (LPARAM)pszText);
	}

	if (cbcd->flags&BBCF_RIGHTBUTTON)
		state = 1;
	else if (sl->realCount == 1)
		state = 2;
	else
		state = 3;

	switch (state) {
	case 1:
		if (ButtonsList[cbcd->dwButtonId]->ptszQValue)
			ptszQValue = ParseString(cbcd->hContact, ButtonsList[cbcd->dwButtonId]->ptszQValue, pszText ? pszText : _T(""), pszCBText ? pszCBText : _T(""), (int)mir_tstrlen(ButtonsList[cbcd->dwButtonId]->ptszQValue), textlenght, pszCBText ? (int)mir_tstrlen(pszCBText) : 0);
		if ((bIsService = ButtonsList[cbcd->dwButtonId]->bIsServName) && ptszQValue)
			CallService(mir_u2a(ptszQValue), (WPARAM)cbcd->hContact, 0);
		break;

	case 2:
		{
			ButtonData *bd = (ButtonData *)sl->items[0];
			if (bd && bd->pszValue) {
				ptszQValue = ParseString(cbcd->hContact, bd->pszValue, pszText ? pszText : _T(""), pszCBText ? pszCBText : _T(""), (int)mir_tstrlen(bd->pszValue), textlenght, pszCBText ? (int)mir_tstrlen(pszCBText) : 0);
				if ((bIsService = bd->bIsServName) && ptszQValue)
					CallService(mir_u2a(ptszQValue), (WPARAM)cbcd->hContact, 0);
			}
		}
		break;

	case 3:
		if (!g_iButtonsCount)
			break;
			
		HMENU hMenu = CreatePopupMenu(), hSubMenu = NULL;

		for (int menunum = 0; menunum < sl->realCount; menunum++) {
			ButtonData *bd = (ButtonData *)sl->items[menunum];
			if (bd->dwOPFlags&QMF_NEW)
				continue;

			BOOL bSetPopupMark = FALSE;
			if (bd->pszValue == 0 && bd->fEntryType == 0) {
				hSubMenu = CreatePopupMenu();
				bSetPopupMark = TRUE;
			}

			if (bd->pszValue && bd->fEntryType == 0)
				hSubMenu = NULL;

			if (bd->fEntryType&QMF_EX_SEPARATOR)
				AppendMenu((HMENU)((hSubMenu && !bSetPopupMark) ? hSubMenu : hMenu), MF_SEPARATOR, 0, NULL);
			else
				AppendMenu((HMENU)((hSubMenu && !bSetPopupMark) ? hSubMenu : hMenu),
				MF_STRING | (bSetPopupMark ? MF_POPUP : 0),
				(bSetPopupMark ? (UINT_PTR)hSubMenu : (menunum + 1)), bd->pszName);
		}

		int res = TrackPopupMenu(hMenu, TPM_RETURNCMD, cbcd->pt.x, cbcd->pt.y, 0, cbcd->hwndFrom, NULL);
		if (res == 0)
			break;

		ButtonData *bd = (ButtonData *)sl->items[res - 1];
		bCTRL = (GetKeyState(VK_CONTROL) & 0x8000) ? 1 : 0;
		if (bd->pszValue) {
			ptszQValue = ParseString(cbcd->hContact, bd->pszValue, pszText ? pszText : _T(""), pszCBText ? pszCBText : _T(""), (int)mir_tstrlen(bd->pszValue), textlenght, pszCBText ? (int)mir_tstrlen(pszCBText) : 0);
			if ((bIsService = bd->bIsServName) && ptszQValue)
				CallService(mir_u2a(ptszQValue), (WPARAM)cbcd->hContact, 0);
		}
		break;
	}

	if (ptszQValue) {
		if (!bIsService) {
			SendMessage(hEdit, EM_REPLACESEL, TRUE, (LPARAM)ptszQValue);

			if ((g_bLClickAuto&&state != 1) || (g_bRClickAuto&&state == 1) || cbcd->flags&BBCF_CONTROLPRESSED || bCTRL)
				SendMessage(cbcd->hwndFrom, WM_COMMAND, IDOK, 0);
		}
		free(ptszQValue);
	}


	mir_free(pszText);
	mir_free(pszCBText);
	return 1;
}
Example #20
0
/*
====================
CL_UISystemCalls

The ui module is making a system call
====================
*/
intptr_t CL_UISystemCalls( intptr_t *args ) {
	switch ( args[0] ) {
	case UI_ERROR:
		Com_Error( ERR_DROP, "%s", VMA( 1 ) );
		return 0;

	case UI_PRINT:
		Com_Printf( "%s", VMA( 1 ) );
		return 0;

	case UI_MILLISECONDS:
		return Sys_Milliseconds();

	case UI_CVAR_REGISTER:
		Cvar_Register( VMA( 1 ), VMA( 2 ), VMA( 3 ), args[4] );
		return 0;

	case UI_CVAR_UPDATE:
		Cvar_Update( VMA( 1 ) );
		return 0;

	case UI_CVAR_SET:
		Cvar_Set( VMA( 1 ), VMA( 2 ) );
		return 0;

	case UI_CVAR_VARIABLEVALUE:
		return FloatAsInt( Cvar_VariableValue( VMA( 1 ) ) );

	case UI_CVAR_VARIABLESTRINGBUFFER:
		Cvar_VariableStringBuffer( VMA( 1 ), VMA( 2 ), args[3] );
		return 0;

	case UI_CVAR_SETVALUE:
		Cvar_SetValue( VMA( 1 ), VMF( 2 ) );
		return 0;

	case UI_CVAR_RESET:
		Cvar_Reset( VMA( 1 ) );
		return 0;

	case UI_CVAR_CREATE:
		Cvar_Get( VMA( 1 ), VMA( 2 ), args[3] );
		return 0;

	case UI_CVAR_INFOSTRINGBUFFER:
		Cvar_InfoStringBuffer( args[1], VMA( 2 ), args[3] );
		return 0;

	case UI_ARGC:
		return Cmd_Argc();

	case UI_ARGV:
		Cmd_ArgvBuffer( args[1], VMA( 2 ), args[3] );
		return 0;

	case UI_CMD_EXECUTETEXT:
		Cbuf_ExecuteText( args[1], VMA( 2 ) );
		return 0;

	case UI_FS_FOPENFILE:
		return FS_FOpenFileByMode( VMA( 1 ), VMA( 2 ), args[3] );

	case UI_FS_READ:
		FS_Read( VMA( 1 ), args[2], args[3] );
		return 0;

//----(SA)	added
	case UI_FS_SEEK:
		FS_Seek( args[1], args[2], args[3] );
		return 0;
//----(SA)	end

	case UI_FS_WRITE:
		FS_Write( VMA( 1 ), args[2], args[3] );
		return 0;

	case UI_FS_FCLOSEFILE:
		FS_FCloseFile( args[1] );
		return 0;

	case UI_FS_DELETEFILE:
		return FS_Delete( VMA( 1 ) );

	case UI_FS_GETFILELIST:
		return FS_GetFileList( VMA( 1 ), VMA( 2 ), VMA( 3 ), args[4] );

	case UI_R_REGISTERMODEL:
		return re.RegisterModel( VMA( 1 ) );

	case UI_R_REGISTERSKIN:
		return re.RegisterSkin( VMA( 1 ) );

	case UI_R_REGISTERSHADERNOMIP:
		return re.RegisterShaderNoMip( VMA( 1 ) );

	case UI_R_CLEARSCENE:
		re.ClearScene();
		return 0;

	case UI_R_ADDREFENTITYTOSCENE:
		re.AddRefEntityToScene( VMA( 1 ) );
		return 0;

	case UI_R_ADDPOLYTOSCENE:
		re.AddPolyToScene( args[1], args[2], VMA( 3 ) );
		return 0;

		// Ridah
	case UI_R_ADDPOLYSTOSCENE:
		re.AddPolysToScene( args[1], args[2], VMA( 3 ), args[4] );
		return 0;
		// done.

	case UI_R_ADDLIGHTTOSCENE:
		re.AddLightToScene( VMA( 1 ), VMF( 2 ), VMF( 3 ), VMF( 4 ), VMF( 5 ), args[6] );
		return 0;

	case UI_R_ADDCORONATOSCENE:
		re.AddCoronaToScene( VMA( 1 ), VMF( 2 ), VMF( 3 ), VMF( 4 ), VMF( 5 ), args[6], args[7] );
		return 0;

	case UI_R_RENDERSCENE:
		re.RenderScene( VMA( 1 ) );
		return 0;

	case UI_R_SETCOLOR:
		re.SetColor( VMA( 1 ) );
		return 0;

	case UI_R_DRAWSTRETCHPIC:
		re.DrawStretchPic( VMF( 1 ), VMF( 2 ), VMF( 3 ), VMF( 4 ), VMF( 5 ), VMF( 6 ), VMF( 7 ), VMF( 8 ), args[9] );
		return 0;

	case UI_R_MODELBOUNDS:
		re.ModelBounds( args[1], VMA( 2 ), VMA( 3 ) );
		return 0;

	case UI_UPDATESCREEN:
		SCR_UpdateScreen();
		return 0;

	case UI_CM_LERPTAG:
		return re.LerpTag( VMA( 1 ), VMA( 2 ), VMA( 3 ), args[4] );

	case UI_S_REGISTERSOUND:
#ifdef DOOMSOUND    ///// (SA) DOOMSOUND
		return S_RegisterSound( VMA( 1 ) );
#else
		return S_RegisterSound( VMA( 1 ), qfalse );
#endif  ///// (SA) DOOMSOUND

	case UI_S_STARTLOCALSOUND:
		S_StartLocalSound( args[1], args[2] );
		return 0;

//----(SA)	added
	case UI_S_FADESTREAMINGSOUND:
		S_FadeStreamingSound( VMF( 1 ), args[2], args[3] );
		return 0;

	case UI_S_FADEALLSOUNDS:
		S_FadeAllSounds( VMF( 1 ), args[2] );
		return 0;
//----(SA)	end

	case UI_KEY_KEYNUMTOSTRINGBUF:
		Key_KeynumToStringBuf( args[1], VMA( 2 ), args[3] );
		return 0;

	case UI_KEY_GETBINDINGBUF:
		Key_GetBindingBuf( args[1], VMA( 2 ), args[3] );
		return 0;

	case UI_KEY_SETBINDING:
		Key_SetBinding( args[1], VMA( 2 ) );
		return 0;

	case UI_KEY_ISDOWN:
		return Key_IsDown( args[1] );

	case UI_KEY_GETOVERSTRIKEMODE:
		return Key_GetOverstrikeMode();

	case UI_KEY_SETOVERSTRIKEMODE:
		Key_SetOverstrikeMode( args[1] );
		return 0;

	case UI_KEY_CLEARSTATES:
		Key_ClearStates();
		return 0;

	case UI_KEY_GETCATCHER:
		return Key_GetCatcher();

	case UI_KEY_SETCATCHER:
		Key_SetCatcher( args[1] );
		return 0;

	case UI_GETCLIPBOARDDATA:
		GetClipboardData( VMA( 1 ), args[2] );
		return 0;

	case UI_GETCLIENTSTATE:
		GetClientState( VMA( 1 ) );
		return 0;

	case UI_GETGLCONFIG:
		CL_GetGlconfig( VMA( 1 ) );
		return 0;

	case UI_GETCONFIGSTRING:
		return GetConfigString( args[1], VMA( 2 ), args[3] );

	case UI_LAN_LOADCACHEDSERVERS:
		LAN_LoadCachedServers();
		return 0;

	case UI_LAN_SAVECACHEDSERVERS:
		LAN_SaveServersToCache();
		return 0;

	case UI_LAN_ADDSERVER:
		return LAN_AddServer( args[1], VMA( 2 ), VMA( 3 ) );

	case UI_LAN_REMOVESERVER:
		LAN_RemoveServer( args[1], VMA( 2 ) );
		return 0;

	case UI_LAN_GETPINGQUEUECOUNT:
		return LAN_GetPingQueueCount();

	case UI_LAN_CLEARPING:
		LAN_ClearPing( args[1] );
		return 0;

	case UI_LAN_GETPING:
		LAN_GetPing( args[1], VMA( 2 ), args[3], VMA( 4 ) );
		return 0;

	case UI_LAN_GETPINGINFO:
		LAN_GetPingInfo( args[1], VMA( 2 ), args[3] );
		return 0;

	case UI_LAN_GETSERVERCOUNT:
		return LAN_GetServerCount( args[1] );

	case UI_LAN_GETSERVERADDRESSSTRING:
		LAN_GetServerAddressString( args[1], args[2], VMA( 3 ), args[4] );
		return 0;

	case UI_LAN_GETSERVERINFO:
		LAN_GetServerInfo( args[1], args[2], VMA( 3 ), args[4] );
		return 0;

	case UI_LAN_GETSERVERPING:
		return LAN_GetServerPing( args[1], args[2] );

	case UI_LAN_MARKSERVERVISIBLE:
		LAN_MarkServerVisible( args[1], args[2], args[3] );
		return 0;

	case UI_LAN_SERVERISVISIBLE:
		return LAN_ServerIsVisible( args[1], args[2] );

	case UI_LAN_UPDATEVISIBLEPINGS:
		return LAN_UpdateVisiblePings( args[1] );

	case UI_LAN_RESETPINGS:
		LAN_ResetPings( args[1] );
		return 0;

	case UI_LAN_SERVERSTATUS:
		return LAN_GetServerStatus( VMA( 1 ), VMA( 2 ), args[3] );

	case UI_LAN_COMPARESERVERS:
		return LAN_CompareServers( args[1], args[2], args[3], args[4], args[5] );

	case UI_MEMORY_REMAINING:
		return Hunk_MemoryRemaining();

	case UI_GET_CDKEY:
		CLUI_GetCDKey( VMA( 1 ), args[2] );
		return 0;

	case UI_SET_CDKEY:
		CLUI_SetCDKey( VMA( 1 ) );
		return 0;

	case UI_R_REGISTERFONT:
		re.RegisterFont( VMA( 1 ), args[2], VMA( 3 ) );
		return 0;

	case UI_MEMSET:
		return (intptr_t)memset( VMA( 1 ), args[2], args[3] );

	case UI_MEMCPY:
		return (intptr_t)memcpy( VMA( 1 ), VMA( 2 ), args[3] );

	case UI_STRNCPY:
		return (intptr_t)strncpy( VMA( 1 ), VMA( 2 ), args[3] );

	case UI_SIN:
		return FloatAsInt( sin( VMF( 1 ) ) );

	case UI_COS:
		return FloatAsInt( cos( VMF( 1 ) ) );

	case UI_ATAN2:
		return FloatAsInt( atan2( VMF( 1 ), VMF( 2 ) ) );

	case UI_SQRT:
		return FloatAsInt( sqrt( VMF( 1 ) ) );

	case UI_FLOOR:
		return FloatAsInt( floor( VMF( 1 ) ) );

	case UI_CEIL:
		return FloatAsInt( ceil( VMF( 1 ) ) );

	case UI_PC_ADD_GLOBAL_DEFINE:
		return botlib_export->PC_AddGlobalDefine( VMA( 1 ) );
	case UI_PC_LOAD_SOURCE:
		return botlib_export->PC_LoadSourceHandle( VMA( 1 ) );
	case UI_PC_FREE_SOURCE:
		return botlib_export->PC_FreeSourceHandle( args[1] );
	case UI_PC_READ_TOKEN:
		return botlib_export->PC_ReadTokenHandle( args[1], VMA( 2 ) );
	case UI_PC_SOURCE_FILE_AND_LINE:
		return botlib_export->PC_SourceFileAndLine( args[1], VMA( 2 ), VMA( 3 ) );

	case UI_S_STOPBACKGROUNDTRACK:
		S_StopBackgroundTrack();
		return 0;
	case UI_S_STARTBACKGROUNDTRACK:
		S_StartBackgroundTrack( VMA( 1 ), VMA( 2 ), args[3] );   //----(SA)	added fadeup time
		return 0;

	case UI_REAL_TIME:
		return Com_RealTime( VMA( 1 ) );

	case UI_CIN_PLAYCINEMATIC:
		Com_DPrintf( "UI_CIN_PlayCinematic\n" );
		return CIN_PlayCinematic( VMA( 1 ), args[2], args[3], args[4], args[5], args[6] );

	case UI_CIN_STOPCINEMATIC:
		return CIN_StopCinematic( args[1] );

	case UI_CIN_RUNCINEMATIC:
		return CIN_RunCinematic( args[1] );

	case UI_CIN_DRAWCINEMATIC:
		CIN_DrawCinematic( args[1] );
		return 0;

	case UI_CIN_SETEXTENTS:
		CIN_SetExtents( args[1], args[2], args[3], args[4], args[5] );
		return 0;

	case UI_R_REMAP_SHADER:
		re.RemapShader( VMA( 1 ), VMA( 2 ), VMA( 3 ) );
		return 0;

	case UI_VERIFY_CDKEY:
		return CL_CDKeyValidate( VMA( 1 ), VMA( 2 ) );

		// NERVE - SMF
	case UI_CL_GETLIMBOSTRING:
		return CL_GetLimboString( args[1], VMA( 2 ) );
		// -NERVE - SMF

	default:
		Com_Error( ERR_DROP, "Bad UI system trap: %i", args[0] );

	}

	return 0;
}
int
camera_device_start_capturing(CameraDevice* cd,
                              uint32_t pixel_format,
                              int frame_width,
                              int frame_height)
{
    WndCameraDevice* wcd;
    HBITMAP bm_handle;
    BITMAP  bitmap;
    size_t format_info_size;
    CAPTUREPARMS cap_param;

    if (cd == NULL || cd->opaque == NULL) {
        E("%s: Invalid camera device descriptor", __FUNCTION__);
        return -1;
    }
    wcd = (WndCameraDevice*)cd->opaque;

    /* wcd->dc is an indicator of capturing: !NULL - capturing, NULL - not */
    if (wcd->dc != NULL) {
        W("%s: Capturing is already on on device '%s'",
          __FUNCTION__, wcd->window_name);
        return 0;
    }

    /* Connect capture window to the video capture driver. */
    if (!capDriverConnect(wcd->cap_window, wcd->input_channel)) {
        return -1;
    }

    /* Get current frame information from the driver. */
    format_info_size = capGetVideoFormatSize(wcd->cap_window);
    if (format_info_size == 0) {
        E("%s: Unable to get video format size: %d",
          __FUNCTION__, GetLastError());
        _camera_device_reset(wcd);
        return -1;
    }
    wcd->frame_bitmap = (BITMAPINFO*)malloc(format_info_size);
    if (wcd->frame_bitmap == NULL) {
        E("%s: Unable to allocate frame bitmap info buffer", __FUNCTION__);
        _camera_device_reset(wcd);
        return -1;
    }
    if (!capGetVideoFormat(wcd->cap_window, wcd->frame_bitmap,
                           format_info_size)) {
        E("%s: Unable to obtain video format: %d", __FUNCTION__, GetLastError());
        _camera_device_reset(wcd);
        return -1;
    }

    /* Lets see if we need to set different frame dimensions */
    if (wcd->frame_bitmap->bmiHeader.biWidth != frame_width ||
            abs(wcd->frame_bitmap->bmiHeader.biHeight) != frame_height) {
        /* Dimensions don't match. Set new frame info. */
        wcd->frame_bitmap->bmiHeader.biWidth = frame_width;
        wcd->frame_bitmap->bmiHeader.biHeight = frame_height;
        /* We need to recalculate image size, since the capture window / driver
         * will use image size provided by us. */
        if (wcd->frame_bitmap->bmiHeader.biBitCount == 24) {
            /* Special case that may require WORD boundary alignment. */
            uint32_t bpl = (frame_width * 3 + 1) & ~1;
            wcd->frame_bitmap->bmiHeader.biSizeImage = bpl * frame_height;
        } else {
            wcd->frame_bitmap->bmiHeader.biSizeImage =
                (frame_width * frame_height * wcd->frame_bitmap->bmiHeader.biBitCount) / 8;
        }
        if (!capSetVideoFormat(wcd->cap_window, wcd->frame_bitmap,
                               format_info_size)) {
            E("%s: Unable to set video format: %d", __FUNCTION__, GetLastError());
            _camera_device_reset(wcd);
            return -1;
        }
    }

    if (wcd->frame_bitmap->bmiHeader.biCompression > BI_PNG) {
        D("%s: Video capturing driver has reported pixel format %.4s",
          __FUNCTION__, (const char*)&wcd->frame_bitmap->bmiHeader.biCompression);
    }

    /* Most of the time frame bitmaps come in "bottom-up" form, where its origin
     * is the lower-left corner. However, it could be in the normal "top-down"
     * form with the origin in the upper-left corner. So, we must adjust the
     * biHeight field, since the way "top-down" form is reported here is by
     * setting biHeight to a negative value. */
    if (wcd->frame_bitmap->bmiHeader.biHeight < 0) {
        wcd->frame_bitmap->bmiHeader.biHeight =
            -wcd->frame_bitmap->bmiHeader.biHeight;
        wcd->is_top_down = 1;
    } else {
        wcd->is_top_down = 0;
    }

    /* Get DC for the capturing window that will be used when we deal with
     * bitmaps obtained from the camera device during frame capturing. */
    wcd->dc = GetDC(wcd->cap_window);
    if (wcd->dc == NULL) {
        E("%s: Unable to obtain DC for %s: %d",
          __FUNCTION__, wcd->window_name, GetLastError());
        _camera_device_reset(wcd);
        return -1;
    }

    /* Setup some capture parameters. */
    if (capCaptureGetSetup(wcd->cap_window, &cap_param, sizeof(cap_param))) {
        /* Use separate thread to capture video stream. */
        cap_param.fYield = TRUE;
        /* Don't show any dialogs. */
        cap_param.fMakeUserHitOKToCapture = FALSE;
        capCaptureSetSetup(wcd->cap_window, &cap_param, sizeof(cap_param));
    }

    /*
     * At this point we need to grab a frame to properly setup framebuffer, and
     * calculate pixel format. The problem is that bitmap information obtained
     * from the driver doesn't necessarily match the actual bitmap we're going to
     * obtain via capGrabFrame / capEditCopy / GetClipboardData
     */

    /* Grab a frame, and post it to the clipboard. Not very effective, but this
     * is how capXxx API is operating. */
    if (!capGrabFrameNoStop(wcd->cap_window) ||
        !capEditCopy(wcd->cap_window) ||
        !OpenClipboard(wcd->cap_window)) {
        E("%s: Device '%s' is unable to save frame to the clipboard: %d",
          __FUNCTION__, wcd->window_name, GetLastError());
        _camera_device_reset(wcd);
        return -1;
    }

    /* Get bitmap handle saved into clipboard. Note that bitmap is still
     * owned by the clipboard here! */
    bm_handle = (HBITMAP)GetClipboardData(CF_BITMAP);
    if (bm_handle == NULL) {
        E("%s: Device '%s' is unable to obtain frame from the clipboard: %d",
          __FUNCTION__, wcd->window_name, GetLastError());
        CloseClipboard();
        _camera_device_reset(wcd);
        return -1;
    }

    /* Get bitmap object that is initialized with the actual bitmap info. */
    if (!GetObject(bm_handle, sizeof(BITMAP), &bitmap)) {
        E("%s: Device '%s' is unable to obtain frame's bitmap: %d",
          __FUNCTION__, wcd->window_name, GetLastError());
        EmptyClipboard();
        CloseClipboard();
        _camera_device_reset(wcd);
        return -1;
    }

    /* Now that we have all we need in 'bitmap' */
    EmptyClipboard();
    CloseClipboard();

    /* Make sure that dimensions match. Othewise - fail. */
    if (wcd->frame_bitmap->bmiHeader.biWidth != bitmap.bmWidth ||
        wcd->frame_bitmap->bmiHeader.biHeight != bitmap.bmHeight ) {
        E("%s: Requested dimensions %dx%d do not match the actual %dx%d",
          __FUNCTION__, frame_width, frame_height,
          wcd->frame_bitmap->bmiHeader.biWidth,
          wcd->frame_bitmap->bmiHeader.biHeight);
        _camera_device_reset(wcd);
        return -1;
    }

    /* Create bitmap info that will be used with GetDIBits. */
    wcd->gdi_bitmap = (BITMAPINFO*)malloc(wcd->frame_bitmap->bmiHeader.biSize);
    if (wcd->gdi_bitmap == NULL) {
        E("%s: Unable to allocate gdi bitmap info", __FUNCTION__);
        _camera_device_reset(wcd);
        return -1;
    }
    memcpy(wcd->gdi_bitmap, wcd->frame_bitmap,
           wcd->frame_bitmap->bmiHeader.biSize);
    wcd->gdi_bitmap->bmiHeader.biCompression = BI_RGB;
    wcd->gdi_bitmap->bmiHeader.biBitCount = bitmap.bmBitsPixel;
    wcd->gdi_bitmap->bmiHeader.biSizeImage = bitmap.bmWidthBytes * bitmap.bmWidth;
    /* Adjust GDI's bitmap biHeight for proper frame direction ("top-down", or
     * "bottom-up") We do this trick in order to simplify pixel format conversion
     * routines, where we always assume "top-down" frames. The trick he is to
     * have negative biHeight in 'gdi_bitmap' if driver provides "bottom-up"
     * frames, and positive biHeight in 'gdi_bitmap' if driver provides "top-down"
     * frames. This way GetGDIBits will always return "top-down" frames. */
    if (wcd->is_top_down) {
        wcd->gdi_bitmap->bmiHeader.biHeight =
            wcd->frame_bitmap->bmiHeader.biHeight;
    } else {
        wcd->gdi_bitmap->bmiHeader.biHeight =
            -wcd->frame_bitmap->bmiHeader.biHeight;
    }

    /* Allocate framebuffer. */
    wcd->framebuffer = (uint8_t*)malloc(wcd->gdi_bitmap->bmiHeader.biSizeImage);
    if (wcd->framebuffer == NULL) {
        E("%s: Unable to allocate %d bytes for framebuffer",
          __FUNCTION__, wcd->gdi_bitmap->bmiHeader.biSizeImage);
        _camera_device_reset(wcd);
        return -1;
    }

    /* Lets see what pixel format we will use. */
    if (wcd->gdi_bitmap->bmiHeader.biBitCount == 16) {
        wcd->pixel_format = V4L2_PIX_FMT_RGB565;
    } else if (wcd->gdi_bitmap->bmiHeader.biBitCount == 24) {
        wcd->pixel_format = V4L2_PIX_FMT_BGR24;
    } else if (wcd->gdi_bitmap->bmiHeader.biBitCount == 32) {
        wcd->pixel_format = V4L2_PIX_FMT_BGR32;
    } else {
        E("%s: Unsupported number of bits per pixel %d",
          __FUNCTION__, wcd->gdi_bitmap->bmiHeader.biBitCount);
        _camera_device_reset(wcd);
        return -1;
    }

    D("%s: Capturing device '%s': %d bits per pixel in %.4s [%dx%d] frame",
      __FUNCTION__, wcd->window_name, wcd->gdi_bitmap->bmiHeader.biBitCount,
      (const char*)&wcd->pixel_format, wcd->frame_bitmap->bmiHeader.biWidth,
      wcd->frame_bitmap->bmiHeader.biHeight);

    /* Try to setup capture frame callback. */
    wcd->use_clipboard = 1;
    if (capSetCallbackOnFrame(wcd->cap_window, _on_captured_frame)) {
        /* Callback is set. Don't use clipboard when capturing frames. */
        wcd->use_clipboard = 0;
    }

    return 0;
}
Example #22
0
//
// I_GetClipboardText
//
// by Denis Lukianov - 20 Mar 2006
// Cross-platform clipboard functionality
//
std::string I_GetClipboardText (void)
{
#ifdef X11
	std::string ret;
	
	Display *dis = XOpenDisplay(NULL);
	int screen = DefaultScreen(dis);
	
	if(!dis)
	{
		Printf(PRINT_HIGH, "I_GetClipboardText: XOpenDisplay failed");
		return "";
	}
	
	XLockDisplay(dis);
	
	Window WindowEvents = XCreateSimpleWindow(dis, RootWindow(dis, screen), 0, 0, 1, 1, 0, BlackPixel(dis, screen), BlackPixel(dis, screen));

	if(XGetSelectionOwner(dis, XA_PRIMARY) != None)
	{
		if(!XConvertSelection(dis, XA_PRIMARY, XA_STRING, XA_PRIMARY, WindowEvents, CurrentTime))
		{
			XDestroyWindow(dis, WindowEvents);
			XUnlockDisplay(dis);
			XCloseDisplay(dis);
			Printf(PRINT_HIGH, "I_GetClipboardText: XConvertSelection failed");
			return "";
		}
		
		XFlush (dis);
		
		// Wait for the reply
		for(;;)
		{
			XEvent e;
			XNextEvent(dis, &e);

			if(e.type == SelectionNotify)
				break;
		}
		
		Atom type;
		int format, result;
		u_long len, bytes_left, temp;
		u_char *data;

		result = XGetWindowProperty(dis, WindowEvents, XA_PRIMARY, 0, 0, False, AnyPropertyType, &type, &format, &len, &bytes_left, &data);
		if(result != Success)
		{
			XDestroyWindow(dis, WindowEvents);
			XUnlockDisplay(dis);
			XCloseDisplay(dis);
			Printf(PRINT_HIGH, "I_GetClipboardText: XGetWindowProperty failed(1)");
			return "";
		}
		
		if(!bytes_left)
		{
			XDestroyWindow(dis, WindowEvents);
			Printf(PRINT_HIGH, "I_GetClipboardText: Len was: %d", len);
			XUnlockDisplay(dis);
			XCloseDisplay(dis);
			return "";
		}
		
		result = XGetWindowProperty(dis, WindowEvents, XA_PRIMARY, 0, bytes_left, False, AnyPropertyType, &type, &format, &len, &temp, &data);
		if(result != Success)
		{
			XDestroyWindow(dis, WindowEvents);
			XUnlockDisplay(dis);
			XCloseDisplay(dis);
			Printf(PRINT_HIGH, "I_GetClipboardText: XGetWindowProperty failed(2)");
			return "";
		}
	
		ret = std::string((const char *)data, len);
		XFree(data);
	}

	XDestroyWindow(dis, WindowEvents);
	XUnlockDisplay(dis);
	XCloseDisplay(dis);
	
	return ret;
#endif

#ifdef WIN32
	std::string ret;

	if(!IsClipboardFormatAvailable(CF_TEXT))
		return "";

	if(!OpenClipboard(NULL))
		return "";
	
	HANDLE hClipboardData = GetClipboardData(CF_TEXT);
		
	if(!hClipboardData)
	{
		CloseClipboard();
		return "";
	}
	
	const char *cData = reinterpret_cast<const char *>(GlobalLock(hClipboardData));
	u_int uiSize = static_cast<u_int>(GlobalSize(hClipboardData));
			
	if(cData && uiSize)
	{
		for(size_t i = 0; i < uiSize; i++)
		{
			if(!cData[i])
			{
				uiSize = i;
				break;
			}
		}

		ret = std::string(cData, uiSize);
	}
	
	GlobalUnlock(hClipboardData);

	CloseClipboard();
	
	return ret;
#endif
	
#ifdef OSX
	ScrapRef scrap;
	Size size;
	
	int err = GetCurrentScrap(&scrap);
	
	if(err)
	{
		Printf(PRINT_HIGH, "GetCurrentScrap error: %d", err);
		return "";
	}
	
	err = GetScrapFlavorSize(scrap, FOUR_CHAR_CODE('TEXT'), &size);
	
	if(err)
	{
		Printf(PRINT_HIGH, "GetScrapFlavorSize error: %d", err);
		return "";
	}
	
	char *data = new char[size+1];
	
	err = GetScrapFlavorData(scrap, FOUR_CHAR_CODE('TEXT'), &size, data);
	data[size] = 0;
	
	if(err)
	{
		Printf(PRINT_HIGH, "GetScrapFlavorData error: %d", err);
		delete[] data;
	}
	
	std::string ret(data);
	
	delete[] data;
	
	return ret;
#endif
	
	return "";
}
Example #23
0
PUBLIC void
get_scrap(int type, int *dstlen, char **dst)
{
  scrap_type format;

  *dstlen = -1;
  format = convert_format(type);

#if defined(X11_SCRAP)
/* * */
  {
    Window owner;
    Atom selection;
    Atom seln_type;
    int seln_format;
    unsigned long nbytes;
    unsigned long overflow;
    char *src;

    owner = XGetSelectionOwner(SDL_Display, XA_PRIMARY);
    if ( (owner == None) || (owner == SDL_Window) )
      {
        owner = DefaultRootWindow(SDL_Display);
        selection = XA_CUT_BUFFER0;
      }
    else
      {
        int selection_response = 0;
        SDL_Event event;

        owner = SDL_Window;
        selection = XInternAtom(SDL_Display, "SDL_SELECTION", False);
        XConvertSelection(SDL_Display, XA_PRIMARY, format,
                                        selection, owner, CurrentTime);
        while ( ! selection_response )
          {
            SDL_WaitEvent(&event);
            if ( event.type == SDL_SYSWMEVENT )
              {
#if SDL_MAJOR_VERSION == 0 && SDL_MINOR_VERSION < 9
                XEvent xevent = event.syswm.msg->xevent;
#else
                XEvent xevent = event.syswm.msg->event.xevent;
#endif
                if ( (xevent.type == SelectionNotify) &&
                     (xevent.xselection.requestor == owner) )
                    selection_response = 1;
              }
            else
              {
                /* FIXME: dropped event? */;
              }
          }
      }
    if ( XGetWindowProperty(SDL_Display, owner, selection, 0, INT_MAX/4,
                            False, format, &seln_type, &seln_format,
                       &nbytes, &overflow, (unsigned char **)&src) == Success )
      {
        if ( seln_type == format )
          {
            char *mem;
            *dstlen = convert_scrap(type, NULL, src, nbytes);
            mem = sdl_ReallocHandle(dst, *dstlen);
            if ( mem == NULL )
              *dstlen = -1;
            else
              convert_scrap(type, mem, src, nbytes);
          }
        XFree(src);
      }
    }

#elif defined(WIN_SCRAP)
/* * */
  if ( IsClipboardFormatAvailable(format) && OpenClipboard(SDL_Window) )
    {
      HANDLE hMem;
      char *src;

      hMem = GetClipboardData(format);
      if ( hMem != NULL )
        {
          char *mem;
          src = (char *)GlobalLock(hMem);
          *dstlen = convert_scrap(type, NULL, src, 0);
          mem = sdl_ReallocHandle(dst, *dstlen);
          if ( mem == NULL )
            *dstlen = -1;
          else
            convert_scrap(type, mem, src, 0);
          GlobalUnlock(hMem);
        }
      CloseClipboard();
    }

#endif /* scrap type */
}
Example #24
0
void *wxGetClipboardData(wxDataFormat dataFormat, long *len)
{
    void *retval = NULL;

    switch ( dataFormat )
    {
#ifndef __WXWINCE__
        case wxDF_BITMAP:
            {
                BITMAP bm;
                HBITMAP hBitmap = (HBITMAP) GetClipboardData(CF_BITMAP);
                if (!hBitmap)
                    break;

                HDC hdcMem = CreateCompatibleDC((HDC) NULL);
                HDC hdcSrc = CreateCompatibleDC((HDC) NULL);

                HBITMAP old = (HBITMAP) ::SelectObject(hdcSrc, hBitmap);
                GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);

                HBITMAP hNewBitmap = CreateBitmapIndirect(&bm);

                if (!hNewBitmap)
                {
                    SelectObject(hdcSrc, old);
                    DeleteDC(hdcMem);
                    DeleteDC(hdcSrc);
                    break;
                }

                HBITMAP old1 = (HBITMAP) SelectObject(hdcMem, hNewBitmap);
                BitBlt(hdcMem, 0, 0, bm.bmWidth, bm.bmHeight,
                       hdcSrc, 0, 0, SRCCOPY);

                // Select new bitmap out of memory DC
                SelectObject(hdcMem, old1);

                // Clean up
                SelectObject(hdcSrc, old);
                DeleteDC(hdcSrc);
                DeleteDC(hdcMem);

                // Create and return a new wxBitmap
                wxBitmap *wxBM = new wxBitmap;
                wxBM->SetHBITMAP((WXHBITMAP) hNewBitmap);
                wxBM->SetWidth(bm.bmWidth);
                wxBM->SetHeight(bm.bmHeight);
                wxBM->SetDepth(bm.bmPlanes);
                retval = wxBM;
                break;
            }
#endif
        case wxDF_METAFILE:
        case CF_SYLK:
        case CF_DIF:
        case CF_TIFF:
        case CF_PALETTE:
        case wxDF_DIB:
            wxLogError(_("Unsupported clipboard format."));
            return NULL;

        case wxDF_OEMTEXT:
            dataFormat = wxDF_TEXT;
            // fall through

        case wxDF_TEXT:
            {
                HANDLE hGlobalMemory = ::GetClipboardData(dataFormat);
                if (!hGlobalMemory)
                    break;

                DWORD hsize = ::GlobalSize(hGlobalMemory);
                if (len)
                    *len = hsize;

                char *s = new char[hsize];
                if (!s)
                    break;

                LPSTR lpGlobalMemory = (LPSTR) GlobalLock(hGlobalMemory);

                memcpy(s, lpGlobalMemory, hsize);

                GlobalUnlock(hGlobalMemory);

                retval = s;
                break;
            }

        default:
            {
                HANDLE hGlobalMemory = ::GetClipboardData(dataFormat);
                if ( !hGlobalMemory )
                    break;

                DWORD size = ::GlobalSize(hGlobalMemory);
                if ( len )
                    *len = size;

                void *buf = malloc(size);
                if ( !buf )
                    break;

                LPSTR lpGlobalMemory = (LPSTR) GlobalLock(hGlobalMemory);

                memcpy(buf, lpGlobalMemory, size);

                GlobalUnlock(hGlobalMemory);

                retval = buf;
                break;
            }
    }

    if ( !retval )
    {
        wxLogSysError(_("Failed to retrieve data from the clipboard."));
    }

    return retval;
}
Example #25
0
void cbLuaBreakHook(lua_State *L, lua_Debug *ar)
{
    // Need some other way to do this in Linux.
#ifdef __PRAXIS_WINDOWS__
    // Force GetAsyncKeyState to be called for both keys so that
    // their respective statuses are up to date.
    // Previously, only Ctrl was kept up to date. Q was checked only if Ctrl held down.
    // Press q, then other stuff, then when Ctrl pressed, a break would be triggered.
    bool bCtrlDown = ::GetAsyncKeyState(VK_LCONTROL) != 0;
    bool bQDown = ::GetAsyncKeyState(0x51) != 0;
    if(bCtrlDown && bQDown) // Ctrl-Q pressed
    {
        // Break detected. Check the time since last break.

        // If its too low, ignore.
        int nTime = ::timeGetTime();
        if(nTime < (g_nLastBreakTime + 200))
            return;

        // If its high enough, then break.
        g_nLastBreakTime = nTime;

        lua_pushstring(L, "User break.");
        lua_error(L);
        return;
    }
#endif

#ifdef __PRAXIS_LINUX__
    // SDL_GetKeyState
    // http://sdl.beuc.net/sdl.wiki/SDL_GetKeyState
    //
    // #include "SDL.h"
    // Uint8 *SDL_GetKeyState(int *numkeys);
    //
    // Example:
    //
    // Uint8 *keystate = SDL_GetKeyState(NULL);
    // if ( keystate[SDLK_RETURN] ) printf("Return Key Pressed.\n");
    // if ( keystate[SDLK_RIGHT] && keystate[SDLK_UP] ) printf("Right and Up Keys Pressed.\n");
    //
    // Note: Use SDL_PumpEvents to update the state array
    //
    // http://sdl.beuc.net/sdl.wiki/SDLKey
    // SDLK_LCTRL
    // SDLK_RCTRL
    // SDLK_q
    //
    // Calling SDL_PumpEvents shouldn't have side effects because SDL isn't being used for OpenGL

    char keys_return[32];

    //glutMainLoopEvent();
    XQueryKeymap(g_pAppDisplay, keys_return);

#if 0
    bool bNonZero = false;
    for (int i = 0; i < 32; i++)
    {
        if(keys_return[i] != 0)
            bNonZero = true;
    }

    if(bNonZero)
    {
        for (int i = 0; i < 32; i++)
        {
            printf("%d ", (unsigned int)keys_return[i]);
        }
        printf("\n");
    }
#endif

    if(keys_return[3] == 1 && keys_return[4] == 32)
    {
        // Break detected. Check the time since last break.

        // If its too low, ignore.
        int nTime = glutGet(GLUT_ELAPSED_TIME);
        if(nTime < (g_nLastBreakTime + 200))
            return;

        // If its high enough, then break.
        g_nLastBreakTime = nTime;

        lua_pushstring(L, "User break.");
        lua_error(L);
        return;
    }
#endif

    return;

#if 0
    HGLOBAL      hGlobal ;
    PTSTR        pGlobal ;

    std::string sText;

    OpenClipboard (g_AppHWND) ;
    if (hGlobal = GetClipboardData (CF_TEXT))
    {
         pGlobal = (PTSTR)GlobalLock (hGlobal) ;
         sText = pGlobal;
         GlobalUnlock(hGlobal);
    }
    CloseClipboard () ;


    if(sText == "praxis:STOP")
    {
        OpenClipboard (g_AppHWND) ;
        EmptyClipboard();
        CloseClipboard () ;

        lua_pushstring(L, "User break.");
        lua_error(L);
    }
#endif
}
Example #26
0
static char *_internal_clippy_paste(int cb)
{
#if defined(MACOSX)
        char *src;
#endif
#if defined(USE_X11)
        Window owner;
        int getme;
#elif defined(WIN32)
        char *src;
        int clen;
#elif defined(__QNXNTO__)
        void *clhandle;
        PhClipHeader *clheader;
        int *cldata;
#endif

        if (has_sys_clip) {
#if defined(USE_X11)
                if (cb == CLIPPY_SELECT) {
                        getme = XA_PRIMARY;
                } else {
                        getme = atom_clip;
                }
                lock_display();
                owner = XGetSelectionOwner(SDL_Display, getme);
                unlock_display();
                if (owner == None || owner == SDL_Window) {
                        /* fall through to default implementation */
                } else {
                        lock_display();
                        XConvertSelection(SDL_Display, getme, XA_STRING, atom_sel, SDL_Window,
                                                        CurrentTime);
                        /* at some point in the near future, we'll get a SelectionNotify
                        see _x11_clip_filter for more details;

                        because of this (otherwise) oddity, we take the selection immediately...
                        */
                        unlock_display();
                        return NULL;
                }
#else
                if (cb == CLIPPY_BUFFER) {
#if defined(WIN32)
                        if (IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(SDL_Window)) {
                                _hmem  = GetClipboardData(CF_TEXT);
                                if (_hmem) {
                                        if (_current_selection != _current_clipboard) {
                                                free(_current_clipboard);
                                        }
                                        _current_clipboard = NULL;
                                        src = (char*)GlobalLock(_hmem);
                                        if (src) {
                                                clen = GlobalSize(_hmem);
                                                if (clen > 0) {
                                                        _current_clipboard = mem_alloc(clen+1);
                                                        memcpy(_current_clipboard, src, clen);
                                                        _current_clipboard[clen] = '\0';
                                                }
                                                GlobalUnlock(_hmem);
                                        }
                                }
                                CloseClipboard();
                                _hmem = NULL;
                        }
#elif defined(__QNXNTO__)
                        if (_current_selection != _current_clipboard) {
                                free(_current_clipboard);
                        }
                        _current_clipboard = NULL;
#if (NTO_VERSION < 620)
                        clhandle = PhClipboardPasteStart(inputgroup);
                        if (clhandle) {
                                clheader = PhClipboardPasteType(clhandle,
                                                                Ph_CLIPBOARD_TYPE_TEXT);
                                if (clheader) {
                                        cldata = clheader->data;
                                        if (clheader->length > 4 && *cldata == Ph_CL_TEXT) {
                                                src = ((char *)clheader->data)+4;
                                                clen = clheader->length - 4;
                                                _current_clipboard = mem_alloc(clen+1);
                                                memcpy(_current_clipboard, src, clen);
                                                _current_clipboard[clen] = '\0';

                                        }
                                        PhClipboardPasteFinish(clhandle);
                                }
                        }
#else
                        /* argh! qnx */
                        clheader = PhClipboardRead(inputgroup, Ph_CLIPBOARD_TYPE_TEXT);
                        if (clheader) {
                                cldata = clheader->data;
                                if (clheader->length > 4 && *cldata == Ph_CL_TEXT) {
                                        src = ((char *)clheader->data)+4;
                                        clen = clheader->length - 4;
                                        _current_clipboard = mem_alloc(clen+1);
                                        memcpy(_current_clipboard, src, clen);
                                        _current_clipboard[clen] = '\0';
                                }
                        }
#endif /* NTO version selector */
                /* okay, we either own the buffer, or it's a selection for folks without */
#endif /* win32/qnx */
                }
#endif /* x11/others */
                /* fall through; the current window owns it */
        }
        if (cb == CLIPPY_SELECT) return _current_selection;
#ifdef MACOSX
        if (cb == CLIPPY_BUFFER) {
                src = str_dup(macosx_clippy_get());
                if (_current_clipboard != _current_selection) {
                        free(_current_clipboard);
                }
                _current_clipboard = src;
                if (!src) return (char *) ""; /* FIXME: de-const-ing is bad */
                return _current_clipboard;
        }
#else
        if (cb == CLIPPY_BUFFER) return _current_clipboard;
#endif
        return NULL;
}
Example #27
0
LRESULT CALLBACK NewMainProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  //Capture
  if (uMsg == WM_CHANGECBCHAIN)
  {
    if (bInitCapture)
    {
      if (hWndNextViewer == (HWND)wParam)
        hWndNextViewer=(HWND)lParam;
      else if (hWndNextViewer && IsWindow(hWndNextViewer))
        SendMessage(hWndNextViewer, uMsg, wParam, lParam);
    }
  }
  else if (uMsg == WM_DRAWCLIPBOARD)
  {
    if (bInitCapture)
    {
      if (hWndCaptureDlg)
      {
        if (GetFocus() != hWndCaptureEdit)
        {
          if (!cfSelAutoCopy || !IsClipboardFormatAvailable(cfSelAutoCopy))
          {
            SendMessage(hWndCaptureEdit, EM_SETSEL, (WPARAM)0x7FFFFFFF, (LPARAM)0x7FFFFFFF);
            SendMessage(hMainWnd, AKD_PASTE, (WPARAM)hWndCaptureEdit, 0);
            SendMessage(hWndCaptureEdit, EM_SETSEL, (WPARAM)0x7FFFFFFF, (LPARAM)0x7FFFFFFF);
            SendMessage(hMainWnd, AKD_REPLACESELW, (WPARAM)hWndCaptureEdit, (LPARAM)wszCaptureSeparator);
          }
        }
      }
      if (hWndNextViewer && IsWindow(hWndNextViewer))
        SendMessage(hWndNextViewer, uMsg, wParam, lParam);
    }
  }

  //PasteSerial
  else if (uMsg == WM_HOTKEY)
  {
    if (bInitPasteSerial)
    {
      char *szSerial=NULL;
      char *pSerial=NULL;
      HWND hWndTargetForeground;
      HWND hWndTargetFocus;
      DWORD dwTargetForeground;
      DWORD dwThreadCurrent;
      WORD wVk;
      int nInsertType=0;

      if (GetHotkeyMod(dwHotkeyDelimSkip) == LOWORD(lParam) && LOBYTE(dwHotkeyDelimSkip) == HIWORD(lParam))
        nInsertType=IT_DELIM_SKIP;
      else if (GetHotkeyMod(dwHotkeyDelimAsTab) == LOWORD(lParam) && LOBYTE(dwHotkeyDelimAsTab) == HIWORD(lParam))
        nInsertType=IT_DELIM_ASTAB;
      else if (GetHotkeyMod(dwHotkeyDelimAsIs) == LOWORD(lParam) && LOBYTE(dwHotkeyDelimAsIs) == HIWORD(lParam))
        nInsertType=IT_DELIM_ASIS;

      if (nInsertType)
      {
        hWndTargetForeground=GetForegroundWindow();
        dwTargetForeground=GetWindowThreadProcessId(hWndTargetForeground, NULL);
        dwThreadCurrent=GetCurrentThreadId();

        if (dwThreadCurrent != dwTargetForeground)
        {
          if (AttachThreadInput(dwThreadCurrent, dwTargetForeground, TRUE))
          {
            WaitForReleaseVkKeys(dwThreadCurrent, dwTargetForeground, INFINITE);

            if (hWndTargetFocus=GetFocus())
            {
              //Get clipboard text
              {
                HGLOBAL hData;
                LPVOID pData;
                int nDataLen;

                if (OpenClipboard(NULL))
                {
                  if (hData=GetClipboardData(CF_TEXT))
                  {
                    if (pData=GlobalLock(hData))
                    {
                      nDataLen=lstrlenA((char *)pData) + 1;

                      if (szSerial=(char *)GlobalAlloc(GPTR, nDataLen))
                      {
                        lstrcpynA(szSerial, (char *)pData, nDataLen);
                      }
                      GlobalUnlock(hData);
                    }
                  }
                  CloseClipboard();
                }
              }

              //Post serial
              if (szSerial)
              {
                pSerial=szSerial;

                while (*pSerial && *pSerial != '\n')
                {
                  if (nInsertType != IT_DELIM_ASIS)
                  {
                    if (*pSerial == '-' || *pSerial == ' ' || *pSerial == '\t')
                    {
                      if (nInsertType == IT_DELIM_ASTAB)
                      {
                        if (GetFocus() == hWndTargetFocus)
                        {
                          if (bEmulatePress)
                          {
                            WaitForReleaseVkKeys(dwThreadCurrent, dwTargetForeground, INFINITE);
                            keybd_event(VK_TAB, 0, KEYEVENTF_EXTENDEDKEY, 0);
                            keybd_event(VK_TAB, 0, KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP, 0);
                            WaitForReleaseVkKeys(dwThreadCurrent, dwTargetForeground, INFINITE);
                          }
                          else SendMessage(hWndTargetFocus, WM_CHAR, '\t', 1);
                        }
                      }
                      while (*++pSerial == '-' || *pSerial == ' ' || *pSerial == '\t');
                      hWndTargetFocus=GetFocus();
                      continue;
                    }
                  }

                  if (bEmulatePress)
                  {
                    wVk=VkKeyScan(*pSerial);

                    WaitForReleaseVkKeys(dwThreadCurrent, dwTargetForeground, INFINITE);
                    if (HIBYTE(wVk) & 1)
                      keybd_event(VK_SHIFT, 0, KEYEVENTF_EXTENDEDKEY, 0);
                    if (HIBYTE(wVk) & 2)
                      keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0);
                    if (HIBYTE(wVk) & 4)
                      keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY, 0);
                    keybd_event(LOBYTE(wVk), 0, 0, 0);
                    keybd_event(LOBYTE(wVk), 0, KEYEVENTF_KEYUP, 0);
                    if (HIBYTE(wVk) & 4)
                      keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP, 0);
                    if (HIBYTE(wVk) & 2)
                      keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP, 0);
                    if (HIBYTE(wVk) & 1)
                      keybd_event(VK_SHIFT, 0, KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP, 0);
                    WaitForReleaseVkKeys(dwThreadCurrent, dwTargetForeground, INFINITE);
                  }
                  else SendMessage(hWndTargetFocus, WM_CHAR, *pSerial, 1);

                  ++pSerial;
                }
                GlobalFree((HGLOBAL)szSerial);
                szSerial=NULL;
              }
            }
            AttachThreadInput(dwThreadCurrent, dwTargetForeground, FALSE);
          }
        }
      }
    }
  }

  //Notifications
  else if (uMsg == AKDN_DOCK_RESIZE)
  {
    if (bInitCapture)
    {
      if (((DOCK *)wParam)->hWnd == dkCaptureDlg->hWnd)
        dwSaveFlags|=OF_CAPTURE_RECT;
    }
  }
  else if (uMsg == AKDN_SIZE_ONSTART)
  {
    if (bInitCapture)
    {
      if (bCaptureDockWaitResize)
      {
        bCaptureDockWaitResize=FALSE;
        ShowWindow(hWndCaptureDlg, SW_SHOW);
        dkCaptureDlg->dwFlags&=~DKF_HIDDEN;
      }
    }
  }
  if (uMsg == AKDN_MAIN_ONSTART_FINISH)
  {
  }
  else if (uMsg == AKDN_MAIN_ONFINISH)
  {
    NewMainProcData->NextProc(hWnd, uMsg, wParam, lParam);

    if (hWndCaptureDlg)
    {
      DestroyDock(hWndCaptureDlg, DKT_ONMAINFINISH);
    }
    if (bInitPasteSerial)
    {
      UninitMain();
      UninitPasteSerial();
    }
    if (bInitSelAutoCopy)
    {
      UninitMain();
      UninitSelAutoCopy();
    }
    return FALSE;
  }

  //Special messages
  {
    LRESULT lResult;

    if (lResult=EditParentMessages(hWnd, uMsg, wParam, lParam))
      return lResult;
  }

  //Call next procedure
  return NewMainProcData->NextProc(hWnd, uMsg, wParam, lParam);
}
Example #28
0
void GameConsole::virtualKeyCallBack(USHORT vKey)
{
	if (!showChat && !showConsole)
	{
		if (GetAsyncKeyState(VK_TAB) & 0x8000)
		{
			return;
		}

		if (vKey == VK_RETURN)
		{
			displayChat(false);
		}

		if (vKey == VK_OEM_3 || vKey == VK_OEM_8) // ` key for US and UK (todo: only use one or the other, since VK_OEM_3 is @ on UK keyboards)
		{
			displayChat(true);
		}

		// TODO: TEMP: remove
		if (vKey == VK_F11)
		{
			Menu::Instance().menuEnabled = !Menu::Instance().menuEnabled;
		}
		return;
	}

	switch (vKey)
	{
	case VK_RETURN:
		if (!currentInput.currentInput.empty())
		{
			selectedQueue->unchangingBacklog.push_back(currentInput.currentInput);
			selectedQueue->pushLineFromKeyboardToGame(currentInput.currentInput);
			selectedQueue->startIndexForScrolling = 0;
		}
		hideConsole();
		break;

	case VK_ESCAPE:
		hideConsole();
		break;

	case VK_BACK:
		if (!currentInput.currentInput.empty())
		{
			currentInput.backspace();
		}
		break;

	case VK_DELETE:
		if (!currentInput.currentInput.empty())
		{
			currentInput.del();
		}
		break;

	case VK_CAPITAL:
		capsLockToggled = !capsLockToggled;
		break;

	case VK_PRIOR: // PAGE UP
		if (selectedQueue->startIndexForScrolling < selectedQueue->numOfLinesBuffer - selectedQueue->numOfLinesToShow)
		{
			selectedQueue->startIndexForScrolling++;
		}
		break;

	case VK_NEXT: // PAGE DOWN
		if (selectedQueue->startIndexForScrolling > 0)
		{
			selectedQueue->startIndexForScrolling--;
		}
		break;

	case VK_UP:
		currentBacklogIndex++;
		if (currentBacklogIndex > (int)selectedQueue->unchangingBacklog.size() - 1)
		{
			currentBacklogIndex--;
		}
		if (currentBacklogIndex >= 0)
		{
			currentInput.currentInput = selectedQueue->unchangingBacklog.at(selectedQueue->unchangingBacklog.size() - currentBacklogIndex - 1);
		}
		break;

	case VK_DOWN:
		currentBacklogIndex--;
		if (currentBacklogIndex < 0)
		{
			currentBacklogIndex = -1;
			currentInput.currentInput = "";
		}
		else
		{
			currentInput.currentInput = selectedQueue->unchangingBacklog.at(selectedQueue->unchangingBacklog.size() - currentBacklogIndex - 1);
		}
		break;

	case VK_LEFT:
		currentInput.left();
		break;

	case VK_RIGHT:
		currentInput.right();
		break;

	case VK_TAB:
		if (showChat)
		{
			if (selectedQueue == &globalChatQueue)
			{
				SwitchToGameChat();
				break;
			}
			else if (selectedQueue == &gameChatQueue)
			{
				SwitchToGlobalChat();
				break;
			}
		}
		
		if (currentInput.currentInput.find_first_of(" ") == std::string::npos && currentInput.currentInput.length() > 0)
		{
			if (tabHitLast)
			{
				if (currentCommandList.size() > 0)
				{
					currentInput.set(currentCommandList.at((++tryCount) % currentCommandList.size()));
				}
			}
			else
			{
				tryCount = 0;
				currentCommandList.clear();
				commandPriorComplete = currentInput.currentInput;

				auto currentLine = currentInput.currentInput;
				std::transform(currentLine.begin(), currentLine.end(), currentLine.begin(), ::tolower);

				for (auto cmd : Modules::CommandMap::Instance().Commands)
				{
					auto commandName = cmd.Name;
					std::transform(commandName.begin(), commandName.end(), commandName.begin(), ::tolower);

					if (commandName.compare(0, currentLine.length(), currentLine) == 0)
					{
						currentCommandList.push_back(commandName);
					}
				}
				consoleQueue.pushLineFromGameToUI(std::to_string(currentCommandList.size()) + " commands found starting with \"" + currentLine + ".\"");
				consoleQueue.pushLineFromGameToUI("Press tab to go through them.");
			}
		}
		break;

	case 'V':
		if (GetAsyncKeyState(VK_LCONTROL) & 0x8000 || GetAsyncKeyState(VK_RCONTROL) & 0x8000) // CTRL+V pasting
		{
			if (OpenClipboard(nullptr))
			{
				HANDLE hData = GetClipboardData(CF_TEXT);
				if (hData)
				{
					char* textPointer = static_cast<char*>(GlobalLock(hData));
					std::string text(textPointer);
					std::string newInputLine = currentInput.currentInput + text;

					for(char c : text) {
						if (currentInput.currentInput.size() <= INPUT_MAX_CHARS)
						{
							currentInput.type(c);
						}
					}

					GlobalUnlock(hData);
				}
				CloseClipboard();
			}
		}
		else
		{
			handleDefaultKeyInput(vKey);
		}
		break;

	default:
		handleDefaultKeyInput(vKey);
		break;
	}

	tabHitLast = vKey == VK_TAB;
}
Example #29
0
static LRESULT vboxClipboardProcessMsg(VBOXCLIPBOARDCONTEXT *pCtx, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    LRESULT rc = 0;

    switch (msg)
    {
        case WM_CHANGECBCHAIN:
        {
            HWND hwndRemoved = (HWND)wParam;
            HWND hwndNext    = (HWND)lParam;

            Log(("VBoxTray: vboxClipboardProcessMsg: WM_CHANGECBCHAIN: hwndRemoved %p, hwndNext %p, hwnd %p\n", hwndRemoved, hwndNext, pCtx->hwnd));

            if (hwndRemoved == pCtx->hwndNextInChain)
            {
                /* The window that was next to our in the chain is being removed.
                 * Relink to the new next window. */
                pCtx->hwndNextInChain = hwndNext;
            }
            else
            {
                if (pCtx->hwndNextInChain)
                {
                    /* Pass the message further. */
                    DWORD_PTR dwResult;
                    rc = SendMessageTimeout(pCtx->hwndNextInChain, WM_CHANGECBCHAIN, wParam, lParam, 0, CBCHAIN_TIMEOUT, &dwResult);
                    if (!rc)
                        rc = (LRESULT) dwResult;
                }
            }
        } break;

        case WM_DRAWCLIPBOARD:
        {
            Log(("VBoxTray: vboxClipboardProcessMsg: WM_DRAWCLIPBOARD, hwnd %p\n", pCtx->hwnd));

            if (GetClipboardOwner () != hwnd)
            {
                /* Clipboard was updated by another application. */
                /* WM_DRAWCLIPBOARD always expects a return code of 0, so don't change "rc" here. */
                int vboxrc = vboxClipboardChanged(pCtx);
                if (RT_FAILURE(vboxrc))
                    Log(("VBoxTray: vboxClipboardProcessMsg: vboxClipboardChanged failed, rc = %Rrc\n", vboxrc));
            }

            /* Pass the message to next windows in the clipboard chain. */
            SendMessageTimeout(pCtx->hwndNextInChain, msg, wParam, lParam, 0, CBCHAIN_TIMEOUT, NULL);
        } break;

        case WM_TIMER:
        {
            HWND hViewer = GetClipboardViewer();

            /* Re-register ourselves in the clipboard chain if our last ping
             * timed out or there seems to be no valid chain. */
            if (!hViewer || pCtx->fCBChainPingInProcess)
            {
                removeFromCBChain(pCtx);
                addToCBChain(pCtx);
            }
            /* Start a new ping by passing a dummy WM_CHANGECBCHAIN to be
             * processed by ourselves to the chain. */
            pCtx->fCBChainPingInProcess = TRUE;
            hViewer = GetClipboardViewer();
            if (hViewer)
                SendMessageCallback(hViewer, WM_CHANGECBCHAIN, (WPARAM)pCtx->hwndNextInChain, (LPARAM)pCtx->hwndNextInChain, CBChainPingProc, (ULONG_PTR) pCtx);
        } break;

        case WM_CLOSE:
        {
            /* Do nothing. Ignore the message. */
        } break;

        case WM_RENDERFORMAT:
        {
            /* Insert the requested clipboard format data into the clipboard. */
            uint32_t u32Format = 0;
            UINT format = (UINT)wParam;

            Log(("VBoxTray: vboxClipboardProcessMsg: WM_RENDERFORMAT, format = %x\n", format));
            switch (format)
            {
                case CF_UNICODETEXT:
                    u32Format |= VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT;
                    break;

                case CF_DIB:
                    u32Format |= VBOX_SHARED_CLIPBOARD_FMT_BITMAP;
                    break;

                default:
                    if (format >= 0xC000)
                    {
                        TCHAR szFormatName[256];

                        int cActual = GetClipboardFormatName(format, szFormatName, sizeof(szFormatName)/sizeof (TCHAR));
                        if (cActual)
                        {
                            if (strcmp (szFormatName, "HTML Format") == 0)
                            {
                                u32Format |= VBOX_SHARED_CLIPBOARD_FMT_HTML;
                            }
                        }
                    }
                    break;
            }

            if (u32Format == 0)
            {
                /* Unsupported clipboard format is requested. */
                Log(("VBoxTray: vboxClipboardProcessMsg: Unsupported clipboard format requested: %ld\n", u32Format));
                EmptyClipboard();
            }
            else
            {
                const uint32_t cbPrealloc = 4096; /* @todo r=andy Make it dynamic for supporting larger text buffers! */
                uint32_t cb = 0;

                /* Preallocate a buffer, most of small text transfers will fit into it. */
                HANDLE hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, cbPrealloc);
                Log(("VBoxTray: vboxClipboardProcessMsg: Preallocated handle hMem = %p\n", hMem));

                if (hMem)
                {
                    void *pMem = GlobalLock(hMem);
                    Log(("VBoxTray: vboxClipboardProcessMsg: Locked pMem = %p, GlobalSize = %ld\n", pMem, GlobalSize(hMem)));

                    if (pMem)
                    {
                        /* Read the host data to the preallocated buffer. */
                        int vboxrc = VbglR3ClipboardReadData(pCtx->u32ClientID, u32Format, pMem, cbPrealloc, &cb);
                        Log(("VBoxTray: vboxClipboardProcessMsg: VbglR3ClipboardReadData returned with rc = %Rrc\n",  vboxrc));

                        if (RT_SUCCESS(vboxrc))
                        {
                            if (cb == 0)
                            {
                                /* 0 bytes returned means the clipboard is empty.
                                 * Deallocate the memory and set hMem to NULL to get to
                                 * the clipboard empty code path. */
                                GlobalUnlock(hMem);
                                GlobalFree(hMem);
                                hMem = NULL;
                            }
                            else if (cb > cbPrealloc)
                            {
                                GlobalUnlock(hMem);

                                /* The preallocated buffer is too small, adjust the size. */
                                hMem = GlobalReAlloc(hMem, cb, 0);
                                Log(("VBoxTray: vboxClipboardProcessMsg: Reallocated hMem = %p\n", hMem));

                                if (hMem)
                                {
                                    pMem = GlobalLock(hMem);
                                    Log(("VBoxTray: vboxClipboardProcessMsg: Locked pMem = %p, GlobalSize = %ld\n", pMem, GlobalSize(hMem)));

                                    if (pMem)
                                    {
                                        /* Read the host data to the preallocated buffer. */
                                        uint32_t cbNew = 0;
                                        vboxrc = VbglR3ClipboardReadData(pCtx->u32ClientID, u32Format, pMem, cb, &cbNew);
                                        Log(("VBoxTray: VbglR3ClipboardReadData returned with rc = %Rrc, cb = %d, cbNew = %d\n", vboxrc, cb, cbNew));

                                        if (RT_SUCCESS (vboxrc) && cbNew <= cb)
                                        {
                                            cb = cbNew;
                                        }
                                        else
                                        {
                                            GlobalUnlock(hMem);
                                            GlobalFree(hMem);
                                            hMem = NULL;
                                        }
                                    }
                                    else
                                    {
                                        GlobalFree(hMem);
                                        hMem = NULL;
                                    }
                                }
                            }

                            if (hMem)
                            {
                                /* pMem is the address of the data. cb is the size of returned data. */
                                /* Verify the size of returned text, the memory block for clipboard
                                 * must have the exact string size.
                                 */
                                if (u32Format == VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                                {
                                    size_t cbActual = 0;
                                    HRESULT hrc = StringCbLengthW((LPWSTR)pMem, cb, &cbActual);
                                    if (FAILED (hrc))
                                    {
                                        /* Discard invalid data. */
                                        GlobalUnlock(hMem);
                                        GlobalFree(hMem);
                                        hMem = NULL;
                                    }
                                    else
                                    {
                                        /* cbActual is the number of bytes, excluding those used
                                         * for the terminating null character.
                                         */
                                        cb = (uint32_t)(cbActual + 2);
                                    }
                                }
                            }

                            if (hMem)
                            {
                                GlobalUnlock(hMem);

                                hMem = GlobalReAlloc(hMem, cb, 0);
                                Log(("VBoxTray: vboxClipboardProcessMsg: Reallocated hMem = %p\n", hMem));

                                if (hMem)
                                {
                                    /* 'hMem' contains the host clipboard data.
                                     * size is 'cb' and format is 'format'. */
                                    HANDLE hClip = SetClipboardData(format, hMem);
                                    Log(("VBoxTray: vboxClipboardProcessMsg: WM_RENDERFORMAT hClip = %p\n", hClip));

                                    if (hClip)
                                    {
                                        /* The hMem ownership has gone to the system. Finish the processing. */
                                        break;
                                    }

                                    /* Cleanup follows. */
                                }
                            }
                        }
                        if (hMem)
                            GlobalUnlock(hMem);
                    }
                    if (hMem)
                        GlobalFree(hMem);
                }

                /* Something went wrong. */
                EmptyClipboard();
            }
        } break;

        case WM_RENDERALLFORMATS:
        {
            /* Do nothing. The clipboard formats will be unavailable now, because the
             * windows is to be destroyed and therefore the guest side becomes inactive.
             */
            if (OpenClipboard(hwnd))
            {
                EmptyClipboard();
                CloseClipboard();
            }
        } break;

        case WM_USER:
        {
            /* Announce available formats. Do not insert data, they will be inserted in WM_RENDER*. */
            uint32_t u32Formats = (uint32_t)lParam;

            if (FALSE == OpenClipboard(hwnd))
            {
                Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER: Failed to open clipboard! Last error = %ld\n", GetLastError()));
            }
            else
            {
                EmptyClipboard();

                HANDLE hClip = NULL;

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                {
                    Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER: VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT\n"));
                    hClip = SetClipboardData(CF_UNICODETEXT, NULL);
                }

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
                {
                    Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER: VBOX_SHARED_CLIPBOARD_FMT_BITMAP\n"));
                    hClip = SetClipboardData(CF_DIB, NULL);
                }

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_HTML)
                {
                    UINT format = RegisterClipboardFormat ("HTML Format");
                    Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER: VBOX_SHARED_CLIPBOARD_FMT_HTML 0x%04X\n", format));
                    if (format != 0)
                    {
                        hClip = SetClipboardData(format, NULL);
                    }
                }

                CloseClipboard();
                Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER: hClip = %p, err = %ld\n", hClip, GetLastError ()));
            }
        } break;

        case WM_USER + 1:
        {
            /* Send data in the specified format to the host. */
            uint32_t u32Formats = (uint32_t)lParam;
            HANDLE hClip = NULL;

            if (FALSE == OpenClipboard(hwnd))
            {
                Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER: Failed to open clipboard! Last error = %ld\n", GetLastError()));
            }
            else
            {
                int vboxrc;
                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
                {
                    hClip = GetClipboardData(CF_DIB);

                    if (hClip != NULL)
                    {
                        LPVOID lp = GlobalLock(hClip);
                        if (lp != NULL)
                        {
                            Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER + 1: CF_DIB\n"));
                            vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_BITMAP,
                                                              lp, GlobalSize(hClip));
                            GlobalUnlock(hClip);
                        }
                        else
                        {
                            hClip = NULL;
                        }
                    }
                }
                else if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                {
                    hClip = GetClipboardData(CF_UNICODETEXT);

                    if (hClip != NULL)
                    {
                        LPWSTR uniString = (LPWSTR)GlobalLock(hClip);

                        if (uniString != NULL)
                        {
                            Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER + 1: CF_UNICODETEXT\n"));
                            vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT,
                                                              uniString, (lstrlenW(uniString) + 1) * 2);
                            GlobalUnlock(hClip);
                        }
                        else
                        {
                            hClip = NULL;
                        }
                    }
                }
                else if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_HTML)
                {
                    UINT format = RegisterClipboardFormat ("HTML Format");
                    if (format != 0)
                    {
                        hClip = GetClipboardData(format);
                        if (hClip != NULL)
                        {
                            LPVOID lp = GlobalLock(hClip);

                            if (lp != NULL)
                            {
                                Log(("VBoxTray: vboxClipboardProcessMsg: WM_USER + 1: CF_HTML\n"));
                                vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_HTML,
                                                                  lp, GlobalSize(hClip));
                                GlobalUnlock(hClip);
                            }
                            else
                            {
                                hClip = NULL;
                            }
                        }
                    }
                }

                CloseClipboard();
            }

            if (hClip == NULL)
            {
                /* Requested clipboard format is not available, send empty data. */
                VbglR3ClipboardWriteData(pCtx->u32ClientID, 0, NULL, 0);
            }
        } break;

        default:
        {
            rc = DefWindowProc(hwnd, msg, wParam, lParam);
        }
    }

    Log(("VBoxTray: vboxClipboardProcessMsg returned with rc = %ld\n", rc));
    return rc;
}
Example #30
0
void CPredView::OnEditPaste()
{
	// TODO: Add your command handler code here
	CFCCDoc* pDoc=(CFCCDoc*)GetDocument();
	UINT uFormat=RegisterClipboardFormat("FCC");
	if(!IsClipboardFormatAvailable(uFormat))
		return;
	if(!OpenClipboard())
	{
		pDoc->strMessage="Fail to open clipboard!";
		pDoc->MessageCenter(IDS_MESSAGE_CUSTOM);
		return;
	}
	int count;
	int nFpLen;
	int i,strlenCmpName;
	int memoffset=0;
	int id=0;
	
	CCompound* pCompound;
	HGLOBAL hglbPaste;
	hglbPaste=GetClipboardData(uFormat);
	char* pData=(char*)GlobalLock(hglbPaste);
	memcpy(&nFpLen,pData+memoffset,sizeof(int));
	memoffset+=sizeof(int);
	memcpy(&count,pData+memoffset,sizeof(int));
	memoffset+=sizeof(int);
	if(nFpLen!=pDoc->nFpLen)
	{
		pDoc->MessageCenter(IDS_MESSAGE_INCONSISTENTLENGTH);
		return;
	}
	//Add Error Processing Function if The pasted fingerprint length and current project do not match
	POSITION pos=pDoc->list_CompoundTest.GetHeadPosition();
	while(pos)
	{
		pCompound=(CCompound*)pDoc->list_CompoundTest.GetNext(pos);
		if(pCompound->id>id)
			id=pCompound->id;
	}
	for(i=0;i<count;i++)
	{
		pCompound=new CCompound;
		memcpy(&strlenCmpName,pData+memoffset,sizeof(int));
		memoffset+=sizeof(int);
		char* pTmpStr=(char*)malloc(sizeof(char)*(strlenCmpName+1));
		memcpy(pTmpStr,pData+memoffset,sizeof(char)*strlenCmpName);
		memoffset+=sizeof(char)*strlenCmpName;
		pTmpStr[strlenCmpName]=NULL;
		pCompound->strCompoundName=pTmpStr;
		pCompound->id=++id;
		pCompound->pFingerprint=(bool*)malloc(sizeof(bool)*pDoc->nFpLen);
		memcpy(pCompound->pFingerprint,pData+memoffset,sizeof(char)*pDoc->nFpLen);
		memoffset+=sizeof(bool)*pDoc->nFpLen;
		delete pTmpStr;
		pDoc->list_CompoundTest.AddTail(pCompound);
	}
	GlobalUnlock(hglbPaste);
	CloseClipboard();
	if(count>0)
	{
		OnUpdate(NULL,0,0);
		Invalidate();
		pDoc->SetModifiedFlag(true);
		if(count>1)
			pDoc->strMessage.Format("%d items are pasted into testing data set.",count);
		else
			pDoc->strMessage.Format("%d item is pasted into testing data set.",count);
		pDoc->MessageCenter(IDS_MESSAGE_PASTE);
	}

}