Example #1
0
void Clipboard::CopyToClipboard(HWND h)
{
	if ( !OpenClipboard(h) )
	{
		MessageBox(NULL,  "Cannot open the Clipboard", "Error", MB_OK);
		return;
	}
	// Remove the current Clipboard contents
	if( !EmptyClipboard() )
	{
		MessageBox(NULL, "Cannot empty the Clipboard", "Error", MB_OK);
		return;
	}
	// ...
	// Get the currently selected data

/*************
	INCCRunTimeEnvironment::tEnvInfo info;
	GetEnvironmentInfoList(info);
	int tlen = 0;
	int i;


	const int ic = eMAXPATHCFGNAMES/2 + eMAXAPPINFONAMES;

	PTCHAR *foo = new PTCHAR[ic];
	for (i = 0; i < ic; i++)
	{
		foo[i] = new TCHAR[512];
		foo[i][0] = 0;
	}

	for (i = 0; i < (eMAXPATHCFGNAMES/2); i++)
	{
		sprintf(foo[i],"%s\t\t%s\t\t%s\t\t%s\r\n",
			info.pIniFile->m_Entry[i].name, 
			info.pIniFile->m_Entry[i].iniValue,  
			info.pIniFile->m_Entry[i].defIniValue,  
			info.pIniFile->m_Entry[i].szDesc);
		tlen += strlen(foo[i]);
	}
	for (i = 0; i < (eMAXAPPINFONAMES); i++)
	{
		sprintf(foo[i + (eMAXPATHCFGNAMES/2)],"%s\t\t%s\t\t%s\t\t%s\r\n",
			info.info[i].name, 
			info.info[i].iniValue,  
			info.info[i].defIniValue,  
			info.info[i].szDesc);    
		tlen += strlen(foo[i]);
	}



	// Allocate a global memory object for the text. 
	LPTSTR  lptstrCopy; 
	HGLOBAL hglbCopy; 
	hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (tlen + 1) * sizeof(TCHAR)); 
	if (hglbCopy == NULL) 
	{ 
		goto cleanup;
	} 

	// Lock the handle and copy the text to the buffer. 
	lptstrCopy = (LPSTR)GlobalLock(hglbCopy);
	lptstrCopy[0] = (TCHAR) 0;    // null character 
	for (i = 0; i < ic; i++)
	{
		LPSTR b = foo[i];
		size_t l = strlen(b);
		strncat(lptstrCopy, b, l);
	}
	lptstrCopy[tlen] = (TCHAR) 0;    // null character 
	GlobalUnlock(hglbCopy); 

	// Place the handle on the clipboard. 

	// For the appropriate data formats...
	if ( ::SetClipboardData( CF_TEXT, hglbCopy ) == NULL )
	{
		MessageBox(NULL, "Unable to set Clipboard data", "Error", MB_OK);
		goto cleanup;
	}

cleanup:
	CloseClipboard();

	for (i = 0; i < ic; i++)
	{
		delete [] foo[i];
	}
	delete [] foo;
		*/
}
Example #2
0
static LRESULT CALLBACK cliprdr_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	static wfClipboard* clipboard = NULL;

	switch (Msg)
	{
		case WM_CREATE:
			DEBUG_CLIPRDR("info: WM_CREATE");
			clipboard = (wfClipboard*)((CREATESTRUCT*) lParam)->lpCreateParams;
			if (!AddClipboardFormatListener(hWnd)) {
				DEBUG_CLIPRDR("error: AddClipboardFormatListener failed with %#x.", GetLastError());
			}
			clipboard->hwnd = hWnd;
			break;

		case WM_CLOSE:
			DEBUG_CLIPRDR("info: WM_CLOSE");
			RemoveClipboardFormatListener(hWnd);
			break;

		case WM_CLIPBOARDUPDATE:
			DEBUG_CLIPRDR("info: WM_CLIPBOARDUPDATE");
			if (clipboard->sync)
			{
				if ((GetClipboardOwner() != clipboard->hwnd) &&
					(S_FALSE == OleIsCurrentClipboard(clipboard->data_obj)))
				{
						if (clipboard->hmem)
						{
							GlobalFree(clipboard->hmem);
							clipboard->hmem = NULL;
						}

						cliprdr_send_format_list(clipboard);
				}
			}
			break;

		case WM_RENDERALLFORMATS:
			DEBUG_CLIPRDR("info: WM_RENDERALLFORMATS");
			/* discard all contexts in clipboard */
			if (!OpenClipboard(clipboard->hwnd))
			{
				DEBUG_CLIPRDR("OpenClipboard failed with 0x%x", GetLastError());
				break;
			}
			EmptyClipboard();
			CloseClipboard();
			break;

		case WM_RENDERFORMAT:
			DEBUG_CLIPRDR("info: WM_RENDERFORMAT");
			if (cliprdr_send_data_request(clipboard, (UINT32) wParam) != 0)
			{
				DEBUG_CLIPRDR("error: cliprdr_send_data_request failed.");
				break;
			}

			if (!SetClipboardData((UINT) wParam, clipboard->hmem))
			{
				DEBUG_CLIPRDR("SetClipboardData failed with 0x%x", GetLastError());

				if (clipboard->hmem)
				{
					GlobalFree(clipboard->hmem);
					clipboard->hmem = NULL;
				}
			}
			/* Note: GlobalFree() is not needed when success */
			break;

		case WM_CLIPRDR_MESSAGE:
			DEBUG_CLIPRDR("info: WM_CLIPRDR_MESSAGE");
			switch (wParam)
			{
				case OLE_SETCLIPBOARD:
					DEBUG_CLIPRDR("info: OLE_SETCLIPBOARD");
					if (wf_create_file_obj(clipboard, &clipboard->data_obj))
					{
						if (OleSetClipboard(clipboard->data_obj) != S_OK)
						{
							wf_destroy_file_obj(clipboard->data_obj);
							clipboard->data_obj = NULL;
						}
					}
					break;

				default:
					break;
			}
			break;

		case WM_DESTROYCLIPBOARD:
		case WM_ASKCBFORMATNAME:
		case WM_HSCROLLCLIPBOARD:
		case WM_PAINTCLIPBOARD:
		case WM_SIZECLIPBOARD:
		case WM_VSCROLLCLIPBOARD:
		default:
			return DefWindowProc(hWnd, Msg, wParam, lParam);
	}

	return 0;
}
Example #3
0
static int cliprdr_send_format_list(wfClipboard* clipboard)
{
	int count;
	int length;
	UINT32 index;
	UINT32 numFormats;
	UINT32 formatId = 0;
	char formatName[1024];
	CLIPRDR_FORMAT* format;
	CLIPRDR_FORMAT* formats;
	CLIPRDR_FORMAT_LIST formatList;

	ZeroMemory(&formatList, sizeof(CLIPRDR_FORMAT_LIST));

	if (!OpenClipboard(clipboard->hwnd))
		return -1;

	count = CountClipboardFormats();

	numFormats = (UINT32) count;
	formats = (CLIPRDR_FORMAT*) calloc(numFormats, sizeof(CLIPRDR_FORMAT));

	index = 0;

	while (formatId = EnumClipboardFormats(formatId))
	{
		format = &formats[index++];

		format->formatId = formatId;

		length = 0;
		format->formatName = NULL;

		if (formatId >= CF_MAX)
		{
			length = GetClipboardFormatNameA(formatId, formatName, sizeof(formatName) - 1);
		}

		if (length > 0)
		{
			format->formatName = _strdup(formatName);
		}
	}

	CloseClipboard();

	formatList.msgFlags = 0;
	formatList.numFormats = numFormats;
	formatList.formats = formats;

	clipboard->context->ClientFormatList(clipboard->context, &formatList);

	for (index = 0; index < numFormats; index++)
	{
		format = &formats[index];
		free(format->formatName);
	}

	free(formats);

	return 1;
}
//------------------------------------------------------------------------------
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms649016%28v=vs.85%29.aspx
DWORD WINAPI Scan_clipboard(LPVOID lParam)
{
  //check if local or not :)
  if (!LOCAL_SCAN)
  {
    h_thread_test[(unsigned int)lParam] = 0;
    check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan
    return 0;
  }

  //db
  sqlite3 *db = (sqlite3 *)db_scan;
  if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"BEGIN TRANSACTION;", NULL, NULL, NULL);

  //lecture du contenu du presse papier et extraction
  if (OpenClipboard(0))
  {
    char description[MAX_LINE_SIZE], format[DEFAULT_TMP_SIZE],
    data[MAX_LINE_SIZE],user[NB_USERNAME_SIZE+1]="";
    unsigned int session_id = current_session_id;
    HGLOBAL hMem;

    //user
    DWORD s=NB_USERNAME_SIZE;
    GetUserName(user,&s);

    int nb_items = CountClipboardFormats();
    if (nb_items > 0)
    {
      unsigned int uFormat = EnumClipboardFormats(0);
      #ifdef CMD_LINE_ONLY_NO_DB
      printf("\"Clipboard\";\"format\";\"code\";\"description\";\"user\";\"session_id\";\"data\";\r\n");
      #endif // CMD_LINE_ONLY_NO_DB
      while (uFormat && start_scan && GetLastError() == ERROR_SUCCESS && --nb_items>0)
      {
        //check if ok
        if (IsClipboardFormatAvailable(uFormat) == FALSE)
        {
          uFormat = EnumClipboardFormats(uFormat);
          continue;
        }

        description[0] = 0;
        data[0]= 0;
        if (GetClipboardFormatName(uFormat, description, MAX_LINE_SIZE) != 0)
        {
          hMem = GetClipboardData(uFormat);
          if (hMem != NULL)
          {
            switch(uFormat)
            {
              case CF_TEXT:
                //format
                strncpy(format,"CF_TEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_BITMAP:
                //format
                strncpy(format,"CF_BITMAP",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Bitmap Picture",DEFAULT_TMP_SIZE);
                //do in bitmap to hexa
                SaveBitmapToHexaStr((HBITMAP)hMem , data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_METAFILEPICT:
                //format
                strncpy(format,"CF_METAFILEPICT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Meta-File Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
                GlobalUnlock(hMem);
              break;
              case CF_SYLK:
                //format
                strncpy(format,"CF_SYLK",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Microsoft Symbolic Link (SYLK) data",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%s",(char*)GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_OEMTEXT:
                //format
                strncpy(format,"CF_OEMTEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text (OEM)",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_DIB:
                //format
                strncpy(format,"CF_DIB",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"DIB Bitmap Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_DIF:
                //format
                strncpy(format,"CF_DIF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Software Arts' Data Interchange information",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_TIFF:
                //format
                strncpy(format,"CF_TIFF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Tagged Image File Format (TIFF) Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_PALETTE:
                //format
                strncpy(format,"CF_PALETTE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Colour Palette",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_PENDATA:
                //format
                strncpy(format,"CF_PENDATA",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Pen Data",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_UNICODETEXT:
                //format
                strncpy(format,"CF_UNICODETEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text Unicode",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%S",GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);h_thread_test[(unsigned int)lParam] = 0;
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_RIFF:
                //format
                strncpy(format,"CF_RIFF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"RIFF Audio data",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_WAVE:
                //format
                strncpy(format,"CF_WAVE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Wave File",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_ENHMETAFILE:
                //format
                strncpy(format,"CF_ENHMETAFILE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Enhanced Meta-File Picture",DEFAULT_TMP_SIZE);
                //datas
                DWORD dwSize = GetEnhMetaFileBits((HENHMETAFILE)hMem, 0, NULL);
                if (dwSize > 0)
                {
                  LPBYTE buffer = (LPBYTE)malloc(dwSize);
                  if (buffer != NULL)
                  {
                    if (GetEnhMetaFileBits((HENHMETAFILE)hMem, dwSize, buffer)!=0)
                    {
                      DatatoHexa(buffer, dwSize, data, MAX_LINE_SIZE);
                    }
                    free(buffer);
                  }
                }
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_HDROP:
              {
                //format
                strncpy(format,"CF_HDROP",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"File List",DEFAULT_TMP_SIZE);

                HDROP H_DropInfo = (HDROP)hMem;
                char tmp[MAX_PATH];
                DWORD i,nb_path = DragQueryFile(H_DropInfo, 0xFFFFFFFF, tmp, MAX_PATH);
                long int s2 =MAX_LINE_SIZE;
                for (i=0;i<nb_path;i++)
                {
                  //traitement des données ^^
                  DragQueryFile(H_DropInfo, i, tmp, MAX_PATH);

                  //add
                  if (s2>0)
                  {
                    snprintf(data+strlen(data),s,"%s\r\n",tmp);
                    //strncpy(data+strlen(data),tmp,s);
                    s2-=strlen(data);
                  }
                }
                convertStringToSQL(data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              }
              break;
              case CF_LOCALE:
                //format
                strncpy(format,"CF_LOCALE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text Locale Identifier",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"0x%X",(unsigned int)GlobalLock(hMem));
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 17: //CF_DIBV5
                //format
                strncpy(format,"CF_DIBV5",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), sizeof(BITMAPV5HEADER), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49155:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"OwnerLink",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49156:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Native Bitmap Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49158:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"FileName",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49159:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"FileNameW",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%S",GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49298:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Rich Text Format",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%s",(char*)GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              default:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
            }
          }
        }
        uFormat = EnumClipboardFormats(uFormat);
      }
    }
    CloseClipboard();
  }
  if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"END TRANSACTION;", NULL, NULL, NULL);

  check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan
  h_thread_test[(unsigned int)lParam] = 0;
  return 0;
}
Example #5
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 #6
0
BOOL ClipboardCopy(void)
{	HGLOBAL	  hMem;
	char huge *pMem;
	LONG	  lSize;
	BOOL	  WideCharConvert = FALSE;
	UINT	  Codepage = 0;

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

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

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

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

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

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

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

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

	/*finally, publish...*/
	SetClipboardData(WideCharConvert ? CF_UNICODETEXT
									 : CharSet == CS_OEM ? CF_OEMTEXT
														 : CF_TEXT, hMem);
	CloseClipboard();
	CheckClipboard();
	return (TRUE);
}
Example #7
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 #8
0
bool EventDlg::CopyToClipboard(bool bAll, bool bHeaders)
{
	const PTCHAR  _cediteol = "\r\n";
	if ( !OpenClipboard() )
	{
		AfxMessageBox( "Cannot open the Clipboard" );
		return true;
	}
	// Remove the current Clipboard contents
	if( !EmptyClipboard() )
	{
		AfxMessageBox( "Cannot empty the Clipboard" );
		return true;
	}
	// Get the currently selected data

	int nItem, j, tlen, headeroffset;
	const int ic = m_List.GetItemCount();
	CStringArray a;
	a.SetSize(ic);
	tlen = 0;
	headeroffset = 0;
	if (bHeaders)
	{
		CString s;
		for (j = efhFacility;  j < efhHeaderCount; j++)
		{
			UINT icol = j;  // direct mapping from header id to header string
			s.Append(CFDMSApp::GetFileHeader(CSVFileHeaderIDs(icol)));
			s.AppendChar('\t');
		}
		s.Append(_cediteol);
		a.SetAtGrow(0, s);
		tlen += s.GetLength();
		headeroffset = 1;
	}

	// now for the rows
	for (nItem = 0; nItem < ic; nItem++)
	{
		if (!bAll && !m_List.GetItemState(nItem, LVIS_SELECTED))
			continue;

		CString s = m_List.GetItemText(nItem,0);
		for (j = efhFacility; j < efhHeaderCount; j++)
		{
			if (j == efhDischMonth || j == efhDischYear)  // blend of three columns into one
				continue;
			if (j == efhMeasMonth || j == efhMeasYear)  // blend
				continue;
			UINT icol = ImpEditCol::m_fileheadermap[j];
			if (j == efhDischDay)  //  build combined disch date
			{
				COleDateTime dt = m_List.GetDateTime(nItem, icol);
				s.Append(dt.Format("%d\t%m\t%Y"));
			}
			else
			if (j == efhMeasDay)  // build combined meas date
			{
				COleDateTime dt = m_List.GetDateTime(nItem, icol);
				s.Append(dt.Format("%d\t%m\t%Y"));				
			}
			else
			if (j == efhStatus)  // get status from the related globals
			{
				s.Append("0");  // the status of all entries in an import dialog is always unmeasured
			}
			else
			if (j == efhMeasType)  // convert string to number from the item text
			{
				CString cs;
				cs.Format("%d", tImageToMeasurementType(m_List.GetItemText(nItem,icol)));
				s.Append(cs);
			}
			else
				s.Append(m_List.GetItemText(nItem,icol));
			s.AppendChar('\t');
		}
		s.Append(_cediteol);
		a.SetAtGrow(nItem + headeroffset, s);
		tlen += s.GetLength();
	}

    // Allocate a global memory object for the text. 
	LPTSTR  lptstrCopy; 
	HGLOBAL hglbCopy; 
    hglbCopy = GlobalAlloc(GMEM_MOVEABLE, 
        (tlen + 1) * sizeof(TCHAR)); 
    if (hglbCopy == NULL) 
    { 
        CloseClipboard(); 
        return true; 
    } 

    // Lock the handle and copy the text to the buffer. 
    lptstrCopy = (LPSTR)GlobalLock(hglbCopy);
    lptstrCopy[0] = (TCHAR) 0;    // null character 
	for (nItem = 0; nItem < a.GetCount(); nItem++)
	{
		LPSTR b = a[nItem].GetBuffer();
		size_t l = a[nItem].GetLength() *  sizeof(TCHAR);
		strncat(lptstrCopy, b, l);
	}
    lptstrCopy[tlen] = (TCHAR) 0;    // null character 
    GlobalUnlock(hglbCopy); 

    // Place the handle on the clipboard. 

	// For the appropriate data formats...
	if ( SetClipboardData( CF_TEXT, hglbCopy ) == NULL )
	{
		AfxMessageBox( "Unable to set Clipboard data" );
		CloseClipboard();
		return true;
	}
	CloseClipboard();
	return true;
}
Example #9
0
void
CDynamoRIOView::OnEditCopystats()
{
    if (m_ProcessList.GetCurSel() == 0) {
        MessageBox(_T("No instance selected"), _T("Error"), MB_OK | MYMBFLAGS);
        return;
    }
    if (!OpenClipboard()) {
        MessageBox(_T("Error opening clipboard"), _T("Error"), MB_OK | MYMBFLAGS);
        return;
    }
    EmptyClipboard();

#define CLIPBOARD_BUFSZ USHRT_MAX
    TCHAR buf[CLIPBOARD_BUFSZ];
    TCHAR *pos = buf;

    if (m_selected_pid > 0) {
        if (m_stats != NULL) {
            pos += _stprintf(pos, _T("Process id                  = %d\r\n"),
                             m_stats->process_id);
            pos += _stprintf(
                pos, _T("Process name                = %") ASCII_PRINTF _T("\r\n"),
                m_stats->process_name);
            pos += _stprintf(pos, _T("Status                      = %s\r\n"),
                             m_Exited.GetBuffer(0));
#ifndef DRSTATS_DEMO
            pos += _stprintf(pos, _T("Log mask                    = %s\r\n"),
                             m_LogMask.GetBuffer(0));
            pos += _stprintf(pos, _T("Log level                   = %s\r\n"),
                             m_LogLevel.GetBuffer(0));
            pos += _stprintf(pos, _T("Log file                    = %s\r\n"),
                             m_LogDir.GetBuffer(0));
#endif
            pos += _stprintf(pos, _T("\r\nSTATS\r\n"));
            uint i;
            for (i = 0; i < m_stats->num_stats; i++) {
                if (pos >= &buf[STATS_BUFSZ - STAT_NAME_MAX_LEN * 2])
                    break;
                // FIXME: Filter here too
                pos += PrintStat(pos, i, TRUE /*filter*/);
                assert(pos < &buf[STATS_BUFSZ - 1]);
            }
        } else {
            CString pname;
            m_ProcessList.GetLBText(m_ProcessList.GetCurSel(), pname);
            _stprintf(pos, _T("%s"), pname.GetString());
            pos += _tcslen(pos);
        }
    }
    if (m_clientStats != NULL) {
        pos += PrintClientStats(pos, &buf[STATS_BUFSZ - 1]);
    }

    size_t len = _tcslen(buf);

    // Allocate a global memory object for the text.
    HGLOBAL hglbCopy = GlobalAlloc(GMEM_DDESHARE, (len + 1) * sizeof(TCHAR));
    if (hglbCopy == NULL) {
        CloseClipboard();
        return;
    }

    // Lock the handle and copy the text to the buffer.
    LPTSTR lptstrCopy = (LPTSTR)GlobalLock(hglbCopy);
    memcpy(lptstrCopy, buf, (len + 1) * sizeof(TCHAR));
    lptstrCopy[len] = (TCHAR)0; // null TCHARacter
    GlobalUnlock(hglbCopy);

    // Place the handle on the clipboard.
    SetClipboardData(
#ifdef UNICODE
        CF_UNICODETEXT,
#else
        CF_TEXT,
#endif
        hglbCopy);

    CloseClipboard();
}
Example #10
0
void SetDlgOutlineTextSp(HWND hDlg,const int *idArray,const int *editWndArray)
{
	if(!OpenClipboard(hDlg))
	{
		AfxMessageBox(_T("clipboard fail!"));
		return;
	}

	UINT cfMp3Infp = RegisterClipboardFormat(CF_MP3INFP);
	HANDLE hText = GetClipboardData(cfMp3Infp);
	if(!hText)
	{
		return;
	}
	
	char *txtData = (char *)GlobalLock(hText);
	if(!txtData)
	{
		return;
	}

	int readOffset = 0;
	while(*(int *)(&(txtData[readOffset])))
	{
		int id = *(int *)(&(txtData[readOffset]));
		readOffset += sizeof(int);
		int len = *(int *)(&(txtData[readOffset]));
		readOffset += sizeof(int);
		if(id != -1)
		{
			for(int i=0; idArray[i]!=0; i++)
			{
				if(idArray[i] == id)
				{
					HWND hwnd = GetDlgItem(hDlg,editWndArray[i]);
					LPCTSTR szTxt = (LPCTSTR)&(txtData[readOffset]);

					if(!IsButton(hwnd))
					{
						// Edit or ComboBox
						if(GetWindowStyle(hwnd) & CBS_DROPDOWNLIST)
						{
							// TODO: Do we need to check the window class?
							ComboBox_SelectString(hwnd, 0, szTxt);
						}
						else
						{
							SetWindowText(hwnd, szTxt);
						}
					}
					else
					{
						// Checkbox
						int val = _ttoi(szTxt) ? 1 : 0;
						CheckDlgButton(hDlg,editWndArray[i],val);
					}
					break;
				}
			}
		}
		readOffset += (len + 1) * sizeof(TCHAR);
	}
		
	GlobalUnlock(hText);
	CloseClipboard();
}
int
winProcSetSelectionOwner (ClientPtr client)
{
  int			i;
  DrawablePtr		pDrawable;
  WindowPtr		pWindow = None;
  Bool			fOwnedToNotOwned = FALSE;
  static Window		s_iOwners[CLIP_NUM_SELECTIONS] = {None};
  static unsigned long	s_ulServerGeneration = 0;
  REQUEST(xSetSelectionOwnerReq);
  
  REQUEST_SIZE_MATCH(xSetSelectionOwnerReq);

#if 0
  ErrorF ("winProcSetSelectionOwner - Hello.\n");
#endif

  /* Watch for server reset */
  if (s_ulServerGeneration != serverGeneration)
    {
      /* Save new generation number */
      s_ulServerGeneration = serverGeneration;

      /* Initialize static variables */
      for (i = 0; i < CLIP_NUM_SELECTIONS; ++i)
	s_iOwners[i] = None;
    }

  /* Abort if clipboard not completely initialized yet */
  if (!g_fClipboardStarted)
    {
      ErrorF ("winProcSetSelectionOwner - Clipboard not yet started, "
	      "aborting.\n");
      goto winProcSetSelectionOwner_Done;
    }
  
  /* Grab window if we have one */
  if (None != stuff->window)
    {
      /* Grab the Window from the request */
      int rc = dixLookupWindow(&pWindow, stuff->window, client, DixReadAccess);
      if (rc != Success) {
	  ErrorF ("winProcSetSelectionOwner - Found BadWindow, aborting.\n");
	  goto winProcSetSelectionOwner_Done;
      }
    }

  /* Now we either have a valid window or None */

  /* Save selection owners for monitored selections, ignore other selections */
  if (XA_PRIMARY == stuff->selection)
    {
      /* Look for owned -> not owned transition */
      if (None == stuff->window
	  && None != s_iOwners[CLIP_OWN_PRIMARY])
	{
	  fOwnedToNotOwned = TRUE;

#if 0
	  ErrorF ("winProcSetSelectionOwner - PRIMARY - Going from "
		  "owned to not owned.\n");
#endif

	  /* Adjust last owned selection */
	  if (None != s_iOwners[CLIP_OWN_CLIPBOARD])
	    g_atomLastOwnedSelection = MakeAtom ("CLIPBOARD", 9, TRUE);
	  else
	    g_atomLastOwnedSelection = None;
	}
      
      /* Save new selection owner or None */
      s_iOwners[CLIP_OWN_PRIMARY] = stuff->window;

#if 0
      ErrorF ("winProcSetSelectionOwner - PRIMARY - Now owned by: %d\n",
	      stuff->window);
#endif
    }
  else if (MakeAtom ("CLIPBOARD", 9, TRUE) == stuff->selection)
    {
      /* Look for owned -> not owned transition */
      if (None == stuff->window
	  && None != s_iOwners[CLIP_OWN_CLIPBOARD])
	{
	  fOwnedToNotOwned = TRUE;
	  
#if 0
	  ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Going from "
		  "owned to not owned.\n");
#endif

	  /* Adjust last owned selection */
	  if (None != s_iOwners[CLIP_OWN_PRIMARY])
	    g_atomLastOwnedSelection = XA_PRIMARY;
	  else
	    g_atomLastOwnedSelection = None;
	}
      
      /* Save new selection owner or None */
      s_iOwners[CLIP_OWN_CLIPBOARD] = stuff->window;

#if 0
      ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Now owned by: %d\n",
	      stuff->window);
#endif
    }
  else
    goto winProcSetSelectionOwner_Done;

  /*
   * At this point, if one of the selections is still owned by the 
   * clipboard manager then it should be marked as unowned since
   * we will be taking ownership of the Win32 clipboard.
   */
  if (g_iClipboardWindow == s_iOwners[CLIP_OWN_PRIMARY])
    s_iOwners[CLIP_OWN_PRIMARY] = None;
  if (g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD])
    s_iOwners[CLIP_OWN_CLIPBOARD] = None;

  /*
   * Handle case when selection is being disowned,
   * WM_DRAWCLIPBOARD did not do the disowning,
   * both monitored selections are no longer owned,
   * an owned to not owned transition was detected,
   * and we currently own the Win32 clipboard.
   */
  if (None == stuff->window
      && g_iClipboardWindow != client->lastDrawableID
      && (None == s_iOwners[CLIP_OWN_PRIMARY]
	  || g_iClipboardWindow == s_iOwners[CLIP_OWN_PRIMARY])
      && (None == s_iOwners[CLIP_OWN_CLIPBOARD]
	  || g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD])
      && fOwnedToNotOwned
      && g_hwndClipboard != NULL
      && g_hwndClipboard == GetClipboardOwner ())
    {
#if 0
      ErrorF ("winProcSetSelectionOwner - We currently own the "
	      "clipboard and neither the PRIMARY nor the CLIPBOARD "
	      "selections are owned, releasing ownership of Win32 "
	      "clipboard.\n");
#endif
      
      /* Release ownership of the Windows clipboard */
      OpenClipboard (NULL);
      EmptyClipboard ();
      CloseClipboard ();

      /* Clear X selection ownership (might still be marked as us owning) */
      s_iOwners[CLIP_OWN_PRIMARY] = None;
      s_iOwners[CLIP_OWN_CLIPBOARD] = None;
      
      goto winProcSetSelectionOwner_Done;
    }

  /* Abort if no window at this point */
  if (None == stuff->window)
    {
#if 0
      ErrorF ("winProcSetSelectionOwner - No window, returning.\n");
#endif
      goto winProcSetSelectionOwner_Done;
    }

  /* Abort if invalid selection */
  if (!ValidAtom (stuff->selection))
    {
      ErrorF ("winProcSetSelectionOwner - Found BadAtom, aborting.\n");
      goto winProcSetSelectionOwner_Done;
    }

  /* Cast Window to Drawable */
  pDrawable = (DrawablePtr) pWindow;
  
  /* Abort if clipboard manager is owning the selection */
  if (pDrawable->id == g_iClipboardWindow)
    {
#if 0
      ErrorF ("winProcSetSelectionOwner - We changed ownership, "
	      "aborting.\n");
#endif
      goto winProcSetSelectionOwner_Done;
    }

  /* Abort if root window is taking ownership */
  if (pDrawable->id == 0)
    {
      ErrorF ("winProcSetSelectionOwner - Root window taking ownership, "
	      "aborting\n");
      goto winProcSetSelectionOwner_Done;
    }

  /* Close clipboard if we have it open already */
  if (GetOpenClipboardWindow () == g_hwndClipboard)
    {
      CloseClipboard ();
    }

  /* Access the Windows clipboard */
  if (!OpenClipboard (g_hwndClipboard))
    {
      ErrorF ("winProcSetSelectionOwner - OpenClipboard () failed: %08x\n",
	      (int) GetLastError ());
      goto winProcSetSelectionOwner_Done;
    }

  /* Take ownership of the Windows clipboard */
  if (!EmptyClipboard ())
    {
      ErrorF ("winProcSetSelectionOwner - EmptyClipboard () failed: %08x\n",
	      (int) GetLastError ());
      goto winProcSetSelectionOwner_Done;
    }

  /* Advertise Unicode if we support it */
  if (g_fUnicodeSupport)
    SetClipboardData (CF_UNICODETEXT, NULL);

  /* Always advertise regular text */
  SetClipboardData (CF_TEXT, NULL);

  /* Save handle to last owned selection */
  g_atomLastOwnedSelection = stuff->selection;

  /* Release the clipboard */
  if (!CloseClipboard ())
    {
      ErrorF ("winProcSetSelectionOwner - CloseClipboard () failed: "
	      "%08x\n",
	      (int) GetLastError ());
      goto winProcSetSelectionOwner_Done;
    }

 winProcSetSelectionOwner_Done:
  return (*winProcSetSelectionOwnerOrig) (client);
}
Example #12
0
int prn_to_clipboard (PRN *prn, int fmt)
{
    char *buf = gretl_print_steal_buffer(prn);
    char *modbuf = NULL;
    int rtf_format = 0;
    int err = 0;

    if (buf == NULL || *buf == '\0') {
	errbox(_("Copy buffer was empty"));
	return 0;
    }

    if (!OpenClipboard(NULL)) {
	errbox(_("Cannot open the clipboard"));
	return 1;
    }

    if (fmt == GRETL_FORMAT_RTF || fmt == GRETL_FORMAT_RTF_TXT) {
	rtf_format = 1;
    }

    EmptyClipboard();

    err = maybe_post_process_buffer(buf, fmt, W_COPY, &modbuf);

    if (!err) {
	HGLOBAL winclip;
	LPTSTR ptr;
	unsigned clip_format;
	gunichar2 *ubuf = NULL;
	char *winbuf;
	glong wrote = 0;
	size_t sz;

	winbuf = modbuf != NULL ? modbuf : buf;

	if (!rtf_format && !gretl_is_ascii(winbuf)) {
	    /* for Windows clipboard, recode UTF-8 to UTF-16 */
	    ubuf = g_utf8_to_utf16(winbuf, -1, NULL, &wrote, NULL);
	}

	if (ubuf != NULL) {
	    sz = (wrote + 1) * sizeof(gunichar2);
	} else {
	    sz = strlen(winbuf) + 1;
	}
	
	winclip = GlobalAlloc(GMEM_MOVEABLE, sz);
	ptr = GlobalLock(winclip);
	if (ubuf != NULL) {
	    memcpy(ptr, ubuf, sz);
	} else {
	    memcpy(ptr, winbuf, sz);
	}
	GlobalUnlock(winclip);    

	if (ubuf != NULL) {
	    clip_format = CF_UNICODETEXT;
	} else if (rtf_format) {
	    clip_format = RegisterClipboardFormat("Rich Text Format");
	} else if (fmt == GRETL_FORMAT_CSV) {
	    clip_format = RegisterClipboardFormat("CSV");
	} else {
	    clip_format = CF_TEXT;
	}

	SetClipboardData(clip_format, winclip);

	if (ubuf != NULL) {
	    g_free(ubuf);
	}
    }

    CloseClipboard();

    free(buf);
    free(modbuf);

    return err;
}
Example #13
0
/**
 *      Function that attempts to retrieve a string from the O/S clipboard
 *      If this functionality is not implemented for you O/S or if it fails then
 *      OSWRAP_FALSE will be returned. Otherwise OSWRAP_TRUE will be returned.
 *      It is assumed that dest has points to size number of allocated bytes.
 *      The actual number of bytes written into the destination buffer is
 *      written into wbytes. If you wish to retrieve all text on the clipboard
 *      you might want to continue calling this function as long as wbytes
 *      equals size. Do note that any other proccess can empty the clipboard
 *      in between calls.
 */
UInt32
StringFromClipboard( char *dest     ,
                     UInt32 size    ,
                     UInt32 *wbytes )
{
        #ifdef GUCEF_MSWIN_BUILD

        HWND whandle = GetCurrentHWND();
        HGLOBAL hglb;
        UInt32 success = OSWRAP_FALSE;

        #ifdef SDL_SUPPORT

        SDL_SysWMinfo winfo;

        #endif /* SDL_SUPPORT */

        if ( IsClipboardFormatAvailable( CF_TEXT ) )
        {
                /*
                 *      Open the clipboard with the current task as the owner
                 */
                if ( !OpenClipboard( whandle ) ) return OSWRAP_FALSE;

                /*
                 *      Get a pointer to the data using the global handle we will
                 *      obtain if possible. Then copy the data pointed to by the handle
                 *      into the buffer provided by the user
                 */
                hglb = GetClipboardData( CF_TEXT );
                if ( hglb != NULL )
                {
                        LPTSTR lptstr = (LPTSTR) GlobalLock( hglb );
                        if ( lptstr != NULL )
                        {
                                UInt32 offset = *wbytes;
                                UInt32 dsize = (UInt32) strlen( lptstr );
                                if ( dsize > offset )
                                {
                                        dsize -= offset;
                                        if ( dsize > size-1 ) dsize = size-1;
                                        strncpy( dest, lptstr+offset, dsize );
                                        *wbytes += dsize;

                                        success = OSWRAP_TRUE;
                                }
                                GlobalUnlock( hglb );
                        }
                        else
                        {
                                *wbytes = 0;
                        }
                }

                /*
                 *      Close the clipboard so that other tasks have access again
                 */
                CloseClipboard();

                return success;
        }
        return OSWRAP_FALSE;

        #else /* GUCEF_MSWIN_BUILD */

        return OSWRAP_FALSE;

        #endif /* OS WRAPPING */
}
Example #14
0
UInt32
StringToClipboard( const char *str )
{
    #ifdef GUCEF_MSWIN_BUILD

    if ( str )
    {
        UInt32 strlength = (UInt32) strlen( str );

        HWND whandle = GetCurrentHWND();
        UInt32 success = OSWRAP_FALSE;
        HGLOBAL hglbcopy;
        LPTSTR lptstrcopy;

        /*
         *      Open the clipboard with the current task as the owner
         */
        if ( !OpenClipboard( whandle ) ) return OSWRAP_FALSE;

        /*
         *      Try to empty the clipboard so that we can get ownership of the
         *      clipboard which is needed for placing data on it.
         */
        EmptyClipboard();

        /*
         *      Allocate global MS windows managed memory for the text
         */
        hglbcopy = GlobalAlloc( GMEM_MOVEABLE                 ,
                                (strlength+1) * sizeof(TCHAR) );
        if ( hglbcopy == NULL )
        {
                CloseClipboard();
                return OSWRAP_FALSE;
        }

        /*
         *      Now we have to lock the memory we just allocated so that
         *      windows keeps it's paws off of it. After that we can copy
         *      our text into the global memory buffer
         */
        lptstrcopy = (LPTSTR) GlobalLock( hglbcopy );
        memcpy( lptstrcopy, str, strlength+1 );
        GlobalUnlock( hglbcopy );

        /*
         *      We now attempt to set the string in the clipboard.
         *      This will fail if the handle we used in OpenClipboard() is
         *      NULL or incorrect.
         */
        if ( SetClipboardData( CF_TEXT, hglbcopy ) )
        {
            success = OSWRAP_TRUE;
        }
        else
        {
            success = OSWRAP_FALSE;
        }

        /*
         *      Close the clipboard so that other tasks have access again
         */
        CloseClipboard();

        return success;
    }
    return OSWRAP_FALSE;

    #else /* GUCEF_MSWIN_BUILD */

    return OSWRAP_FALSE;

    #endif /* OS WRAPPING */
}
Example #15
0
void CJabberDlgGcJoin::OnInitDialog()
{
	CSuper::OnInitDialog();

	Window_SetIcon_IcoLib(m_hwnd, g_GetIconHandle(IDI_GROUP));

	JabberGcRecentInfo *pInfo = NULL;
	if (m_jid)
		pInfo = new JabberGcRecentInfo(m_proto, m_jid);
	else if (OpenClipboard(m_hwnd)) {
		HANDLE hData = GetClipboardData(CF_UNICODETEXT);

		if (hData) {
			TCHAR *buf = (TCHAR *)GlobalLock(hData);
			if (buf && _tcschr(buf, _T('@')) && !_tcschr(buf, _T(' ')))
				pInfo = new JabberGcRecentInfo(m_proto, buf);
			GlobalUnlock(hData);
		}
		CloseClipboard();
	}

	if (pInfo) {
		pInfo->fillForm(m_hwnd);
		delete pInfo;
	}

	ptrT tszNick(m_proto->getTStringA("Nick"));
	if (tszNick == NULL)
		tszNick = JabberNickFromJID(m_proto->m_szJabberJID);
	SetDlgItemText(m_hwnd, IDC_NICK, tszNick);

	TEXTMETRIC tm = { 0 };
	HDC hdc = GetDC(m_hwnd);
	GetTextMetrics(hdc, &tm);
	ReleaseDC(m_hwnd, hdc);
	sttTextLineHeight = tm.tmHeight;
	SendDlgItemMessage(m_hwnd, IDC_ROOM, CB_SETITEMHEIGHT, -1, sttTextLineHeight - 1);

	LOGFONT lf = { 0 };
	HFONT hfnt = (HFONT)SendDlgItemMessage(m_hwnd, IDC_TXT_RECENT, WM_GETFONT, 0, 0);
	GetObject(hfnt, sizeof(lf), &lf);
	lf.lfWeight = FW_BOLD;
	SendDlgItemMessage(m_hwnd, IDC_TXT_RECENT, WM_SETFONT, (WPARAM)CreateFontIndirect(&lf), TRUE);

	SendDlgItemMessage(m_hwnd, IDC_BOOKMARKS, BM_SETIMAGE, IMAGE_ICON, (LPARAM)m_proto->LoadIconEx("bookmarks"));
	SendDlgItemMessage(m_hwnd, IDC_BOOKMARKS, BUTTONSETASFLATBTN, TRUE, 0);
	SendDlgItemMessage(m_hwnd, IDC_BOOKMARKS, BUTTONADDTOOLTIP, (WPARAM)"Bookmarks", 0);
	SendDlgItemMessage(m_hwnd, IDC_BOOKMARKS, BUTTONSETASPUSHBTN, TRUE, 0);

	m_proto->ComboLoadRecentStrings(m_hwnd, IDC_SERVER, "joinWnd_rcSvr");

	int i;
	for (i = 0; i < 5; i++) {
		TCHAR jid[JABBER_MAX_JID_LEN];
		JabberGcRecentInfo info(m_proto);
		if (!info.loadRecent(i))
			break;

		mir_sntprintf(jid, _T("%s@%s (%s)"), info.m_room, info.m_server, info.m_nick ? info.m_nick : TranslateT("<no nick>"));
		SetDlgItemText(m_hwnd, IDC_RECENT1 + i, jid);
	}
	sttJoinDlgShowRecentItems(m_hwnd, i);
}
Example #16
0
WINEXPORT LRESULT CALLBACK WMainWndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
    HMENU               menu;
#if 0
    HWND                win;
#endif
    LRESULT             ret;
    bool                pass_to_def;
    WMenuEditInfo       *einfo;
    WORD                wp;
    MINMAXINFO          *minmax;
    about_info          ai;

    pass_to_def = TRUE;
    ret = FALSE;
    einfo = (WMenuEditInfo *)GET_WNDLONGPTR( hWnd, 0 );
    WSetCurrentEditInfo( einfo );

    switch( message ) {
    case WM_ACTIVATE:
        if( GET_WM_ACTIVATE_FACTIVE( wParam, lParam ) &&
            !GET_WM_ACTIVATE_FMINIMIZED( wParam, lParam ) &&
            einfo != NULL && einfo->edit_dlg != (HWND)NULL ) {
            SetFocus( einfo->edit_dlg );
            pass_to_def = FALSE;
        }
        break;

    case WM_INITMENU:
        if( wParam == (WPARAM)GetMenu( hWnd ) ) {
            // set the cut and copy menu items
            if( SendDlgItemMessage( einfo->edit_dlg, IDM_MENUEDLIST, LB_GETCURSEL, 0, 0 ) != LB_ERR ) {
                EnableMenuItem( (HMENU)wParam, IDM_MENU_CUT, MF_ENABLED );
                EnableMenuItem( (HMENU)wParam, IDM_MENU_COPY, MF_ENABLED );
            } else {
                EnableMenuItem( (HMENU)wParam, IDM_MENU_CUT, MF_GRAYED );
                EnableMenuItem( (HMENU)wParam, IDM_MENU_COPY, MF_GRAYED );
            }
            // set the paste menu item
            if( OpenClipboard( hWnd ) ) {
                if( //IsClipboardFormatAvailable( WClipbdFormat ) ||
                    IsClipboardFormatAvailable( WItemClipbdFormat ) ) {
                    EnableMenuItem( (HMENU)wParam, IDM_MENU_PASTE, MF_ENABLED );
                } else {
                    EnableMenuItem( (HMENU)wParam, IDM_MENU_PASTE, MF_GRAYED );
                }
                CloseClipboard();
            }
        }
        break;

    case WM_CREATE:
        einfo = ((CREATESTRUCT *)lParam)->lpCreateParams;
        SET_WNDLONGPTR( hWnd, 0, (LONG_PTR)einfo );
        break;

    case WM_MENUSELECT:
        if( einfo != NULL ) {
            menu = WGetMenuHandle( einfo );
            WHandleMenuSelect( einfo->wsb, menu, wParam, lParam );
        }
        break;

    case WM_GETMINMAXINFO:
        minmax = (MINMAXINFO *)lParam;
        minmax->ptMinTrackSize.x = appWidth;
        minmax->ptMinTrackSize.y = appHeight;
        break;

    case WM_MOVE:
        if( einfo != NULL ) {
            if( IsZoomed( hWnd ) ) {
                WSetOption( WOptScreenMax, TRUE );
            } else if( !IsIconic( hWnd ) ) {
                WUpdateScreenPosOpt( hWnd );
                WSetOption( WOptScreenMax, FALSE );
            }
            WMovePrevWindow( einfo );
        }
        break;

    case WM_SETFOCUS:
        if( einfo != NULL && einfo->preview_window != (HWND)NULL ) {
            SendMessage( einfo->preview_window, WM_NCACTIVATE, (WPARAM)TRUE, (LPARAM)NULL );
        }
        break;

    case WM_SHOWWINDOW:
        if( wParam ) {
            ShowWindow( einfo->preview_window, SW_SHOWNA );
        } else {
            ShowWindow( einfo->preview_window, SW_HIDE );
        }
        break;

    case WM_SIZE:
        if( einfo != NULL ) {
            if( wParam == SIZE_MAXIMIZED ) {
                WSetOption( WOptScreenMax, TRUE );
            } else if ( wParam != SIZE_MINIMIZED ) {
                WUpdateScreenPosOpt( hWnd );
                WSetOption( WOptScreenMax, FALSE );
            }
            if( einfo->preview_window != (HWND)NULL ) {
                if( wParam == SIZE_MINIMIZED ) {
                    ShowWindow( einfo->preview_window, SW_HIDE );
                } else {
                    ShowWindow( einfo->preview_window, SW_SHOWNA );
                }
            }
            if( wParam != SIZE_MINIMIZED ) {
                WResizeWindows( einfo );
            }
        }
        break;

#if 0
    case WM_ACTIVATE:
        if( GET_WM_ACTIVATE_FACTIVE( wParam, lParam ) != WA_INACTIVE ) {
            win = GET_WM_ACTIVATE_HWND( wParam, lParam );
            einfo = (WMenuEditInfo *)GET_WNDLONGPTR( win, 0 );
            WSetCurrentEditInfo( einfo );
        } else {
            WSetCurrentEditInfo( NULL );
        }
        break;
#endif

    case WM_COMMAND:
        wp = LOWORD( wParam );
        switch( wp ) {
        case IDM_MENU_CLEAR:
            WHandleClear( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_UPDATE:
            SendMessage( einfo->info->parent, MENU_PLEASE_SAVEME, 0,
                         (LPARAM)einfo->hndl );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_OPEN:
            pass_to_def = FALSE;
            if( einfo->info->modified ) {
                ret = WQuerySave( einfo, FALSE );
                if( !ret ) {
                    break;
                }
            }
            ret = SendMessage( einfo->info->parent, MENU_PLEASE_OPENME, 0,
                               (LPARAM)einfo->hndl );
            ret = FALSE;
            break;

        case IDM_MENU_SAVE:
            WSaveObject( einfo, FALSE, FALSE );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_SAVEAS:
            WSaveObject( einfo, TRUE, FALSE );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_SAVEINTO:
            WSaveObject( einfo, TRUE, TRUE );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_EXIT:
            /* clean up before we exit */
            PostMessage( einfo->win, WM_CLOSE, 0, 0 );
            break;

        case IDM_MENU_PASTE:
            WPasteMenuItem( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_CUT:
        case IDM_MENU_COPY:
            WClipMenuItem( einfo, wp == IDM_MENU_CUT );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_DELETE:
            WDeleteMenuEntry( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_INSERTSUBITEMS:
            WToggleInsertSubitems( einfo );
            break;

        case IDM_MENU_INSERTBEFORE:
            if( !einfo->insert_before ) {
                WToggleInsertBitmap( einfo );
            }
            break;

        case IDM_MENU_INSERTAFTER:
            if( einfo->insert_before ) {
                WToggleInsertBitmap( einfo );
            }
            break;

        case IDM_MENU_INSERTTOGGLE:
            WToggleInsertBitmap( einfo );
            break;

#if 0
        case IDM_MENU_NEWITEM:
            WInsertNewMenuEntry( einfo, FALSE, FALSE );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_NEWPOPUP:
            WInsertNewMenuEntry( einfo, TRUE, FALSE );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_NEWSEPARATOR:
            WInsertNewMenuEntry( einfo, FALSE, TRUE );
            pass_to_def = FALSE;
            break;
#else
        case IDM_MENU_NEWITEM:
            WInsertNew( einfo );
            pass_to_def = FALSE;
            break;
#endif

        case IDM_MENU_SYMBOLS:
            handleSymbols( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_LOAD_SYMBOLS:
            handleLoadSymbols( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_SHOWRIBBON:
            menu = WGetMenuHandle( einfo );
            WShowRibbon( einfo, menu );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_MEM_FLAGS:
            WSetStatusByID( einfo->wsb, W_CHANGEMENUMEMFLAGS, -1 );
            einfo->info->modified |= WChangeMemFlags( einfo->win, &einfo->info->MemFlags,
                                                      einfo->info->res_name,
                                                      WGetEditInstance(),
                                                      WMenuHelpRoutine );
            WSetStatusReadyText( einfo->wsb );
            pass_to_def = FALSE;
            break;

        case IDM_MENU_RENAME:
            WHandleRename( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_HELP:
            WMenuHelpRoutine();
            pass_to_def = FALSE;
            break;

        case IDM_HELP_SEARCH:
            WMenuHelpSearchRoutine();
            pass_to_def = FALSE;
            break;

        case IDM_HELP_ON_HELP:
            WMenuHelpOnHelpRoutine();
            pass_to_def = FALSE;
            break;

        case IDM_MENU_ABOUT:
            ai.owner = hWnd;
            ai.inst = WGetEditInstance();
            ai.name = AllocRCString( W_ABOUT_NAME );
            ai.version = AllocRCString( W_ABOUT_VERSION );
            ai.first_cr_year = "2002";
            ai.title = AllocRCString( W_ABOUT_TITLE );
            DoAbout( &ai );
            FreeRCString( ai.name );
            FreeRCString( ai.version );
            FreeRCString( ai.title );
            pass_to_def = FALSE;
            break;
        }
        break;

    case WM_DESTROY:
        WWinHelp( hWnd, "resmnu.hlp", HELP_QUIT, 0 );
        WCleanup( einfo );
        break;

    case WM_CLOSE:
        ret = TRUE;
        pass_to_def = WHandleWM_CLOSE( einfo, wParam != 0 );
        wParam = 0;
        break;
    }

    if( pass_to_def ) {
        ret = DefWindowProc( hWnd, message, wParam, lParam );
    }

    return( ret );
}
Example #17
0
BOOL ClipboardPaste(void)
{
	HGLOBAL  hMem = 0;
	LPSTR	 lpMem;
	UINT	 uFormat = CharSet == CS_OEM ? CF_OEMTEXT : CF_TEXT;
	LONG	 lSize;
	MODEENUM SaveMode;
	BOOL	 FreeConversionMemory = FALSE;

	if (IsViewOnly()) return(FALSE);

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

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

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

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

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

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

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

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

									while ((i += 2) <= lSize) {
										lpMem[i-2] = *lpWideCharMem >> 8;
										lpMem[i-1] = *lpWideCharMem++ & 255;
									}
									FreeConversionMemory = TRUE;
								} else {
									GlobalFree(hMem);
									hMem = 0;
								}
							}
						}
					} else {
Example #18
0
static Image *ReadCLIPBOARDImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  Image
    *image;

  register ssize_t
    x;

  register Quantum
    *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,exception);
  {
    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->rows=bitmap.bmHeight;
          image->columns=bitmap.bmWidth;
        }
      /*
        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 == (Quantum *) NULL)
          break;
        for (x=0; x < (ssize_t) image->columns; x++)
        {
          SetPixelRed(image,ScaleCharToQuantum(pBits->rgbRed),q);
          SetPixelGreen(image,ScaleCharToQuantum(pBits->rgbGreen),q);
          SetPixelBlue(image,ScaleCharToQuantum(pBits->rgbBlue),q);
          SetPixelAlpha(image,OpaqueAlpha,q);
          pBits++;
          q+=GetPixelChannels(image);
        }
        if (SyncAuthenticPixels(image,exception) == MagickFalse)
          break;
      }
      DeleteDC(hDC);
      DeleteObject(hBitmap);
    }
  }
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}
Example #19
0
VOID
StoreSelection(
    IN PCONSOLE_INFORMATION Console
    )

/*++

 StoreSelection - Store selection (if present) into the Clipboard

--*/

{
    PCHAR_INFO Selection,CurCharInfo;
    COORD SourcePoint;
    COORD TargetSize;
    SMALL_RECT TargetRect;
    PWCHAR CurChar,CharBuf;
    HANDLE ClipboardDataHandle;
    SHORT i,j;
    BOOL Success;
    PSCREEN_INFORMATION ScreenInfo;
    BOOL bFalseUnicode;

    //
    // See if there is a selection to get
    //

    if (!(Console->SelectionFlags & CONSOLE_SELECTION_NOT_EMPTY)) {
        return;
    }

    //
    // read selection rectangle.  clip it first.
    //

    ScreenInfo = Console->CurrentScreenBuffer;
    if (Console->SelectionRect.Left < 0) {
        Console->SelectionRect.Left = 0;
    }
    if (Console->SelectionRect.Top < 0) {
        Console->SelectionRect.Top = 0;
    }
    if (Console->SelectionRect.Right >= ScreenInfo->ScreenBufferSize.X) {
        Console->SelectionRect.Right = (SHORT)(ScreenInfo->ScreenBufferSize.X-1);
    }
    if (Console->SelectionRect.Bottom >= ScreenInfo->ScreenBufferSize.Y) {
        Console->SelectionRect.Bottom = (SHORT)(ScreenInfo->ScreenBufferSize.Y-1);
    }

    TargetSize.X = WINDOW_SIZE_X(&Console->SelectionRect);
    TargetSize.Y = WINDOW_SIZE_Y(&Console->SelectionRect);
    if (ScreenInfo->Flags & CONSOLE_TEXTMODE_BUFFER) {
        Selection = (PCHAR_INFO)HeapAlloc(pConHeap,MAKE_TAG( TMP_TAG ),sizeof(CHAR_INFO) * TargetSize.X * TargetSize.Y);
        if (Selection == NULL)
            return;

#ifdef _X86_
        if ((Console->FullScreenFlags & CONSOLE_FULLSCREEN) &&
            (Console->Flags & CONSOLE_VDM_REGISTERED)) {
            ReadRegionFromScreenHW(ScreenInfo,
                                   &Console->SelectionRect,
                                   Selection);
        } else {
#endif
            SourcePoint.X = Console->SelectionRect.Left;
            SourcePoint.Y = Console->SelectionRect.Top;
            TargetRect.Left = TargetRect.Top = 0;
            TargetRect.Right = (SHORT)(TargetSize.X-1);
            TargetRect.Bottom = (SHORT)(TargetSize.Y-1);
            ReadRectFromScreenBuffer(ScreenInfo,
                                     SourcePoint,
                                     Selection,
                                     TargetSize,
                                     &TargetRect);
#ifdef _X86_
        }
#endif

        // extra 2 per line is for CRLF, extra 1 is for null
        ClipboardDataHandle = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
                (TargetSize.Y * (TargetSize.X + 2) + 1) * sizeof(WCHAR));
        if (ClipboardDataHandle == NULL) {
            HeapFree(pConHeap,0,Selection);
            return;
        }

        //
        // convert to clipboard form
        //

        CurCharInfo = Selection;
        CurChar = CharBuf = GlobalLock(ClipboardDataHandle);
        bFalseUnicode = ((ScreenInfo->Flags & CONSOLE_OEMFONT_DISPLAY) &&
                !(Console->FullScreenFlags & CONSOLE_FULLSCREEN));
        for (i=0;i<TargetSize.Y;i++) {
            PWCHAR pwchLineStart = CurChar;

            for (j=0;j<TargetSize.X;j++,CurCharInfo++,CurChar++) {
                *CurChar = CurCharInfo->Char.UnicodeChar;
                if (*CurChar == 0) {
                    *CurChar = UNICODE_SPACE;
                }
            }
            // trim trailing spaces
            CurChar--;
            while ((CurChar >= pwchLineStart) && (*CurChar == UNICODE_SPACE))
                CurChar--;

            CurChar++;
            if (bFalseUnicode) {
                FalseUnicodeToRealUnicode(pwchLineStart,
                        CurChar - pwchLineStart, Console->OutputCP);
            }
            *CurChar++ = UNICODE_CARRIAGERETURN;
            *CurChar++ = UNICODE_LINEFEED;
        }
        if (TargetSize.Y)
            CurChar -= 2;   // don't put CRLF on last line
        *CurChar = '\0';    // null terminate
        GlobalUnlock(ClipboardDataHandle);
        HeapFree(pConHeap,0,Selection);

        Success = OpenClipboard(Console->hWnd);
        if (!Success) {
            GlobalFree(ClipboardDataHandle);
            return;
        }

        Success = EmptyClipboard();
        if (!Success) {
            GlobalFree(ClipboardDataHandle);
            return;
        }

        SetClipboardData(CF_UNICODETEXT,ClipboardDataHandle);
        CloseClipboard();   // Close clipboard
    } else {
        HBITMAP hBitmapTarget, hBitmapOld;
        HDC hDCMem;
        HPALETTE hPaletteOld;
	int Height;

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

        hDCMem = CreateCompatibleDC(Console->hDC);
        hBitmapTarget = CreateCompatibleBitmap(Console->hDC,
                                                  TargetSize.X,
                                                  TargetSize.Y);
        if (hBitmapTarget) {
            hBitmapOld = SelectObject(hDCMem, hBitmapTarget);
            if (ScreenInfo->hPalette) {
                hPaletteOld = SelectPalette(hDCMem,
                                             ScreenInfo->hPalette,
                                             FALSE);
            }
            MyInvert(Console,&Console->SelectionRect);

	    // if (DIB is a top-down)
	    //	    ySrc = abs(height) - rect.bottom - 1;
	    // else
	    //	    ySrc = rect.Bottom.
	    //
	    Height = ScreenInfo->BufferInfo.GraphicsInfo.lpBitMapInfo->bmiHeader.biHeight;

            StretchDIBits(hDCMem, 0, 0,
                        TargetSize.X, TargetSize.Y,
			Console->SelectionRect.Left + ScreenInfo->Window.Left,
			(Height < 0) ? -Height - (Console->SelectionRect.Bottom + ScreenInfo->Window.Top) -  1
				     : Console->SelectionRect.Bottom + ScreenInfo->Window.Top,
                        TargetSize.X, TargetSize.Y,
                        ScreenInfo->BufferInfo.GraphicsInfo.BitMap,
                        ScreenInfo->BufferInfo.GraphicsInfo.lpBitMapInfo,
                        ScreenInfo->BufferInfo.GraphicsInfo.dwUsage,
                        SRCCOPY);
            MyInvert(Console,&Console->SelectionRect);
            if (ScreenInfo->hPalette) {
                SelectPalette(hDCMem, hPaletteOld, FALSE);
            }
            SelectObject(hDCMem, hBitmapOld);
            OpenClipboard(Console->hWnd);
            EmptyClipboard();
            SetClipboardData(CF_BITMAP,hBitmapTarget);
            CloseClipboard();
        }
        DeleteDC(hDCMem);
        NtReleaseMutant(ScreenInfo->BufferInfo.GraphicsInfo.hMutex, NULL);
    }

}
Example #20
0
/*
MainDlgProc handles messages to the main dialog box
*/
INT_PTR CALLBACK MainDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	DIALOGPARAM *DlgParam = (DIALOGPARAM*)GetWindowLongPtr(hDlg, GWLP_USERDATA);
	HMENU listMenu;

	switch (msg) {
	case WM_INITDIALOG: {
		MCONTACT hContact;
		TCHAR title[256];
		TCHAR filter[FILTERTEXT];
		RECT rc;
		POINT pt;
			
		SetWindowLongPtr(hDlg, GWLP_USERDATA, lParam);
		DlgParam = (DIALOGPARAM*)lParam;
		listMenu = GetMenu(hDlg);
		TranslateDialogDefault(hDlg);
		TranslateMenu(listMenu);

		hContact = ((db_get_b(NULL, LINKLIST_MODULE, LINKLIST_SAVESPECIAL, 0) == 0) ? NULL: DlgParam->hContact);
		if (db_get_b(hContact, LINKLIST_MODULE, LINKLIST_FIRST, 0) == 0) {
			// First use of this plugin! Set default size!
			db_set_dw(hContact, LINKLIST_MODULE, "LinklistWidth", 400);
			db_set_dw(hContact, LINKLIST_MODULE, "LinklistHeight", 450);
			db_set_dw(hContact, LINKLIST_MODULE, "LinklistX", 0);
			db_set_dw(hContact, LINKLIST_MODULE, "LinklistY", 0);
				
			db_set_b(hContact, LINKLIST_MODULE, LINKLIST_FIRST, 1);
		}

		DlgParam->splitterPosNew = (int)db_get_dw(hContact, LINKLIST_MODULE, LINKLIST_SPLITPOS, -1);

		GetWindowRect(GetDlgItem(hDlg, IDC_MAIN), &rc);
		DlgParam->minSize.cx = rc.right - rc.left;
		DlgParam->minSize.cy = rc.bottom - rc.top;

		GetWindowRect(GetDlgItem(hDlg, IDC_SPLITTER), &rc);
		pt.y = (rc.top + rc.bottom) / 2;
		pt.x = 0;
		ScreenToClient(hDlg, &pt);
			
		DlgParam->splitterPosOld = rc.bottom - 20 - pt.y;
		if(DlgParam->splitterPosNew == -1)
			DlgParam->splitterPosNew = DlgParam->splitterPosOld;
			
		Utils_RestoreWindowPosition(hDlg, hContact, LINKLIST_MODULE, "Linklist");

		SetClassLongPtr(hDlg, GCLP_HICON, (LONG_PTR)LoadIcon(hInst, MAKEINTRESOURCE(IDI_LINKLISTICON))); 
		WindowList_Add(hWindowList, hDlg, DlgParam->hContact);
		mir_sntprintf(title, _T("%s [%s]"), TranslateT("Linklist plugin"), pcli->pfnGetContactDisplayName(DlgParam->hContact, 0));
		SetWindowText(hDlg, title);
		GetFilterText(listMenu, filter, _countof(filter));
		SetDlgItemText(hDlg, IDC_STATUS, filter);
			
		mir_subclassWindow(GetDlgItem(hDlg, IDC_SPLITTER), SplitterProc);
			
		SendDlgItemMessage( hDlg, IDC_MAIN, EM_SETEVENTMASK, 0, (LPARAM)ENM_LINK);
		SendDlgItemMessage( hDlg, IDC_MAIN, EM_AUTOURLDETECT, TRUE, 0 );
		// This is used in srmm... and I think he knew what he did... :)
		SendDlgItemMessage(hDlg, IDC_MAIN, EM_LIMITTEXT, (WPARAM)-1, 0);

		WriteLinkList(hDlg, WLL_ALL, (LISTELEMENT*)DlgParam->listStart, NULL, 0);

		return TRUE;
		} break;
	// open browser an load url if link is pressed
	// found at
	// http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.ui/2004-03/0133.html
	//
	// Popup menu on right mouse button is mainly taken from the miranda 
	// send/receive messaging plugin.
	case WM_NOTIFY: {  
		if (lParam == NULL)
			break;
		if (((LPNMHDR)lParam)->code != EN_LINK)
			break;
		LPTSTR link;
		BYTE mouseEvent;
		ENLINK *pENLink = (ENLINK*)lParam;

		mouseEvent = db_get_b(NULL, LINKLIST_MODULE, LINKLIST_MOUSE_EVENT, 0xFF);

		switch (pENLink->msg) {
		case WM_MOUSEMOVE:
			if (mouseEvent != 0x01)
				break;
			memcpy(&DlgParam->chrg, &pENLink->chrg, sizeof(CHARRANGE));
			SendDlgItemMessage(hDlg, IDC_MAIN, EM_EXSETSEL, 0, (LPARAM)&pENLink->chrg);
			WriteMessage(hDlg, DlgParam->listStart, SendDlgItemMessage(hDlg, IDC_MAIN, EM_LINEFROMCHAR, -1, 0));
			break;
		case WM_LBUTTONUP:
			link = (LPTSTR)mir_alloc((pENLink->chrg.cpMax - pENLink->chrg.cpMin + 2) * sizeof(TCHAR));
			if (link == NULL)
				break;
			SendDlgItemMessage(hDlg, IDC_MAIN, EM_EXSETSEL, 0, (LPARAM)&pENLink->chrg); 
			SendDlgItemMessage(hDlg, IDC_MAIN, EM_GETSELTEXT, 0, (LPARAM)link);
			if (_tcsstr(link, _T("mailto:")) != NULL)
				ShellExecute(HWND_TOP, NULL, link, NULL, NULL, SW_SHOWNORMAL); 
			else {
				bool openNewWindow = db_get_b(NULL, LINKLIST_MODULE, LINKLIST_OPEN_WINDOW, 0xFF) != 0xFF;
				Utils_OpenUrlT(link,openNewWindow);
			}
			mir_free(link);
			break;
		case WM_RBUTTONDOWN: { 
			HMENU hPopup, hSubMenu;
			POINT pt;
			hPopup = LoadMenu(hInst, MAKEINTRESOURCE(IDR_MENU2));
			hSubMenu = GetSubMenu(hPopup, 0);

			// Disable Menuoption if "mouse over" events are active
			mouseEvent = db_get_b(NULL, LINKLIST_MODULE, LINKLIST_MOUSE_EVENT, 0xFF);
			if (mouseEvent == 0x01)
				EnableMenuItem(hSubMenu, IDM_SHOWMESSAGE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);	
			TranslateMenu(hSubMenu);
			link = (LPTSTR)mir_alloc((pENLink->chrg.cpMax - pENLink->chrg.cpMin + 4) * sizeof(TCHAR));
			if (link == NULL)
				break;
			SendDlgItemMessage(hDlg, IDC_MAIN, EM_EXSETSEL, 0, (LPARAM)&pENLink->chrg); 
			SendDlgItemMessage(hDlg, IDC_MAIN, EM_GETSELTEXT, 0, (LPARAM)link);

			pt.x = (short)LOWORD(pENLink->lParam);
			pt.y = (short)HIWORD(pENLink->lParam);
			ClientToScreen(((NMHDR*)lParam)->hwndFrom, &pt);

			switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, pt.x, pt.y, 0, hDlg, NULL)) {
			case IDM_LINK_OPEN:
				if (_tcsstr(link, _T("mailto:")) != NULL)
					ShellExecute(HWND_TOP, NULL, link, NULL, NULL, SW_SHOWNORMAL); 
				else
					Utils_OpenUrlT(link,false);
				break;
			case IDM_LINK_OPENNEW:
				if (_tcsstr(link, _T("mailto:")) != NULL)
					ShellExecute(HWND_TOP, NULL, link, NULL, NULL, SW_SHOWNORMAL); 
				else
					Utils_OpenUrlT(link);
				break;
			case IDM_LINK_COPY: {
				if (!OpenClipboard(hDlg))
					break;
				EmptyClipboard();

				size_t dataLen = ((mir_tstrlen(link) + 1) * sizeof(TCHAR));
				HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE, dataLen);
				memcpy((LPTSTR)GlobalLock(hData), link, dataLen);
				GlobalUnlock(hData);
				SetClipboardData(CF_UNICODETEXT, hData);
				CloseClipboard();
				} break;
			case IDM_SHOWMESSAGE:
				WriteMessage(hDlg, DlgParam->listStart, SendDlgItemMessage(hDlg, IDC_MAIN, EM_LINEFROMCHAR, -1, 0));
				break;
			}
			mir_free(link);
			DestroyMenu(hPopup);
			} break;
		}
		} break;
	case WM_COMMAND: {
		TCHAR filter[40];

		listMenu = GetMenu(hDlg);
		switch (wParam) {
		case IDM_SEARCH: // open Search Box
			if (DlgParam != 0) {	
				HWND hWndSearchDlg = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_SEARCH_DLG), hDlg, SearchDlgProc, (LPARAM)DlgParam);
				EnableMenuItem(listMenu, IDM_SEARCH, (MF_BYCOMMAND | MF_DISABLED | MF_GRAYED));
				ShowWindow(hWndSearchDlg, SW_SHOW);
				SetFocus(GetDlgItem(hWndSearchDlg, IDC_SEARCHSTRING));
			}
			break;
		case IDM_CLEARSEARCH: // clear search results
			GetFilterText(listMenu, filter, _countof(filter));
			SetDlgItemText(hDlg, IDC_STATUS, filter);
			SetDlgItemText(hDlg, IDC_MAIN, _T(""));
			WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);
			break;
		case IDM_SAVE: // save button
			SaveEditAsStream(hDlg);
			SetFocus(GetDlgItem(hDlg, IDC_MAIN));
			break;
		case IDCANCEL: // Esc or Close pressed
		case IDM_CLOSE:
			SendMessage(hDlg, WM_CLOSE, 0, 0);
			break;
		case IDM_DIR_IN: // view only incoming messages
			GetFilterText(listMenu, filter, _countof(filter));
			SetDlgItemText(hDlg, IDC_STATUS, filter);
			if ((GetMenuState(listMenu, IDM_SEARCH, MF_BYCOMMAND) & MF_DISABLED))
				break; // not possible if search dialog is open
			SetDlgItemText(hDlg, IDC_MAIN, _T(""));
			if (GetMenuState(listMenu, IDM_DIR_IN, MF_BYCOMMAND) == MF_CHECKED) {
				CheckMenuItem(listMenu, IDM_DIR_IN, MF_UNCHECKED);
				WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);
			} else {
				CheckMenuItem(listMenu, IDM_DIR_IN, MF_CHECKED);
				CheckMenuItem(listMenu, IDM_DIR_OUT, MF_UNCHECKED);
				WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);
			}		
			GetFilterText(GetMenu(hDlg), filter, _countof(filter));
			SetDlgItemText(hDlg, IDC_STATUS, filter);
			break;
		case IDM_DIR_OUT: // view only outgoing messages
			GetFilterText(listMenu, filter, _countof(filter));
			SetDlgItemText(hDlg, IDC_STATUS, filter);
			if ((GetMenuState(listMenu, IDM_SEARCH, MF_BYCOMMAND) & MF_DISABLED))
				break; // not possible if search dialog is open
			SetDlgItemText(hDlg, IDC_MAIN, _T(""));
			if (GetMenuState(listMenu, IDM_DIR_OUT, MF_BYCOMMAND) == MF_CHECKED) {
				CheckMenuItem(listMenu, IDM_DIR_OUT, MF_UNCHECKED);		
				WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);
			} else {
				CheckMenuItem(listMenu, IDM_DIR_OUT, MF_CHECKED);
				CheckMenuItem(listMenu, IDM_DIR_IN, MF_UNCHECKED);
				WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);
			}
			GetFilterText(listMenu, filter, _countof(filter));
			SetDlgItemText(hDlg, IDC_STATUS, filter);
			break;
		case IDM_TYPE_WEB: // view only e-mail addresses
			GetFilterText(listMenu, filter, _countof(filter));
			SetDlgItemText(hDlg, IDC_STATUS, filter);
			// not possible if search dialog is open
			if ((GetMenuState(listMenu, IDM_SEARCH, MF_BYCOMMAND) & MF_DISABLED))
				break;
			SetDlgItemText(hDlg, IDC_MAIN, _T(""));
			if (GetMenuState(listMenu, IDM_TYPE_WEB, MF_BYCOMMAND) == MF_CHECKED) {
				CheckMenuItem(listMenu, IDM_TYPE_WEB, MF_UNCHECKED);		
				WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);
			} else {
				CheckMenuItem(listMenu, IDM_TYPE_WEB, MF_CHECKED);
				CheckMenuItem(listMenu, IDM_TYPE_MAIL, MF_UNCHECKED);
				WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);
			}
			GetFilterText(listMenu, filter, _countof(filter));
			SetDlgItemText(hDlg, IDC_STATUS, filter);
			break;
		case IDM_TYPE_MAIL: // view only URLs
			if ((GetMenuState(listMenu, IDM_SEARCH, MF_BYCOMMAND) & MF_DISABLED))
				break; // not possible if search dialog is open
			SetDlgItemText(hDlg, IDC_MAIN, _T(""));
			if (GetMenuState(listMenu, IDM_TYPE_MAIL, MF_BYCOMMAND) == MF_CHECKED) {
				CheckMenuItem(listMenu, IDM_TYPE_MAIL, MF_UNCHECKED);		
				WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);				
			} else {
				CheckMenuItem(listMenu, IDM_TYPE_MAIL, MF_CHECKED);
				CheckMenuItem(listMenu, IDM_TYPE_WEB, MF_UNCHECKED);
				WriteLinkList(hDlg, GetFlags(listMenu), DlgParam->listStart, NULL, 0);
			}
			GetFilterText(listMenu, filter, _countof(filter));
			SetDlgItemText(hDlg, IDC_STATUS, filter);
			break;
		}
		} break;
	// Taken from srmm.
	// Btw: The longer I searched the source of this plugin
	// to learn how things work, the more I became a fan of
	// the programmer! 
	case WM_GETMINMAXINFO: {
		MINMAXINFO *mmi = (MINMAXINFO *)lParam;
		RECT rcWindow, rcMain;

		GetWindowRect(hDlg, &rcWindow);
		GetWindowRect(GetDlgItem(hDlg, IDC_MAIN), &rcMain);
		mmi->ptMinTrackSize.x = rcWindow.right - rcWindow.left - ((rcMain.right - rcMain.left) - DlgParam->minSize.cx);
		mmi->ptMinTrackSize.y = rcWindow.bottom - rcWindow.top - ((rcMain.bottom - rcMain.top) - DlgParam->minSize.cy);
		} break;
	case WM_SIZE:
		Utils_ResizeDialog(hDlg, hInst, MAKEINTRESOURCEA(IDD_MAIN_DLG), LinklistResizer, (LPARAM)DlgParam);
		// To get some scrollbars if needed...
		RedrawWindow(GetDlgItem(hDlg, IDC_MAIN), NULL, NULL, RDW_INVALIDATE);
		RedrawWindow(GetDlgItem(hDlg, IDC_MESSAGE), NULL, NULL, RDW_INVALIDATE);
		break;
	
	case DM_LINKSPLITTER: {
		POINT pt;
		RECT rc;
		int splitPosOld;

		GetClientRect(hDlg, &rc);
		pt.x = 0;
		pt.y = wParam;
		ScreenToClient(hDlg, &pt);

		splitPosOld = DlgParam->splitterPosNew;
		DlgParam->splitterPosNew = rc.bottom - pt.y;
			
		GetWindowRect(GetDlgItem(hDlg, IDC_MESSAGE), &rc);
		if (rc.bottom - rc.top + (DlgParam->splitterPosNew - splitPosOld) < 0)
			DlgParam->splitterPosNew = splitPosOld + 0 - (rc.bottom - rc.top);

		GetWindowRect(GetDlgItem(hDlg, IDC_MAIN), &rc);
		if (rc.bottom - rc.top - (DlgParam->splitterPosNew - splitPosOld) < DlgParam->minSize.cy)
			DlgParam->splitterPosNew = splitPosOld - DlgParam->minSize.cy + (rc.bottom - rc.top);
		SendMessage(hDlg, WM_SIZE, 0, 0);
		} break;
	case WM_CLOSE:
		DestroyWindow(hDlg);
		break;
	case WM_DESTROY:
		if (DlgParam != NULL) {
			MCONTACT hContact = ((db_get_b(NULL, LINKLIST_MODULE, LINKLIST_SAVESPECIAL, 0) == 0) ? NULL: DlgParam->hContact);
			Utils_SaveWindowPosition(hDlg, hContact, LINKLIST_MODULE, "Linklist");
			db_set_dw(NULL, LINKLIST_MODULE, LINKLIST_SPLITPOS, DlgParam->splitterPosNew);
			RemoveList(DlgParam->listStart);
			mir_free(DlgParam);
		}
		// Remove entry from Window list
		WindowList_Remove(hWindowList, hDlg);
		break;
	}
	return FALSE;
}
Example #21
0
LRESULT CALLBACK EditCtlProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
    LPCTSTR lpTable, lpTable1;
    TCHAR   c;
#ifdef FAREAST
    TCHAR ch, chHW;
#endif // FAREAST
    HKL     hkl = GetKeyboardLayout(0);

    ASSERT(oldEditCtlProc);

    switch (message) {
    case WM_PASTE :
    {
        BOOL bPassThrough = TRUE;

        if (IsNumericOnlyEdit(hwnd))
        {
            // only going to accept pastes that have pure numeric data in them

            HANDLE hMem;

            if(OpenClipboard(hwnd))
            {
                hMem = GetClipboardData(CF_UNICODETEXT);
                if(hMem)
                {
                    TCHAR *pText = (TCHAR *)LocalLock(hMem); // can't fail on CE
                    int iLen = _tcslen(pText);
                    int iPos = 0;

                    for (iPos = 0; (iPos < iLen) && bPassThrough; iPos++)
                    {
                        if (!_istdigit(pText[iPos]))
                        {
                            // bad char
                            bPassThrough = FALSE;

                        }
                    }

                    LocalUnlock(hMem);
                }
                CloseClipboard();
            }
        }

        if (bPassThrough)
        {
            return CallWindowProc(oldEditCtlProc,hwnd, message, wParam, lParam);
        } else {
            MessageBeep(MB_OK);
            return FALSE;
        }
    }
    break;


    case WM_IME_COMPOSITION:
        if( ImmIsIME(hkl ) &&
                LOWORD(hkl ) == MAKELANGID(LANG_KOREAN, SUBLANG_DEFAULT))
        {
            HIMC himc = ImmGetContext(hwnd);
            if (himc)
            {
                TCHAR szTempStr[4];
                if (0<ImmGetCompositionString(himc,GCS_COMPSTR, szTempStr, 4))
                {
                    DWORD fdwConversion;
                    DWORD fdwSentence;

                    ImmNotifyIME(himc,NI_COMPOSITIONSTR,CPS_CANCEL,0);
                    ImmGetConversionStatus(himc, &fdwConversion, &fdwSentence);
                    fdwConversion&=(~IME_CMODE_NATIVE);
                    ImmSetConversionStatus(himc,fdwConversion, fdwSentence);
                }
                ImmReleaseContext(hwnd,himc);
                return CallWindowProc(oldEditCtlProc,hwnd, message, wParam, lParam);
            }
        }
        break;

    case WM_CHAR:
#ifdef FAREAST // Convert full-width numbers to half width
        ch = (TCHAR)wParam;
        LCMapString(LOCALE_USER_DEFAULT, LCMAP_HALFWIDTH,
                    &ch, 1, &chHW, 1);
        wParam = (WPARAM)chHW;
#endif // FAREAST
        // This character is not ASCII. If your country/region needs specific characters. You
        // have to change this. Otherwise, we abandon this character.
        if (wParam >= 0x80 )  {  // service on ilegal chars
            MessageBeep(MB_OK);
            return TRUE;
        }
        if (wParam < VK_SPACE || wParam > 0x7e )  {  // service on legal chars
            //DPF("None ascii char. ignore \r\n ");
            break;
        }

        if ((lpTable = GetTable(hwnd)) == NULL) {
            //				DPF("Can not find table, trying parent \r\n");
            if ((lpTable = GetTable(GetParent(hwnd))) == NULL) {
                //DPF("Can not find table,  \r\n");
                break;
            }
        }
        lpTable1 = lpTable;
        if (wParam >= '0' && wParam <= '9')
            goto found;
        while ((c = *lpTable++) > 0) {
            if ((TCHAR)wParam == c)
                goto found;
        }
        // now try w/ upper case
        if (iswlower((TCHAR)wParam)) {
            wParam = (LPARAM)towupper((TCHAR)wParam);
            while ((c = *lpTable1++) > 0) {
                if ((TCHAR)wParam == c)
                    goto found;
            }
        }
        //DPF1("Char '%c' not in table\r\n", wParam);
        MessageBeep(MB_OK);
        return TRUE;
found:
        //DPF1("Found char '%c' in table\r\n", wParam);
        break;
    default:
        break;
    }                                                                                   // of switch
    return CallWindowProc(oldEditCtlProc, hwnd, message, wParam, lParam);
}
Example #22
0
//////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers
void CMainFrame::OnEditPaste() 
{
	CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); 

	if (NewDoc)
	{
		if (OpenClipboard())
		{
			HANDLE hData=NULL;
			
			if (hData = GetClipboardData(((CDemoApp*)AfxGetApp())->GetCF())){ //custom CxImage object
				CxImage *newima = new CxImage();
				DWORD dwSize = GlobalSize(hData);
				if (dwSize) {
					BYTE *lpVoid = (BYTE *)GlobalLock(hData);
					newima->UnDump(lpVoid);
					GlobalUnlock(lpVoid);
				}
				NewDoc->image = newima;
			} else if (hData = GetClipboardData(CF_DIB)){ // check if bitmap
				CxImage *newima = new CxImage();
				newima->CreateFromHANDLE(hData);
				NewDoc->image = newima;
			} else  {		
#if CXIMAGE_SUPPORT_WMF
				if (hData = GetClipboardData(CF_ENHMETAFILE)) //check if metafile
				{
					HENHMETAFILE hMeta = (HENHMETAFILE)hData;
					ENHMETAHEADER emh;
					GetEnhMetaFileHeader(hMeta, sizeof(emh), &emh); 

					int	cx,cy;
					cx = (int)((emh.rclBounds.right - emh.rclBounds.left)/2.54);
					cy = (int)((emh.rclBounds.bottom - emh.rclBounds.top)/2.54);

					HDC hDC0 = ::GetDC(0); // screen dc
					HBITMAP hBitmap = CreateCompatibleBitmap(hDC0, cx, cy);
					HDC	hDC = CreateCompatibleDC(hDC0);	// memory dc compatible with screen
					::ReleaseDC(0, hDC0);	// don't need anymore. get rid of it.

					if (hDC && hBitmap){

						RECT rc = {0,0,cx,cy};
						int bpp = ::GetDeviceCaps(hDC, BITSPIXEL);

						HBITMAP hBitmapOld = (HBITMAP)SelectObject(hDC, hBitmap);

						// paint the background
						DWORD	dwBack = RGB(255, 255, 255); //GetSysColor(COLOR_WINDOW);
						DWORD OldColor = SetBkColor(hDC, dwBack);
						ExtTextOut(hDC, 0, 0, ETO_OPAQUE, &rc, NULL, 0, NULL);
						SetBkColor(hDC, OldColor);

						// Play the Metafile into Memory DC
						BOOL bRet = PlayEnhMetaFile(hDC, hMeta,	&rc);

						SelectObject(hDC, hBitmapOld);

						CxImage *newima = new CxImage();
						if(bRet && newima->Create(cx, cy, bpp, CXIMAGE_FORMAT_WMF)){
							
							bRet = GetDIBits(hDC, hBitmap, 0,	(UINT)cy, newima->GetBits(),
								             (LPBITMAPINFO)newima->GetDIB(), DIB_RGB_COLORS);

							NewDoc->image = newima;
						}
						else
						{
							delete newima;
						}
					}
					if (hBitmap) DeleteObject(hBitmap);
					if (hDC) DeleteDC(hDC);
				}
#endif
			}
		}

		CloseClipboard();

		CString s;
		s.Format(_T("Clipboard Image %d"),((CDemoApp*)AfxGetApp())->m_nDocCount++);
		NewDoc->SetTitle(s);
		NewDoc->UpdateAllViews(0,WM_USER_NEWIMAGE);
		NewDoc->UpdateStatusBar();
	}
}
Example #23
0
void CAnsiWnd::OnLButtonUp(UINT nFlags, CPoint point) 
{
    if ( m_bSelected ) {
        ReleaseCapture();
        m_bSelected = FALSE;
        InvalidateRect(NULL, FALSE);
        UpdateWindow();
        pDoc->m_bFrozen = FALSE;

        // Well, start forming text for Clipboard
        CString ResultStr;

        // Good, getting reall numbers of strings
        int ScrollIndex = GetScrollPos(SB_VERT)+1;
        ASSERT(m_nStartSelectY>=0);
        POSITION pos = m_strList.FindIndex(ScrollIndex+m_nStartSelectY);
        ASSERT(pos);
        int i = m_nStartSelectY;
        do { 
            CString tmpStr = m_strList.GetAt(pos);
            char* ptr = (LPSTR)(LPCSTR)tmpStr;
            int count = 0;
            if (i == m_nStartSelectY && i == m_nEndSelectY) {
                // Skip to StartX character
                while ( count < m_nStartSelectX && *ptr){
                    if ( *ptr == 0x1B ){
                        ptr = SkipAnsi(ptr);
                    }
                    else {
                        count++;
                        ptr++;
                    }
                } 
                
            }
            // characters skipped now copy nessesary info to string
            do {
                if ( *ptr == '\n' /*|| *ptr == '\r'*/ ) {
                    ptr++;
                    continue;
                }
                if ( *ptr == 0x1B ) {
                    ptr = SkipAnsi(ptr);
                    continue;
                } //* en: do not even try
                if ( /*i == m_nEndSelectY &&*/ count >= m_nEndSelectX ) 
                    break;
                ResultStr+= *ptr++;
                count++;
            } while ( *ptr );
            if ( i != m_nEndSelectY ) 
                ResultStr +="\r\n";
            i++;
            pos = m_strList.FindIndex(ScrollIndex+i);
        } while ( i<=m_nEndSelectY && pos );
        // Put to clipboard
		if (strlen(ResultStr) != 0)
		{
			VERIFY(OpenClipboard());

			VERIFY(EmptyClipboard());

			LCID lc = GetUserDefaultLCID();
			HANDLE hData = GlobalAlloc(GMEM_ZEROINIT, sizeof(lc) );
			LCID* pLc = (LCID*)GlobalLock(hData);
			*pLc = lc;
			GlobalUnlock(hData);
			SetClipboardData(CF_LOCALE, hData);
			hData = GlobalAlloc(GMEM_ZEROINIT, ResultStr.GetLength()+1 );
			char* buff = (char*)GlobalLock(hData);
			strcpy (buff, (LPSTR)(LPCSTR)ResultStr);
			GlobalUnlock(hData);
			SetClipboardData(CF_TEXT, hData);
			CloseClipboard();
		}
    }
	CWnd::OnLButtonUp(nFlags, point);
}
Example #24
0
void COpenDlg::OnOK()
{
	UpdateData(TRUE);

	bool bUDiffOnClipboard = false;
	if (OpenClipboard())
	{
		UINT enumFormat = 0;
		do 
		{
			if (enumFormat == m_cFormat)
			{
				bUDiffOnClipboard = true;
			}
		} while((enumFormat = EnumClipboardFormats(enumFormat))!=0);
		CloseClipboard();
	}

	if (GetDlgItem(IDC_BASEFILEEDIT)->IsWindowEnabled())
	{
		m_sUnifiedDiffFile.Empty();
		m_sPatchDirectory.Empty();
	}
	else
	{
		m_sBaseFile.Empty();
		m_sYourFile.Empty();
		m_sTheirFile.Empty();
	}
	UpdateData(FALSE);
	CString sFile;
	if (!m_sUnifiedDiffFile.IsEmpty())
		if (!PathFileExists(m_sUnifiedDiffFile))
			sFile = m_sUnifiedDiffFile;
	if (!m_sPatchDirectory.IsEmpty())
		if (!PathFileExists(m_sPatchDirectory))
			sFile = m_sPatchDirectory;
	if (!m_sBaseFile.IsEmpty())
		if (!PathFileExists(m_sBaseFile))
			sFile = m_sBaseFile;
	if (!m_sYourFile.IsEmpty())
		if (!PathFileExists(m_sYourFile))
			sFile = m_sYourFile;
	if (!m_sTheirFile.IsEmpty())
		if (!PathFileExists(m_sTheirFile))
			sFile = m_sTheirFile;

	if (bUDiffOnClipboard && m_bFromClipboard)
	{
		if (OpenClipboard()) 
		{ 
			HGLOBAL hglb = GetClipboardData(m_cFormat); 
			LPCSTR lpstr = (LPCSTR)GlobalLock(hglb); 

			DWORD len = GetTempPath(0, NULL);
			TCHAR * path = new TCHAR[len+1];
			TCHAR * tempF = new TCHAR[len+100];
			GetTempPath (len+1, path);
			GetTempFileName (path, TEXT("tsm"), 0, tempF);
			CString sTempFile = CString(tempF);
			delete [] path;
			delete [] tempF;

			FILE * outFile;
			size_t patchlen = strlen(lpstr);
			_tfopen_s(&outFile, sTempFile, _T("wb"));
			if(outFile)
			{
				size_t size = fwrite(lpstr, sizeof(char), patchlen, outFile);
				if (size < patchlen)
					bUDiffOnClipboard = false;
				else
				{
					m_sUnifiedDiffFile = sTempFile;
					UpdateData(FALSE);
					sFile.Empty();
				}
				fclose(outFile);
			}
			GlobalUnlock(hglb); 
			CloseClipboard(); 
		} 

	}

	if (!sFile.IsEmpty())
	{
		CString sErr;
		sErr.Format(IDS_ERR_PATCH_INVALIDPATCHFILE, (LPCTSTR)sFile);
		MessageBox(sErr, NULL, MB_ICONERROR);
		return;
	}
	CDialog::OnOK();
}
Example #25
0
static int editTextField(float x, float y, char* editString, bool isFocused, int editType, unsigned int maxLength = 32)
{
	//r3dColor clr(0, 86, 159);
  r3dColor clr(156, 156, 156);

  char stars[512];
  for(size_t i=0; i<strlen(editString); i++)
    stars[i] = '*';
  stars[strlen(editString)] = 0;
     
  char* msg = (editType == 1) ? stars : editString;
  g_font1->PrintF(x, y + ((editType == 1) ? 4 : 0), clr, "%s", msg); // '*' in font is way up, adjust it to center
  if(!isFocused)
    return 0;
    
  // blinking 
  static float blinkRate = (float)GetCaretBlinkTime() / 1000.0f;
  static float nextBlink = r3dGetTime();
  static int   caretOn   = 0;
  
  if(r3dGetTime() > nextBlink) {
    nextBlink += blinkRate;
    caretOn = !caretOn;
  }

  // by some weird reason GetTextExtent ignoring last spaces in string.
  char sizemsg[512];
  sprintf(sizemsg, "%s.", msg);
  SIZE ts1 = GetTextExtent(g_font1, sizemsg);
  SIZE ts2 = GetTextExtent(g_font1, ".");
  if(caretOn) {
    r3dDrawBox2D(x + (float)(ts1.cx - ts2.cx), y+2, 1, 16, r3dColor(0, 0, 0));
  }

  // some wierd Control-V logic, as we can't detect it - it's eated inside WMKEYDOWN
  static bool btnVPressed = false;
  if(::GetFocus() == win::hWnd && (GetKeyState('V') & 0x80) && !btnVPressed) {
    btnVPressed = true;
    if(GetKeyState(VK_CONTROL) & 0x80) {
      if(OpenClipboard(NULL)) 
      {
        HANDLE clip = GetClipboardData(CF_TEXT);
        const char* ptr = (LPSTR)GlobalLock(clip);
        if(ptr)
        {
          std::string text = ptr;
          text = trim(text);
          r3dscpy_s(editString, maxLength, text.c_str());
        }
        GlobalUnlock(clip);
        CloseClipboard();
      }
    }
  }
  else btnVPressed = false;
  
  // do input
  int ch = win32_getch();
  if(ch == 0)
    return 0;
    
  // backspace
  if(ch == 8 && *editString != 0)
    editString[strlen(editString)-1] = 0;

  // check for max length
  if(strlen(editString) >= maxLength)
    return 0;
    
  if(editType == 2)
  {
    // special case for serial entry
    int len = strlen(editString);
    if(len >= 19) // max length
      return 0;
    if(len == 4 || len == 9 || len == 14) { // '-' in serial
      if(ch == '-') {
        sprintf(editString + strlen(editString), "%c", ch);
      }
      return 0;
    }
    if(ch >= '0' && ch <= '9')
      sprintf(editString + strlen(editString), "%c", ch);
    else if(ch >= 'a' && ch <= 'z')
      sprintf(editString + strlen(editString), "%c", ch - 0x20);
    else if(ch >= 'A' && ch <= 'Z')
      sprintf(editString + strlen(editString), "%c", ch);
    else if(ch == 9 || ch == 13)
      return ch;

    return 0;
  }
    
  // normal key
  if(ch >= 0x20 && ch < 0x80) {
    sprintf(editString + strlen(editString), "%c", ch);
  }
  
  return ch;
}
//*********************增加的函数**********************************************************
//考贝屏幕,这段代码是拿来主义 呵呵
HBITMAP CCatchScreenDlg::CopyScreenToBitmap(LPRECT lpRect,BOOL bSave)
//lpRect 代表选定区域
{
	HDC       hScrDC, hMemDC;      
	// 屏幕和内存设备描述表
	HBITMAP    hBitmap, hOldBitmap;   
	// 位图句柄
	int       nX, nY, nX2, nY2;      
	// 选定区域坐标
	int       nWidth, nHeight;
	
	// 确保选定区域不为空矩形
	if (IsRectEmpty(lpRect))
		return NULL;
	//为屏幕创建设备描述表
	hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);

	//为屏幕设备描述表创建兼容的内存设备描述表
	hMemDC = CreateCompatibleDC(hScrDC);
	// 获得选定区域坐标
	nX = lpRect->left;
	nY = lpRect->top;
	nX2 = lpRect->right;
	nY2 = lpRect->bottom;

	//确保选定区域是可见的
	if (nX < 0)
		nX = 0;
	if (nY < 0)
		nY = 0;
	if (nX2 > m_xScreen)
		nX2 = m_xScreen;
	if (nY2 > m_yScreen)
		nY2 = m_yScreen;
	nWidth = nX2 - nX;
	nHeight = nY2 - nY;
	// 创建一个与屏幕设备描述表兼容的位图
	hBitmap = CreateCompatibleBitmap
		(hScrDC, nWidth, nHeight);
	// 把新位图选到内存设备描述表中
	hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
	// 把屏幕设备描述表拷贝到内存设备描述表中
	if(bSave)
	{
		//创建军兼容DC,当bSave为中时把开始保存的全屏位图,按截取矩形大小保存
		CDC dcCompatible;
		dcCompatible.CreateCompatibleDC(CDC::FromHandle(hMemDC));
		dcCompatible.SelectObject(m_pBitmap);
        
		BitBlt(hMemDC, 0, 0, nWidth, nHeight,
			dcCompatible, nX, nY, SRCCOPY);

	}
	else
	{
		BitBlt(hMemDC, 0, 0, nWidth, nHeight,
			hScrDC, nX, nY, SRCCOPY);
	}

	hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
	//得到屏幕位图的句柄
	//清除 
	DeleteDC(hScrDC);
	DeleteDC(hMemDC);
	
	if(bSave)
	{
				
		if (OpenClipboard()) 
		{
        //清空剪贴板
        EmptyClipboard();
        //把屏幕内容粘贴到剪贴板上,
        //hBitmap 为刚才的屏幕位图句柄
        SetClipboardData(CF_BITMAP, hBitmap);
        //关闭剪贴板
        CloseClipboard();
      }
	}
	// 返回位图句柄

	return hBitmap;
}
Example #27
0
static int wf_cliprdr_server_format_data_request(CliprdrClientContext* context, CLIPRDR_FORMAT_DATA_REQUEST* formatDataRequest)
{
	int size = 0;
	char* buff = NULL;
	char* globlemem = NULL;
	HANDLE hClipdata = NULL;
	UINT32 requestedFormatId;
	CLIPRDR_FORMAT_DATA_RESPONSE response;
	wfClipboard* clipboard = (wfClipboard*) context->custom;

	requestedFormatId = formatDataRequest->requestedFormatId;

	if (requestedFormatId == RegisterClipboardFormatW(_T("FileGroupDescriptorW")))
	{
		int len;
		int i;
		WCHAR* wFileName;
		unsigned int uSize;
		HRESULT result;
		LPDATAOBJECT dataObj;
		FORMATETC format_etc;
		STGMEDIUM stg_medium;
		DROPFILES* dropFiles;

		result = OleGetClipboard(&dataObj);

		if (FAILED(result))
			return -1;

		ZeroMemory(&format_etc, sizeof(FORMATETC));
		ZeroMemory(&stg_medium, sizeof(STGMEDIUM));

		/* try to get FileGroupDescriptorW struct from OLE */
		format_etc.cfFormat = requestedFormatId;
		format_etc.tymed = TYMED_HGLOBAL;
		format_etc.dwAspect = 1;
		format_etc.lindex = -1;
		format_etc.ptd = 0;

		result = IDataObject_GetData(dataObj, &format_etc, &stg_medium);

		if (SUCCEEDED(result))
		{
			DEBUG_CLIPRDR("Got FileGroupDescriptorW.");
			globlemem = (char*) GlobalLock(stg_medium.hGlobal);
			uSize = GlobalSize(stg_medium.hGlobal);
			size = uSize;
			buff = (char*) malloc(uSize);
			CopyMemory(buff, globlemem, uSize);
			GlobalUnlock(stg_medium.hGlobal);

			ReleaseStgMedium(&stg_medium);

			clear_file_array(clipboard);
		}
		else
		{
			/* get DROPFILES struct from OLE */
			format_etc.cfFormat = CF_HDROP;
			format_etc.tymed = TYMED_HGLOBAL;
			format_etc.dwAspect = 1;
			format_etc.lindex = -1;

			result = IDataObject_GetData(dataObj, &format_etc, &stg_medium);

			if (FAILED(result)) {
				DEBUG_CLIPRDR("dataObj->GetData failed.");
			}

			globlemem = (char*) GlobalLock(stg_medium.hGlobal);

			if (!globlemem)
			{
				GlobalUnlock(stg_medium.hGlobal);

				ReleaseStgMedium(&stg_medium);
				clipboard->nFiles = 0;

				goto exit;
			}
			uSize = GlobalSize(stg_medium.hGlobal);

			dropFiles = (DROPFILES*) malloc(uSize);
			memcpy(dropFiles, globlemem, uSize);

			GlobalUnlock(stg_medium.hGlobal);

			ReleaseStgMedium(&stg_medium);

			clear_file_array(clipboard);

			if (dropFiles->fWide)
			{
				WCHAR* p;
				int str_len;
				int offset;
				int pathLen;

				/* dropFiles contains file names */
				for (wFileName = (WCHAR*)((char*)dropFiles + dropFiles->pFiles); (len = wcslen(wFileName)) > 0; wFileName += len + 1)
				{
					/* get path name */
					str_len = wcslen(wFileName);
					offset = str_len;
					/* find the last '\' in full file name */
					for (p = wFileName + offset; *p != L'\\'; p--)
					{
						;
					}
					p += 1;
					pathLen = wcslen(wFileName) - wcslen(p);

					wf_cliprdr_add_to_file_arrays(clipboard, wFileName, pathLen);

					if ((clipboard->fileDescriptor[clipboard->nFiles - 1]->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
					{
						/* this is a directory */
						wf_cliprdr_traverse_directory(clipboard, wFileName, pathLen);
					}
				}
			}
			else
			{
				char* p;

				for (p = (char*)((char*)dropFiles + dropFiles->pFiles); (len = strlen(p)) > 0; p += len + 1, clipboard->nFiles++)
				{
					int cchWideChar;

					cchWideChar = MultiByteToWideChar(CP_ACP, MB_COMPOSITE, p, len, NULL, 0);
					clipboard->file_names[clipboard->nFiles] = (LPWSTR) malloc(cchWideChar * 2);
					MultiByteToWideChar(CP_ACP, MB_COMPOSITE, p, len, clipboard->file_names[clipboard->nFiles], cchWideChar);

					map_ensure_capacity(clipboard);
				}
			}

exit:
			size = 4 + clipboard->nFiles * sizeof(FILEDESCRIPTORW);
			buff = (char*) malloc(size);

			*((UINT32*) buff) = clipboard->nFiles;

			for (i = 0; i < clipboard->nFiles; i++)
			{
				if (clipboard->fileDescriptor[i])
				{
					memcpy(buff + 4 + i * sizeof(FILEDESCRIPTORW), clipboard->fileDescriptor[i], sizeof(FILEDESCRIPTORW));
				}
			}
		}

		IDataObject_Release(dataObj);
	}
	else
	{
		if (!OpenClipboard(clipboard->hwnd))
			return -1;

		hClipdata = GetClipboardData(requestedFormatId);

		if (!hClipdata)
		{
			CloseClipboard();
			return -1;
		}

		globlemem = (char*) GlobalLock(hClipdata);
		size = (int) GlobalSize(hClipdata);

		buff = (char*) malloc(size);
		CopyMemory(buff, globlemem, size);

		GlobalUnlock(hClipdata);

		CloseClipboard();
	}

	ZeroMemory(&response, sizeof(CLIPRDR_FORMAT_DATA_RESPONSE));

	response.msgFlags = CB_RESPONSE_OK;
	response.dataLen = size;
	response.requestedFormatData = (BYTE*) buff;

	clipboard->context->ClientFormatDataResponse(clipboard->context, &response);

	free(buff);

	return 1;
}
Example #28
0
void
text_copy_to_clipboard(TW *tw)
{
    int size, count;
    HGLOBAL hGMem;
#ifdef WINDOWS_NO_UNICODE
    LPSTR cbuf, cp;
    HDC hdc;
    TEXTMETRIC tm;
#else
    LPWSTR cbuf, cp;
#endif
    UINT type;
    int i;

    size = tw->ScreenSize.y * (tw->ScreenSize.x + 2) + 1;
    size *= CHARSIZE;
    hGMem = GlobalAlloc(GHND | GMEM_SHARE, (DWORD)size);
#ifdef WINDOWS_NO_UNICODE
    cbuf = cp = (LPSTR)GlobalLock(hGMem);
#else
    cbuf = cp = (LPWSTR)GlobalLock(hGMem);
#endif
    if (cp == NULL)
        return;

    for (i=0; i<tw->ScreenSize.y; i++) {
        count = tw->ScreenSize.x;
        memcpy(cp, tw->ScreenBuffer + tw->ScreenSize.x*i, count*CHARSIZE);
        /* remove trailing spaces */
        for (count=count-1; count>=0; count--) {
                if (cp[count]!=' ')
                        break;
                cp[count] = '\0';
        }
        cp[++count] = '\r';
        cp[++count] = '\n';
        cp[++count] = '\0';
        cp += count;
    }
    /* Now remove completely empty trailing lines */
    while (cp >= cbuf+4) {
        if ((cp[-3] != '\n') || (cp[-4] != '\r'))
            break;
        cp -= 2;
        *cp = '\0';
    }
#ifdef WINDOWS_NO_UNICODE
    size = strlen(cbuf) + 1;
#else
    size = CHARSIZE*(wcslen(cbuf) + 1);
#endif
    GlobalUnlock(hGMem);
    hGMem = GlobalReAlloc(hGMem, (DWORD)size, GHND | GMEM_SHARE);
#ifdef WINDOWS_NO_UNICODE
    /* find out what type to put into clipboard */
    hdc = GetDC(tw->hwnd);
    SelectFont(hdc, tw->hfont);
    GetTextMetrics(hdc,(TEXTMETRIC FAR *)&tm);
    if (tm.tmCharSet == OEM_CHARSET)
        type = CF_OEMTEXT;
    else
        type = CF_TEXT;
    ReleaseDC(tw->hwnd, hdc);
#else
    type = CF_UNICODETEXT;
#endif
    /* give buffer to clipboard */
    OpenClipboard(tw->hwnd);
    EmptyClipboard();
    SetClipboardData(type, hGMem);
    CloseClipboard();
}
Example #29
0
void CPlayerPlaylistBar::OnContextMenu(CWnd* /*pWnd*/, CPoint p)
{
    LVHITTESTINFO lvhti;
    lvhti.pt = p;
    m_list.ScreenToClient(&lvhti.pt);
    m_list.SubItemHitTest(&lvhti);

    POSITION pos = FindPos(lvhti.iItem);
    //bool fSelected = (pos == m_pl.GetPos());
    bool fOnItem = !!(lvhti.flags & LVHT_ONITEM);

    CMenu m;
    m.CreatePopupMenu();

    enum {
        M_OPEN = 1, M_ADD, M_REMOVE, M_CLEAR, M_CLIPBOARD, M_SAVEAS,
        M_SORTBYNAME, M_SORTBYPATH, M_RANDOMIZE, M_SORTBYID,
        M_SHUFFLE, M_HIDEFULLSCREEN
    };

    CAppSettings& s = AfxGetAppSettings();

    m.AppendMenu(MF_STRING | (!fOnItem ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_OPEN, ResStr(IDS_PLAYLIST_OPEN));
    if (((CMainFrame*)AfxGetMainWnd())->GetPlaybackMode() == PM_CAPTURE) {
        m.AppendMenu(MF_STRING | MF_ENABLED, M_ADD, ResStr(IDS_PLAYLIST_ADD));
    }
    m.AppendMenu(MF_STRING | (/*fSelected||*/!fOnItem ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_REMOVE, ResStr(IDS_PLAYLIST_REMOVE));
    m.AppendMenu(MF_SEPARATOR);
    m.AppendMenu(MF_STRING | (!m_pl.GetCount() ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_CLEAR, ResStr(IDS_PLAYLIST_CLEAR));
    m.AppendMenu(MF_SEPARATOR);
    m.AppendMenu(MF_STRING | (!fOnItem ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_CLIPBOARD, ResStr(IDS_PLAYLIST_COPYTOCLIPBOARD));
    m.AppendMenu(MF_STRING | (!m_pl.GetCount() ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_SAVEAS, ResStr(IDS_PLAYLIST_SAVEAS));
    m.AppendMenu(MF_SEPARATOR);
    m.AppendMenu(MF_STRING | (!m_pl.GetCount() ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_SORTBYNAME, ResStr(IDS_PLAYLIST_SORTBYLABEL));
    m.AppendMenu(MF_STRING | (!m_pl.GetCount() ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_SORTBYPATH, ResStr(IDS_PLAYLIST_SORTBYPATH));
    m.AppendMenu(MF_STRING | (!m_pl.GetCount() ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_RANDOMIZE, ResStr(IDS_PLAYLIST_RANDOMIZE));
    m.AppendMenu(MF_STRING | (!m_pl.GetCount() ? (MF_DISABLED | MF_GRAYED) : MF_ENABLED), M_SORTBYID, ResStr(IDS_PLAYLIST_RESTORE));
    m.AppendMenu(MF_SEPARATOR);
    m.AppendMenu(MF_STRING | MF_ENABLED | (s.bShufflePlaylistItems ? MF_CHECKED : MF_UNCHECKED), M_SHUFFLE, ResStr(IDS_PLAYLIST_SHUFFLE));
    m.AppendMenu(MF_SEPARATOR);
    m.AppendMenu(MF_STRING | MF_ENABLED | (s.bHidePlaylistFullScreen ? MF_CHECKED : MF_UNCHECKED), M_HIDEFULLSCREEN, ResStr(IDS_PLAYLIST_HIDEFS));

    CMainFrame* pMainFrm = (CMainFrame*)AfxGetMainWnd();

    int nID = (int)m.TrackPopupMenu(TPM_LEFTBUTTON | TPM_RETURNCMD, p.x, p.y, this);
    switch (nID) {
        case M_OPEN:
            m_pl.SetPos(pos);
            m_list.Invalidate();
            pMainFrm->OpenCurPlaylistItem();
            break;
        case M_ADD:
            pMainFrm->AddCurDevToPlaylist();
            m_pl.SetPos(m_pl.GetTailPosition());
            break;
        case M_REMOVE:
            if (m_pl.RemoveAt(pos)) {
                pMainFrm->CloseMedia();
            }
            m_list.DeleteItem(lvhti.iItem);
            SavePlaylist();
            break;
        case M_CLEAR:
            if (Empty()) {
                pMainFrm->CloseMedia();
            }
            break;
        case M_SORTBYID:
            m_pl.SortById();
            SetupList();
            SavePlaylist();
            break;
        case M_SORTBYNAME:
            m_pl.SortByName();
            SetupList();
            SavePlaylist();
            break;
        case M_SORTBYPATH:
            m_pl.SortByPath();
            SetupList();
            SavePlaylist();
            break;
        case M_RANDOMIZE:
            m_pl.Randomize();
            SetupList();
            SavePlaylist();
            break;
        case M_CLIPBOARD:
            if (OpenClipboard() && EmptyClipboard()) {
                CString str;

                CPlaylistItem& pli = m_pl.GetAt(pos);
                POSITION pos2 = pli.m_fns.GetHeadPosition();
                while (pos2) {
                    str += _T("\r\n") + pli.m_fns.GetNext(pos2);
                }
                str.Trim();

                if (HGLOBAL h = GlobalAlloc(GMEM_MOVEABLE, (str.GetLength() + 1) * sizeof(TCHAR))) {
                    if (TCHAR* cp = (TCHAR*)GlobalLock(h)) {
                        _tcscpy_s(cp, str.GetLength() + 1, str);
                        GlobalUnlock(h);
                        SetClipboardData(CF_UNICODETEXT, h);
                    }
                }
                CloseClipboard();
            }
            break;
        case M_SAVEAS: {
            CSaveTextFileDialog fd(
                CTextFile::ASCII, NULL, NULL,
                _T("Media Player Classic playlist (*.mpcpl)|*.mpcpl|Playlist (*.pls)|*.pls|Winamp playlist (*.m3u)|*.m3u|Windows Media playlist (*.asx)|*.asx||"),
                this);

            if (fd.DoModal() != IDOK) {
                break;
            }

            CTextFile::enc encoding = (CTextFile::enc)fd.GetEncoding();
            if (encoding == CTextFile::ASCII) {
                encoding = CTextFile::ANSI;
            }

            int idx = fd.m_pOFN->nFilterIndex;

            CPath path(fd.GetPathName());

            switch (idx) {
                case 1:
                    path.AddExtension(_T(".mpcpl"));
                    break;
                case 2:
                    path.AddExtension(_T(".pls"));
                    break;
                case 3:
                    path.AddExtension(_T(".m3u"));
                    break;
                case 4:
                    path.AddExtension(_T(".asx"));
                    break;
                default:
                    break;
            }

            bool fRemovePath = true;

            CPath p(path);
            p.RemoveFileSpec();
            CString base = (LPCTSTR)p;

            pos = m_pl.GetHeadPosition();
            while (pos && fRemovePath) {
                CPlaylistItem& pli = m_pl.GetNext(pos);

                if (pli.m_type != CPlaylistItem::file) {
                    fRemovePath = false;
                } else {
                    POSITION pos;

                    pos = pli.m_fns.GetHeadPosition();
                    while (pos && fRemovePath) {
                        CString fn = pli.m_fns.GetNext(pos);

                        CPath p(fn);
                        p.RemoveFileSpec();
                        if (base != (LPCTSTR)p) {
                            fRemovePath = false;
                        }
                    }

                    pos = pli.m_subs.GetHeadPosition();
                    while (pos && fRemovePath) {
                        CString fn = pli.m_subs.GetNext(pos);

                        CPath p(fn);
                        p.RemoveFileSpec();
                        if (base != (LPCTSTR)p) {
                            fRemovePath = false;
                        }
                    }
                }
            }

            if (idx == 1) {
                SaveMPCPlayList(path, encoding, fRemovePath);
                break;
            }

            CTextFile f;
            if (!f.Save(path, encoding)) {
                break;
            }

            if (idx == 2) {
                f.WriteString(_T("[playlist]\n"));
            } else if (idx == 4) {
                f.WriteString(_T("<ASX version = \"3.0\">\n"));
            }

            pos = m_pl.GetHeadPosition();
            CString str;
            int i;
            for (i = 0; pos; i++) {
                CPlaylistItem& pli = m_pl.GetNext(pos);

                if (pli.m_type != CPlaylistItem::file) {
                    continue;
                }

                CString fn = pli.m_fns.GetHead();

                /*
                            if (fRemovePath)
                            {
                                CPath p(path);
                                p.StripPath();
                                fn = (LPCTSTR)p;
                            }
                */

                switch (idx) {
                    case 2:
                        str.Format(_T("File%d=%s\n"), i + 1, fn);
                        break;
                    case 3:
                        str.Format(_T("%s\n"), fn);
                        break;
                    case 4:
                        str.Format(_T("<Entry><Ref href = \"%s\"/></Entry>\n"), fn);
                        break;
                    default:
                        break;
                }
                f.WriteString(str);
            }

            if (idx == 2) {
                str.Format(_T("NumberOfEntries=%d\n"), i);
                f.WriteString(str);
                f.WriteString(_T("Version=2\n"));
            } else if (idx == 4) {
                f.WriteString(_T("</ASX>\n"));
            }
        }
        break;
        case M_SHUFFLE:
            s.bShufflePlaylistItems = !s.bShufflePlaylistItems;
            break;
        case M_HIDEFULLSCREEN:
            s.bHidePlaylistFullScreen = !s.bHidePlaylistFullScreen;
            break;
        default:
            break;
    }
}
Example #30
0
int win_clipboard_to_bmp(WILLUSBITMAP *bmp,FILE *out)

    {
    static char *funcname="win_clipboard_to_bmp";
    HBITMAP hbitmap;
    HWND    dtwin;
    HDC     hDC,hMemDC;

    dtwin=GetDesktopWindow();
    if (!OpenClipboard(dtwin))
        {
        nprintf(out,"win_clipboard_to_bmp:  Error opening clipboard.\n");
        return(-1);
        }
    hbitmap=(HBITMAP)GetClipboardData(CF_BITMAP);
    if (hbitmap==NULL)
        {
        nprintf(out,"win_clipboard_to_bmp:  Clipboard does not have a bitmap.\n");
        CloseClipboard();
        return(-2);
        }
    // This is kludgy, but works for 24-bit desktops
    hDC=GetDC(dtwin);
    if (hDC==NULL)
        {
        nprintf(out,"win_clipboard_to_bmp:  Could not get DC.\n");
        CloseClipboard();
        return(-3);
        }
    // Create a device context for the windows bitmap
    hMemDC=CreateCompatibleDC(hDC);
    if (hMemDC==NULL)
        {
        nprintf(out,"win_clipboard_to_bmp:  Could not create hMemDC.\n");
        // DeleteObject(hbitmap);
        ReleaseDC(dtwin,hDC);
        return(-4);
        }
    // Select the windows bitmap into the new device context
    SelectObject(hMemDC,hbitmap);
    /* Kludgey way to get BMP dims, but GetBitmapDimensionsEx() doesn't work. */
    {
    int step;
    for (step=2048,bmp->width=0;1;bmp->width+=step)
        {
        if (GetPixel(hMemDC,bmp->width,0)==CLR_INVALID)
            {
            if (step==1 || bmp->width==0)
                break;
            bmp->width -= step;
            step >>= 1;
            }
        }
    for (step=1024,bmp->height=0;1;bmp->height+=step)
        {
        if (GetPixel(hMemDC,0,bmp->height)==CLR_INVALID)
            {
            if (step==1 || bmp->height==0)
                break;
            bmp->height -= step;
            step >>= 1;
            }
        }
    }
    if (bmp->height==0 || bmp->width==0)
        {
        nprintf(out,"win_clipboard_to_bmp:  Zero sized bitmap.\n");
        DeleteDC(hMemDC);
        ReleaseDC(dtwin,hDC);
        return(-5);
        }
    bmp->bpp=24;
    bmp->type=WILLUSBITMAP_TYPE_WIN32;
    bmp_alloc(bmp);

    // Set up the device independent bitmap
    {
    BITMAPINFO         *bmi;
    willus_mem_alloc_warn((void **)&bmi,sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD),funcname,10);
    bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi->bmiHeader.biWidth = bmp->width;
    bmi->bmiHeader.biHeight = bmp->height;
    bmi->bmiHeader.biPlanes = 1;
    bmi->bmiHeader.biBitCount = 24;
    bmi->bmiHeader.biCompression = BI_RGB;
    bmi->bmiHeader.biSizeImage = 0;
    bmi->bmiHeader.biXPelsPerMeter = (int)(72.0*100./2.54);
    bmi->bmiHeader.biYPelsPerMeter = (int)(72.0*100./2.54);
    bmi->bmiHeader.biClrUsed = 0;
    bmi->bmiHeader.biClrImportant = 0;
    GetDIBits(hMemDC,hbitmap,0,bmp->height,bmp->data,bmi,DIB_RGB_COLORS);
/* Old way--pretty slow */
/*
    for (row=0;row<bmp->height;row++)
        {
        unsigned char *p;
        int col;

        p=bmp_rowptr_from_top(bmp,row);
        for (col=0;col<bmp->width;col++,p+=3)
            {
            int x;

            x=(int)GetPixel(hMemDC,col,row);
            p[0]=x&0xff;
            p[1]=(x>>8)&0xff;
            p[2]=(x>>16)&0xff;
            }
        }
*/
    willus_mem_free((double **)&bmi,funcname);
    }
    DeleteDC(hMemDC);
    ReleaseDC(dtwin,hDC);
    return(0);
    }