Пример #1
0
bool Layer::Translate( double x, double y, double z )
{
  double pos[3] = { x, y, z };
  return Translate( pos );
}
Пример #2
0
void CheckMailInbox(Account *curAcc)
{
	// internet connection handle
	// internet request handle
	HINTERNET hHTTPConnection = 0, hHTTPRequest = 0;		    

	DBVARIANT dbv;
	static char *contentType = "Content-Type: application/x-www-form-urlencoded";
	char requestBuffer[256] = "continue=https%3A%2F%2Fmail.google.com%2Fa%2F";
	char fileBuffer[_MAX_DOWN_BUFFER] = "";
	char *tail;
	char str[64];
	char temp[_MAX_DOWN_BUFFER] = "";
	unsigned long bufferLength;

	if (curAcc->IsChecking)
		return;

	curAcc->IsChecking = TRUE;

	if (!db_get_s(curAcc->hContact, "CList", "MyHandle", &dbv)) {
		mir_strcpy(curAcc->results.content, dbv.pszVal);
		db_free(&dbv);
	}
	else mir_strcpy(curAcc->results.content, curAcc->name);

	tail = strstr(curAcc->results.content, " [");
	if (tail) *tail = '\0';
	mir_strcat(curAcc->results.content, " [");

	mir_strcpy(str, curAcc->results.content);
	mir_strcat(str, Translate("Checking..."));
	mir_strcat(str, "]");

	db_set_s(curAcc->hContact, "CList", "MyHandle", str);
	// internet open handle
	HINTERNET hHTTPOpen = InternetOpenA("", INTERNET_OPEN_TYPE_PRECONFIG, "", "", 0);
	if (!hHTTPOpen) {
		mir_strcat(curAcc->results.content, Translate("Can't open Internet!"));
		goto error_handle;
	}

	if (curAcc->hosted[0]) {
		hHTTPConnection = InternetConnectA(hHTTPOpen,
			"www.google.com",
			INTERNET_DEFAULT_HTTPS_PORT,
			NULL,
			NULL,
			INTERNET_SERVICE_HTTP,
			0,
			0);

		if (!hHTTPConnection) {
			mir_strcat(curAcc->results.content, Translate("Can't reach server!"));
			goto error_handle;
		}
		mir_strcpy(str, "/a/");
		mir_strcat(str, curAcc->hosted);
		mir_strcat(str, "/LoginAction");
		hHTTPRequest = HttpOpenRequestA(hHTTPConnection, "POST", str, HTTP_VERSIONA, NULL, NULL, INTERNET_FLAG_SECURE, 0);
		mir_strcat(requestBuffer, curAcc->hosted);
		mir_strcat(requestBuffer, "%2Ffeed%2Fatom&service=mail&userName="******"&password="******"Can't send account data!"));
			goto error_handle;
		}

		InternetCloseHandle(hHTTPConnection);
		InternetCloseHandle(hHTTPRequest);
		hHTTPRequest = 0;
	}

	hHTTPConnection = InternetConnectA(hHTTPOpen, "mail.google.com", INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	if (!hHTTPConnection) {
		mir_strcat(curAcc->results.content, Translate("Can't reach server!"));
		goto error_handle;
	}
	if (curAcc->hosted[0]) {
		mir_strcpy(str, "/a/");
		mir_strcat(str, curAcc->hosted);
		mir_strcat(str, "/feed/atom");
	}
	else mir_strcpy(str, "/mail/feed/atom");

	hHTTPRequest = HttpOpenRequest(hHTTPConnection, _T("GET"), _A2T(str), NULL, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, 0);
	InternetSetOption(hHTTPRequest, INTERNET_OPTION_USERNAME, _A2T(curAcc->name), (int)mir_strlen(curAcc->name) + 1);
	InternetSetOption(hHTTPRequest, INTERNET_OPTION_PASSWORD, _A2T(curAcc->pass), (int)mir_strlen(curAcc->pass) + 1);
	if (!HttpSendRequest(hHTTPRequest, NULL, 0, NULL, 0)) {
		mir_strcat(curAcc->results.content, Translate("Can't get RSS feed!"));
		goto error_handle;
	}
	while (InternetReadFile(hHTTPRequest, temp, _MAX_DOWN_BUFFER, &bufferLength) && bufferLength > 0) {
		temp[bufferLength] = '\0';
		mir_strcat(fileBuffer, temp);
	}

	fileBuffer[_MAX_DOWN_BUFFER - 1] = '\0';
	curAcc->results_num = ParsePage(fileBuffer, &curAcc->results);
	if (curAcc->results_num == -1) {
		mir_strcat(curAcc->results.content, Translate("Wrong name or password!"));
		goto error_handle;
	}
	InternetCloseHandle(hHTTPOpen);
	InternetCloseHandle(hHTTPConnection);
	InternetCloseHandle(hHTTPRequest);

	mir_strcat(curAcc->results.content, _itoa(curAcc->results_num, str, 10));
	mir_strcat(curAcc->results.content, "]");

	curAcc->IsChecking = FALSE;
	return;

error_handle:
	curAcc->results_num = -1;
	InternetCloseHandle(hHTTPOpen);
	InternetCloseHandle(hHTTPConnection);
	InternetCloseHandle(hHTTPRequest);

	mir_strcat(curAcc->results.content, "]");

	curAcc->IsChecking = FALSE;
}
Пример #3
0
INT_PTR CALLBACK DlgProcYAMNBadConnection(HWND hDlg,UINT msg,WPARAM wParam,LPARAM lParam)
{
	switch(msg)
	{
		case WM_INITDIALOG:
		{
			BOOL ShowPopup,ShowMsg,ShowIco;
			HACCOUNT ActualAccount;
			DWORD  ErrorCode;
			char* TitleStrA;
			char *Message1A=NULL;
			TCHAR *Message1W=NULL;
			POPUPDATAT BadConnectPopup;

			ActualAccount=((struct BadConnectionParam *)lParam)->account;
			ErrorCode=((struct BadConnectionParam *)lParam)->errcode;
#ifdef DEBUG_SYNCHRO
			DebugLog(SynchroFile,"BadConnect:ActualAccountSO-read wait\n");
#endif
			if (WAIT_OBJECT_0 != WaitToReadFcn(ActualAccount->AccountAccessSO))
			{
#ifdef DEBUG_SYNCHRO
				DebugLog(SynchroFile,"BadConnect:ActualAccountSO-read wait failed\n");
#endif
				return FALSE;
			}
#ifdef DEBUG_SYNCHRO
			DebugLog(SynchroFile,"BadConnect:ActualAccountSO-read enter\n");
#endif
			int size = (int)(strlen(ActualAccount->Name)+strlen(Translate(BADCONNECTTITLE)));
			TitleStrA = new char[size];
			mir_snprintf(TitleStrA, size, Translate(BADCONNECTTITLE), ActualAccount->Name);

			ShowPopup=ActualAccount->BadConnectN.Flags & YAMN_ACC_POP;
			ShowMsg=ActualAccount->BadConnectN.Flags & YAMN_ACC_MSG;
			ShowIco=ActualAccount->BadConnectN.Flags & YAMN_ACC_ICO;

			if (ShowPopup) {
				BadConnectPopup.lchIcon = g_LoadIconEx(3);
				BadConnectPopup.colorBack = ActualAccount->BadConnectN.Flags & YAMN_ACC_POPC ? ActualAccount->BadConnectN.PopupB : GetSysColor(COLOR_BTNFACE);
				BadConnectPopup.colorText = ActualAccount->BadConnectN.Flags & YAMN_ACC_POPC ? ActualAccount->BadConnectN.PopupT : GetSysColor(COLOR_WINDOWTEXT);
				BadConnectPopup.iSeconds = ActualAccount->BadConnectN.PopupTime;

				BadConnectPopup.PluginWindowProc = BadConnectPopupProc;
				BadConnectPopup.PluginData = ActualAccount;
				lstrcpyn(BadConnectPopup.lptzContactName, _A2T(ActualAccount->Name), SIZEOF(BadConnectPopup.lptzContactName));
			}

			if (ActualAccount->Plugin->Fcn != NULL && ActualAccount->Plugin->Fcn->GetErrorStringWFcnPtr != NULL) {
				Message1W = ActualAccount->Plugin->Fcn->GetErrorStringWFcnPtr(ErrorCode);
				SetDlgItemText(hDlg,IDC_STATICMSG,Message1W);
				lstrcpyn(BadConnectPopup.lptzText,Message1W,sizeof(BadConnectPopup.lptzText));
				if (ShowPopup)
					PUAddPopupT(&BadConnectPopup);
			}
			else if (ActualAccount->Plugin->Fcn != NULL && ActualAccount->Plugin->Fcn->GetErrorStringAFcnPtr != NULL)
			{
				Message1W=ActualAccount->Plugin->Fcn->GetErrorStringWFcnPtr(ErrorCode);
				SetDlgItemText(hDlg,IDC_STATICMSG,Message1W);
				lstrcpyn(BadConnectPopup.lptzText,Message1W,sizeof(BadConnectPopup.lptzText));
				if (ShowPopup)
					PUAddPopupT(&BadConnectPopup);
			}
			else
			{
				Message1W=TranslateT("Unknown error");
				SetDlgItemText(hDlg,IDC_STATICMSG,Message1W);
				lstrcpyn(BadConnectPopup.lptzText,Message1W,sizeof(BadConnectPopup.lptzText));
				if (ShowPopup)
					PUAddPopupT(&BadConnectPopup);
			}

			if (!ShowMsg && !ShowIco)
				DestroyWindow(hDlg);
#ifdef DEBUG_SYNCHRO
			DebugLog(SynchroFile,"BadConnect:ActualAccountSO-read done\n");
#endif
			ReadDoneFcn(ActualAccount->AccountAccessSO);

			SetWindowTextA(hDlg, TitleStrA);
			delete[] TitleStrA;
			if (Message1A != NULL)
				delete[] Message1A;
			if (ActualAccount->Plugin->Fcn != NULL && ActualAccount->Plugin->Fcn->DeleteErrorStringFcnPtr != NULL && Message1A != NULL)
				ActualAccount->Plugin->Fcn->DeleteErrorStringFcnPtr(Message1A);
			if (ActualAccount->Plugin->Fcn != NULL && ActualAccount->Plugin->Fcn->DeleteErrorStringFcnPtr != NULL && Message1W != NULL)
				ActualAccount->Plugin->Fcn->DeleteErrorStringFcnPtr(Message1W);
			return 0;
		}
		case WM_DESTROY:
		{
			NOTIFYICONDATA nid;

			ZeroMemory(&nid,sizeof(NOTIFYICONDATA));
			nid.cbSize=sizeof(NOTIFYICONDATA);
			nid.hWnd=hDlg;
			nid.uID=0;
			Shell_NotifyIcon(NIM_DELETE,&nid);
			PostQuitMessage(0);
			break;
		}
		case WM_YAMN_NOTIFYICON:
			switch (lParam)
			{
				case WM_LBUTTONDBLCLK:
				          ShowWindow(hDlg,SW_SHOWNORMAL);
				          SetForegroundWindow(hDlg);
				          break;
			}
			return 0;
		case WM_CHAR:
			switch((TCHAR)wParam)
			{
				case 27:
				case 13:
					DestroyWindow(hDlg);
					break;
			}
			break;
		case WM_SYSCOMMAND:
			switch(wParam)
			{
				case SC_CLOSE:
					DestroyWindow(hDlg);
					break;
			}
		case WM_COMMAND:
		{
			WORD wNotifyCode = HIWORD(wParam);
			switch(LOWORD(wParam))
			{
				case IDC_BTNOK:
					DestroyWindow(hDlg);
					break;
			}
			break;
		}
	}
	return 0;
}
Пример #4
0
// Note: Once the eval graph is opened, this window-proc lives forever; een closing the
// eval-graph window merely hides it. On opening we re-initialize it, though, so it could
// as well hae been destroyed. While it is open it processes the REFRESH_GRAPH commands.
LRESULT CALLBACK EvalGraphProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam )
{
    static SnapData sd;

    PAINTSTRUCT stPS;
    HDC hDC;

    switch (message) {
    case WM_INITDIALOG:
        Translate(hDlg, DLG_EvalGraph);
        if( evalGraphDialog == NULL ) {
            evalGraphDialog = hDlg;

            RestoreWindowPlacement( hDlg, &wpEvalGraph ); /* Restore window placement */
        }

        return FALSE;

    case WM_COMMAND:
        switch (LOWORD(wParam)) {
        case IDOK:
          EndDialog(hDlg, TRUE);
          return TRUE;

        case IDCANCEL:
          EndDialog(hDlg, FALSE);
          return TRUE;

        default:
          break;
        }

        break;

    case WM_ERASEBKGND:
        return TRUE;

    case WM_PAINT:
        hDC = BeginPaint( hDlg, &stPS );
        DisplayEvalGraph( hDlg, hDC );
        EndPaint( hDlg, &stPS );
        break;

    case WM_REFRESH_GRAPH:
        hDC = GetDC( hDlg );
        DisplayEvalGraph( hDlg, hDC );
        ReleaseDC( hDlg, hDC );
        break;

    case WM_LBUTTONDOWN:
        if( wParam == 0 || wParam == MK_LBUTTON ) {
            int index = GetMoveIndexFromPoint( LOWORD(lParam), HIWORD(lParam) );

            if( index >= 0 && index < currLast ) {
                ToNrEvent( index + 1 );
            }
        }
        return TRUE;

    case WM_SIZE:
        InvalidateRect( hDlg, NULL, FALSE );
        break;

    case WM_GETMINMAXINFO:
        {
            MINMAXINFO * mmi = (MINMAXINFO *) lParam;
        
            mmi->ptMinTrackSize.x = 100;
            mmi->ptMinTrackSize.y = 100;
        }
        break;

    /* Support for captionless window */
    case WM_CLOSE:
        EvalGraphPopDown();
        break;

    case WM_ENTERSIZEMOVE:
        return OnEnterSizeMove( &sd, hDlg, wParam, lParam );

    case WM_SIZING:
        return OnSizing( &sd, hDlg, wParam, lParam );

    case WM_MOVING:
        return OnMoving( &sd, hDlg, wParam, lParam );

    case WM_EXITSIZEMOVE:
        return OnExitSizeMove( &sd, hDlg, wParam, lParam );
    }

    return FALSE;
}
Пример #5
0
CVKNewsItem* CVkProto::GetVkNewsItem(const JSONNode &jnItem, OBJLIST<CVkUserInfo> &vkUsers, bool isRepost)
{
    bool bPostLink = true;
    CVKNewsItem *vkNewsItem = new CVKNewsItem();
    if (!jnItem)
        return vkNewsItem;

    LONG iSourceId = !jnItem["source_id"] ? jnItem["owner_id"].as_int() : jnItem["source_id"].as_int();
    LONG iPostId = jnItem["post_id"].as_int();
    CMString tszText(jnItem["text"].as_mstring());
    CMString tszPopupText(tszText);

    vkNewsItem->tszType = jnItem["type"].as_mstring();
    vkNewsItem->vkUser = GetVkUserInfo(iSourceId, vkUsers);
    vkNewsItem->bIsGroup = vkNewsItem->vkUser->m_bIsGroup;
    vkNewsItem->tDate = jnItem["date"].as_int();

    if (!tszText.IsEmpty())
        tszText += _T("\n");

    debugLog(_T("CVkProto::GetVkNewsItem %d %d %s"), iSourceId, iPostId, vkNewsItem->tszType);

    if (vkNewsItem->tszType == _T("photo_tag")) {
        bPostLink = false;
        const JSONNode &jnPhotos = jnItem["photo_tags"];
        if (jnPhotos) {
            const JSONNode &jnPhotoItems = jnPhotos["items"];
            if (jnPhotoItems) {
                tszText = TranslateT("User was tagged in these photos:");
                tszPopupText = tszText + TranslateT("(photos)");
                for (auto it = jnPhotoItems.begin(); it != jnPhotoItems.end(); ++it)
                    tszText += _T("\n") + GetVkPhotoItem((*it), m_iBBCForNews);
            }
        }
    }
    else if (vkNewsItem->tszType == _T("photo") || vkNewsItem->tszType == _T("wall_photo")) {
        bPostLink = false;
        const JSONNode &jnPhotos = jnItem["photos"];
        int i = 0;
        if (jnPhotos) {
            const JSONNode &jnPhotoItems = jnPhotos["items"];
            if (jnPhotoItems) {
                tszPopupText += TranslateT("(photos)");
                for (auto it = jnPhotoItems.begin(); it != jnPhotoItems.end(); ++it) {
                    const JSONNode &jnPhotoItem = (*it);
                    tszText += GetVkPhotoItem(jnPhotoItem, m_iBBCForNews) + _T("\n");
                    if (i == 0 && vkNewsItem->tszType == _T("wall_photo")) {
                        if (jnPhotoItem["post_id"]) {
                            bPostLink = true;
                            iPostId = jnPhotoItem["post_id"].as_int();
                            break; // max 1 wall_photo when photo post_id !=0
                        }
                    }
                    i++;
                }
            }
        }
    }
    else if (vkNewsItem->tszType == _T("post") || vkNewsItem->tszType.IsEmpty()) {
        bPostLink = true;
        const JSONNode &jnRepost = jnItem["copy_history"];
        if (jnRepost) {
            CVKNewsItem *vkRepost = GetVkNewsItem((*jnRepost.begin()), vkUsers, true);
            vkRepost->tszText.Replace(_T("\n"), _T("\n\t"));
            tszText += vkRepost->tszText;
            tszText += _T("\n");

            tszPopupText += _T("\t");
            tszPopupText += vkRepost->tszPopupTitle;
            tszPopupText += _T("\n\t");
            tszPopupText += vkRepost->tszPopupText;
            vkNewsItem->bIsRepost = true;
            delete vkRepost;
        }

        const JSONNode &jnAttachments = jnItem["attachments"];
        if (jnAttachments) {
            if (!tszText.IsEmpty())
                tszText.AppendChar(_T('\n'));
            if (!tszPopupText.IsEmpty())
                tszPopupText.AppendChar(_T('\n'));
            tszPopupText += TranslateT("(attachments)");
            tszText += GetAttachmentDescr(jnAttachments, m_bUseBBCOnAttacmentsAsNews ? m_iBBCForNews : m_iBBCForAttachments);
        }
    }

    CMString tszResFormat, tszTitleFormat;

    if (!isRepost) {
        tszResFormat = Translate("News from %s\n%s");
        tszTitleFormat = Translate("News from %s");
    }
    else {
        tszResFormat = Translate("\tRepost from %s\n%s");
        tszTitleFormat = Translate("Repost from %s");
        bPostLink = false;
    }

    vkNewsItem->tszText.AppendFormat(tszResFormat,
                                     SetBBCString(vkNewsItem->vkUser->m_tszUserNick, m_iBBCForNews, vkbbcUrl,
                                             vkNewsItem->vkUser->m_tszLink), tszText);
    vkNewsItem->tszPopupTitle.AppendFormat(tszTitleFormat, vkNewsItem->vkUser->m_tszUserNick);
    vkNewsItem->tszPopupText = tszPopupText;

    vkNewsItem->tszId.AppendFormat(_T("%d_%d"), vkNewsItem->vkUser->m_UserId, iPostId);
    if (bPostLink) {
        vkNewsItem->tszLink = CMString(_T("https://vk.com/wall")) + vkNewsItem->tszId;
        vkNewsItem->tszText.AppendChar(_T('\n'));
        vkNewsItem->tszText += SetBBCString(TranslateT("Link"), m_iBBCForNews, vkbbcUrl, vkNewsItem->tszLink);
    }

    debugLog(_T("CVkProto::GetVkNewsItem %d %d <\n%s\n>"), iSourceId, iPostId, vkNewsItem->tszText);

    return vkNewsItem;
}
Пример #6
0
// main ping options 
static INT_PTR CALLBACK DlgProcOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	HWND hw;
	OPENFILENAME ofn = {0};

	switch ( msg ) {
	case WM_INITDIALOG: {
		TranslateDialogDefault( hwndDlg );

		if(!ServiceExists(MS_FONT_REGISTER)) {
			SetDlgItemText(hwndDlg, IDC_STATFS, Translate("Install the FontService plugin to change the font and font colour."));
		}

		if(ServiceExists(MS_CLIST_FRAMES_ADDFRAME)) {
			hw = GetDlgItem(hwndDlg, IDC_CHK_ATTACH);
			EnableWindow(hw, FALSE);
		}
		CheckDlgButton(hwndDlg, IDC_CHK_ATTACH, options.attach_to_clist);

		SetDlgItemInt(hwndDlg, IDC_PPM, options.ping_period, FALSE);
		SetDlgItemInt(hwndDlg, IDC_PT, options.ping_timeout, FALSE);
		CheckDlgButton(hwndDlg, IDC_CHECKPOPUP, options.show_popup);
		CheckDlgButton(hwndDlg, IDC_CHECKPOPUP2, options.show_popup2);
		CheckDlgButton(hwndDlg, IDC_CHK_BLOCK, options.block_reps);
		CheckDlgButton(hwndDlg, IDC_CHK_LOG, options.logging);
		CheckDlgButton(hwndDlg, IDC_CHK_LOGCSV, options.log_csv);
		CheckDlgButton(hwndDlg, IDC_CHK_NOTESTICON, options.no_test_icon);

		SendMessage(GetDlgItem(hwndDlg, IDC_SP_INDENT), UDM_SETRANGE, 0, (LPARAM)MAKELONG(500, 0));
		SendMessage(GetDlgItem(hwndDlg, IDC_SP_INDENT), UDM_SETPOS, 0, options.indent);
		SendMessage(GetDlgItem(hwndDlg, IDC_SP_ROWHEIGHT), UDM_SETRANGE, 0, (LPARAM)MAKELONG(500, 6));
		SendMessage(GetDlgItem(hwndDlg, IDC_SP_ROWHEIGHT), UDM_SETPOS, 0, options.row_height);

		SetDlgItemInt(hwndDlg, IDC_RPT, options.retries, FALSE);

		SetDlgItemText(hwndDlg, IDC_ED_FILENAME, options.log_filename);
		if(!options.logging) {
			hw = GetDlgItem(hwndDlg, IDC_ED_FILENAME);
			EnableWindow(hw, FALSE);
			hw = GetDlgItem(hwndDlg, IDC_BTN_LOGBROWSE);
			EnableWindow(hw, FALSE);
			hw = GetDlgItem(hwndDlg, IDC_CHK_LOGCSV);
			EnableWindow(hw, FALSE);
		}

		if(!ServiceExists( MS_POPUP_ADDPOPUP )) {
			hw = GetDlgItem(hwndDlg, IDC_CHECKPOPUP);
			EnableWindow(hw, FALSE);
			hw = GetDlgItem(hwndDlg, IDC_CHECKPOPUP2);
			EnableWindow(hw, FALSE);
			hw = GetDlgItem(hwndDlg, IDC_CHK_BLOCK);
			EnableWindow(hw, FALSE);
		} 
		return TRUE;
	}
	case WM_COMMAND:
		if ( HIWORD( wParam ) == EN_CHANGE && ( HWND )lParam == GetFocus()) {
			switch( LOWORD( wParam )) {
			case IDC_PPM:
			case IDC_PT:
			case IDC_ED_FILENAME:
			case IDC_RPT:
				SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
			}	
			break;
		}

		if (HIWORD( wParam ) == CBN_SELCHANGE) {
			SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
			break;
		}

		if ( HIWORD( wParam ) == BN_CLICKED ) {
			switch( LOWORD( wParam )) {
			case IDC_CHK_LOG:
				hw = GetDlgItem(hwndDlg, IDC_ED_FILENAME);
				EnableWindow(hw, IsDlgButtonChecked(hwndDlg, IDC_CHK_LOG));
				hw = GetDlgItem(hwndDlg, IDC_BTN_LOGBROWSE);
				EnableWindow(hw, IsDlgButtonChecked(hwndDlg, IDC_CHK_LOG));
				hw = GetDlgItem(hwndDlg, IDC_CHK_LOGCSV);
				EnableWindow(hw, IsDlgButtonChecked(hwndDlg, IDC_CHK_LOG));
				// drop through
			case IDC_CHK_LOGCSV:
			case IDC_CHECKPOPUP:
			case IDC_CHECKPOPUP2:
			case IDC_CHK_BLOCK:
			case IDC_CHK_MINMAX:
			case IDC_CHK_NOTESTICON:
			case IDC_CHK_ATTACH:
				SendMessage( GetParent( hwndDlg ), PSM_CHANGED, 0, 0 );
				break;
			case IDC_BTN_VIEWLOG:
				CallService(PLUG "/ViewLogData", 0, 0);
				break;
			case IDC_BTN_LOGBROWSE:
				ofn.lStructSize = sizeof(ofn);
				ofn.lpstrFile = options.log_filename;
				ofn.hwndOwner = hwndDlg;
				ofn.Flags = CC_FULLOPEN;
				//ofn.lpstrFile[0] = '\0';
				ofn.nMaxFile = sizeof(options.log_filename);
				ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
				ofn.nFilterIndex = 1;
				ofn.lpstrFileTitle = NULL;
				ofn.nMaxFileTitle = 0;
				ofn.lpstrInitialDir = NULL;
				ofn.Flags = OFN_PATHMUSTEXIST;

				if(GetOpenFileName(&ofn) == TRUE) {
					SetDlgItemText(hwndDlg, IDC_ED_FILENAME, ofn.lpstrFile);
					SendMessage( GetParent( hwndDlg ), PSM_CHANGED, 0, 0 );
				}
				break;
			}
			break;
		}
		break;

	case WM_NOTIFY:
		if (((LPNMHDR)lParam)->code == UDN_DELTAPOS ) {
			SendMessage( GetParent( hwndDlg ), PSM_CHANGED, 0, 0 );
		} 
		if (((LPNMHDR)lParam)->code == PSN_APPLY ) {

			BOOL trans_success;

			DWORD new_ping_period = GetDlgItemInt( hwndDlg, IDC_PPM, &trans_success, FALSE);
			if(trans_success) {
				options.ping_period = new_ping_period;
			}
			DWORD new_ping_timeout = GetDlgItemInt( hwndDlg, IDC_PT, &trans_success, FALSE);
			if(trans_success) {
				options.ping_timeout = new_ping_timeout;
			}
			options.show_popup = IsDlgButtonChecked(hwndDlg, IDC_CHECKPOPUP) == BST_CHECKED;
			options.show_popup2 = IsDlgButtonChecked(hwndDlg, IDC_CHECKPOPUP2) == BST_CHECKED;
			options.block_reps = IsDlgButtonChecked(hwndDlg, IDC_CHK_BLOCK) == BST_CHECKED;
			options.logging = IsDlgButtonChecked(hwndDlg, IDC_CHK_LOG) == BST_CHECKED;
			options.log_csv = IsDlgButtonChecked(hwndDlg, IDC_CHK_LOGCSV) == BST_CHECKED;
			GetDlgItemText(hwndDlg, IDC_ED_FILENAME, options.log_filename, MAX_PATH);

			options.no_test_icon = IsDlgButtonChecked(hwndDlg, IDC_CHK_NOTESTICON) == BST_CHECKED;

			options.indent = SendMessage(GetDlgItem(hwndDlg, IDC_SP_INDENT), UDM_GETPOS, 0, 0);
			options.row_height = SendMessage(GetDlgItem(hwndDlg, IDC_SP_ROWHEIGHT), UDM_GETPOS, 0, 0);

			DWORD new_retries = GetDlgItemInt( hwndDlg, IDC_RPT, &trans_success, FALSE);
			if(trans_success) {
				options.retries = new_retries;
			}

			bool new_attach = (IsDlgButtonChecked(hwndDlg, IDC_CHK_ATTACH) == BST_CHECKED);
			if(!ServiceExists(MS_CLIST_FRAMES_ADDFRAME) && options.attach_to_clist != new_attach)
				AttachToClist(new_attach);

			options.attach_to_clist = new_attach;

			SaveOptions();

			RefreshWindow(0, 0);

			if(options.logging) CallService(PLUG "/Log", (WPARAM)"options changed", 0);
			if(hWakeEvent) SetEvent(hWakeEvent);
			return TRUE;
		}
		break;
	}

	return FALSE;
}
Пример #7
0
void __cdecl CYahooProto::im_sendackfail_longmsg(HANDLE hContact)
{
	SleepEx(1000, TRUE);
	ProtoBroadcastAck(m_szModuleName, hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, (HANDLE) 1, 
						(LPARAM)Translate("Message is too long: Yahoo messages are limited by 800 UTF8 chars"));
}
Пример #8
0
void pbrtTranslate(Float dx, Float dy, Float dz) {
    VERIFY_INITIALIZED("Translate");
    FOR_ACTIVE_TRANSFORMS(curTransform[i] = curTransform[i] *
                                            Translate(Vector3f(dx, dy, dz));)
}
Пример #9
0
INT_PTR CDropbox::ProtoSendMessage(void *obj, WPARAM, LPARAM lParam)
{
	CDropbox *instance = (CDropbox*)obj;

	if (!instance->HasAccessToken())
		return ACKRESULT_FAILED;

	CCSDATA *pccsd = (CCSDATA*)lParam;

	char *message = (char*)pccsd->lParam;

	DBEVENTINFO dbei = { sizeof(dbei) };
	dbei.szModule = MODULE;
	dbei.timestamp = time(NULL);
	dbei.eventType = EVENTTYPE_MESSAGE;
	dbei.cbBlob = strlen(message);
	dbei.pBlob = (PBYTE)message;
	dbei.flags = DBEF_SENT | DBEF_READ | DBEF_UTF;
	db_event_add(pccsd->hContact, &dbei);

	char help[1024];

	if (message[0] && message[0] == '/')
	{
		// parse commands
		char *sep = strchr(message, ' ');
		int len = strlen(message) - (sep ? strlen(sep) : 0) - 1;
		ptrA cmd((char*)mir_alloc(len + 1));
		strncpy(cmd, message + 1, len);
		cmd[len] = 0;
		if (instance->commands.find((char*)cmd) != instance->commands.end())
		{
			ULONG messageId = InterlockedIncrement(&instance->hMessageProcess);

			CommandParam *param = new CommandParam();
			param->instance = instance;
			param->hContact = pccsd->hContact;
			param->hProcess = (HANDLE)messageId;
			param->data = (sep ? sep + 1 : NULL);

			mir_forkthread(instance->commands[(char*)cmd], param);

			return messageId;
		}
		else
		{
			mir_snprintf(
				help,
				SIZEOF(help),
				Translate("Unknown command \"%s\".\nUse \"/help\" for more info."),
				message);

			CallContactService(instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)help);

			return 0;
		}
	}

	mir_snprintf(
		help,
		SIZEOF(help),
		Translate("\"%s\" is not valid.\nUse \"/help\" for more info."),
		message);

	CallContactService(instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)help);

	return 0;
}
Пример #10
0
	void SpriteBatch::FlushText(
		const std::vector<sstring>& text, 
		const tstring& fontname,
		TransformComponent* transform,
		const Color& color
		)
	{
		if(text.size() == 0)
		{
			Logger::GetInstance()->Log(LogLevel::Warning,
				_T("FontManager::DrawText: Drawing an empty string..."));
			return;
		}
		
		auto curfont = FontManager::GetInstance()->GetFont(fontname);
		float32 h = curfont.GetSize()/0.63f;
		const vec2& position = transform->GetWorldPosition().pos2D();
		const vec2& origposition = position;

		GLuint* textures = curfont.GetTextures();
		const std::vector<fontUvCoords>& tempuvs = curfont.GetUvCoords();
		const std::vector<fontVertices>& tempverts = curfont.GetVetrices();
		const std::vector<ivec2>& tempsizes = curfont.GetLetterDimensions();

		m_Shader.Bind();
		
		//Enable the attributes
		glEnableVertexAttribArray(ATTRIB_VERTEX);
		glEnableVertexAttribArray(ATTRIB_UV);

		glActiveTexture(GL_TEXTURE0);
		GLint s_textureId = glGetUniformLocation(m_Shader.GetID(), "textureSampler");
		glUniform1i(s_textureId, 0);
		GLint s_colorId = glGetUniformLocation(m_Shader.GetID(), "colorMultiplier");
		glUniform4f(s_colorId,color.r,color.g,color.b,color.a);
	
		float32 scaleValue = ScaleSystem::GetInstance()->GetScale();
		mat4 scaleMat = Scale(scaleValue, scaleValue, 1.0f);

		int32 offsetX(0);
		int32 offsetY(0);
		for(auto it = text.begin(); it != text.end() ; ++it)
		{
			const schar *start_line=it->c_str();
			for(int32 i = 0 ; start_line[i] != 0 ; ++i) 
			{

				glBindTexture(GL_TEXTURE_2D,textures[ start_line[i] ]);

				//Set attributes and buffers
				glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT,0,0,
					tempverts[start_line[i]].ver);
				glVertexAttribPointer(ATTRIB_UV, 2, GL_FLOAT, 0, 0, 
					tempuvs[start_line[i]].uv);

				mat4 offsetTrans;
				
				if(start_line[i] != 0)
				{
					int32 offset = curfont.GetMaxLetterHeight() - tempsizes[start_line[i]].y;
					offsetTrans = Translate(
						vec3(offsetX, offsetY - curfont.GetMaxLetterHeight() - offset, 0));
					offsetX += tempsizes[start_line[i]].x;
				}
				else
				{
					offsetTrans = Translate(0.0f, 0.0f, 0.0f);
				}
				const mat4& world = transform->GetWorldMatrix() * offsetTrans;

				glUniformMatrix4fv(glGetUniformLocation(m_Shader.GetID(),"MVP"),
					1,GL_FALSE,
					ToPointerValue(
						Transpose(world) *
						scaleMat *
						GraphicsManager::GetInstance()->GetViewProjectionMatrix()
						)
					);
				glDrawArrays(GL_TRIANGLE_STRIP,0,4);
			}
			offsetY -= curfont.GetMaxLetterHeight();
			offsetX = 0;
		}	

		//Unbind attributes and buffers
		glDisableVertexAttribArray(ATTRIB_VERTEX);
		glDisableVertexAttribArray(ATTRIB_UV);
		m_Shader.Unbind();
	}
void mitk::BoundingShapeVtkMapper2D::GenerateDataForRenderer(BaseRenderer *renderer)
{
  const DataNode::Pointer node = GetDataNode();
  if (node == nullptr)
    return;

  LocalStorage *localStorage = m_Impl->LocalStorageHandler.GetLocalStorage(renderer);

  // either update if GeometryData was modified or if the zooming was performed
  bool needGenerateData = localStorage->IsUpdateRequired(
    renderer, this, GetDataNode()); // true; // localStorage->GetLastGenerateDataTime() < node->GetMTime() ||
  // localStorage->GetLastGenerateDataTime() < node->GetData()->GetMTime();
  // //localStorage->IsGenerateDataRequired(renderer, this, GetDataNode());

  double scale = renderer->GetScaleFactorMMPerDisplayUnit();

  if (std::abs(scale - localStorage->m_ZoomFactor) > 0.001)
  {
    localStorage->m_ZoomFactor = scale;
    needGenerateData = true;
  }

  if (needGenerateData)
  {
    bool visible = true;
    GetDataNode()->GetVisibility(visible, renderer, "visible");

    if (!visible)
    {
      localStorage->m_Actor->VisibilityOff();
      return;
    }
    GeometryData::Pointer shape = static_cast<GeometryData *>(node->GetData());
    if (shape == nullptr)
      return;

    mitk::BaseGeometry::Pointer geometry = shape->GetGeometry();
    mitk::Vector3D spacing = geometry->GetSpacing();

    // calculate cornerpoints and extent from geometry with visualization offset
    std::vector<Point3D> cornerPoints = GetCornerPoints(geometry, true);
    Point3D p0 = cornerPoints[0];
    Point3D p1 = cornerPoints[1];
    Point3D p2 = cornerPoints[2];
    Point3D p4 = cornerPoints[4];
    Point3D extent;
    extent[0] =
      sqrt((p0[0] - p4[0]) * (p0[0] - p4[0]) + (p0[1] - p4[1]) * (p0[1] - p4[1]) + (p0[2] - p4[2]) * (p0[2] - p4[2]));
    extent[1] =
      sqrt((p0[0] - p2[0]) * (p0[0] - p2[0]) + (p0[1] - p2[1]) * (p0[1] - p2[1]) + (p0[2] - p2[2]) * (p0[2] - p2[2]));
    extent[2] =
      sqrt((p0[0] - p1[0]) * (p0[0] - p1[0]) + (p0[1] - p1[1]) * (p0[1] - p1[1]) + (p0[2] - p1[2]) * (p0[2] - p1[2]));

    // calculate center based on half way of the distance between two opposing cornerpoints
    mitk::Point3D center = CalcAvgPoint(cornerPoints[7], cornerPoints[0]);

    if (m_Impl->HandlePropertyList.size() == 6)
    {
      // set handle positions
      Point3D pointLeft = CalcAvgPoint(cornerPoints[5], cornerPoints[6]);
      Point3D pointRight = CalcAvgPoint(cornerPoints[1], cornerPoints[2]);
      Point3D pointTop = CalcAvgPoint(cornerPoints[0], cornerPoints[6]);
      Point3D pointBottom = CalcAvgPoint(cornerPoints[7], cornerPoints[1]);
      Point3D pointFront = CalcAvgPoint(cornerPoints[2], cornerPoints[7]);
      Point3D pointBack = CalcAvgPoint(cornerPoints[4], cornerPoints[1]);

      m_Impl->HandlePropertyList[0].SetPosition(pointLeft);
      m_Impl->HandlePropertyList[1].SetPosition(pointRight);
      m_Impl->HandlePropertyList[2].SetPosition(pointTop);
      m_Impl->HandlePropertyList[3].SetPosition(pointBottom);
      m_Impl->HandlePropertyList[4].SetPosition(pointFront);
      m_Impl->HandlePropertyList[5].SetPosition(pointBack);
    }

    // caculate face normals
    double result0[3], result1[3], result2[3];
    double a[3], b[3];
    a[0] = (cornerPoints[5][0] - cornerPoints[6][0]);
    a[1] = (cornerPoints[5][1] - cornerPoints[6][1]);
    a[2] = (cornerPoints[5][2] - cornerPoints[6][2]);

    b[0] = (cornerPoints[5][0] - cornerPoints[4][0]);
    b[1] = (cornerPoints[5][1] - cornerPoints[4][1]);
    b[2] = (cornerPoints[5][2] - cornerPoints[4][2]);

    vtkMath::Cross(a, b, result0);

    a[0] = (cornerPoints[0][0] - cornerPoints[6][0]);
    a[1] = (cornerPoints[0][1] - cornerPoints[6][1]);
    a[2] = (cornerPoints[0][2] - cornerPoints[6][2]);

    b[0] = (cornerPoints[0][0] - cornerPoints[2][0]);
    b[1] = (cornerPoints[0][1] - cornerPoints[2][1]);
    b[2] = (cornerPoints[0][2] - cornerPoints[2][2]);

    vtkMath::Cross(a, b, result1);

    a[0] = (cornerPoints[2][0] - cornerPoints[7][0]);
    a[1] = (cornerPoints[2][1] - cornerPoints[7][1]);
    a[2] = (cornerPoints[2][2] - cornerPoints[7][2]);

    b[0] = (cornerPoints[2][0] - cornerPoints[6][0]);
    b[1] = (cornerPoints[2][1] - cornerPoints[6][1]);
    b[2] = (cornerPoints[2][2] - cornerPoints[6][2]);

    vtkMath::Cross(a, b, result2);

    vtkMath::Normalize(result0);
    vtkMath::Normalize(result1);
    vtkMath::Normalize(result2);

    // create cube for rendering bounding box
    auto cube = vtkCubeSource::New();
    cube->SetXLength(extent[0] / spacing[0]);
    cube->SetYLength(extent[1] / spacing[1]);
    cube->SetZLength(extent[2] / spacing[2]);

    // calculates translation based on offset+extent not on the transformation matrix
    vtkSmartPointer<vtkMatrix4x4> imageTransform = geometry->GetVtkTransform()->GetMatrix();
    auto translation = vtkSmartPointer<vtkTransform>::New();
    translation->Translate(center[0] - imageTransform->GetElement(0, 3),
      center[1] - imageTransform->GetElement(1, 3),
      center[2] - imageTransform->GetElement(2, 3));

    auto transform = vtkSmartPointer<vtkTransform>::New();
    transform->SetMatrix(imageTransform);
    transform->PostMultiply();
    transform->Concatenate(translation);
    transform->Update();
    cube->Update();

    auto transformFilter = vtkSmartPointer<vtkTransformFilter>::New();
    transformFilter->SetInputData(cube->GetOutput());
    transformFilter->SetTransform(transform);
    transformFilter->Update();
    cube->Delete();

    vtkSmartPointer<vtkPolyData> polydata = transformFilter->GetPolyDataOutput();
    if (polydata == nullptr || (polydata->GetNumberOfPoints() < 1))
    {
      localStorage->m_Actor->VisibilityOff();
      localStorage->m_HandleActor->VisibilityOff();
      localStorage->m_SelectedHandleActor->VisibilityOff();
      return;
    }

    // estimate current image plane to decide whether the cube is visible or not
    const PlaneGeometry *planeGeometry = renderer->GetCurrentWorldPlaneGeometry();
    if ((planeGeometry == nullptr) || (!planeGeometry->IsValid()) || (!planeGeometry->HasReferenceGeometry()))
      return;

    double origin[3];
    origin[0] = planeGeometry->GetOrigin()[0];
    origin[1] = planeGeometry->GetOrigin()[1];
    origin[2] = planeGeometry->GetOrigin()[2];

    double normal[3];
    normal[0] = planeGeometry->GetNormal()[0];
    normal[1] = planeGeometry->GetNormal()[1];
    normal[2] = planeGeometry->GetNormal()[2];

    //    MITK_INFO << "normal1 " << normal[0] << " " << normal[1] << " " << normal[2];
    localStorage->m_CuttingPlane->SetOrigin(origin);
    localStorage->m_CuttingPlane->SetNormal(normal);

    // add cube polydata to local storage
    localStorage->m_Cutter->SetInputData(polydata);
    localStorage->m_Cutter->SetGenerateCutScalars(1);
    localStorage->m_Cutter->Update();

    if (localStorage->m_PropAssembly->GetParts()->IsItemPresent(localStorage->m_HandleActor))
      localStorage->m_PropAssembly->RemovePart(localStorage->m_HandleActor);
    if (localStorage->m_PropAssembly->GetParts()->IsItemPresent(localStorage->m_Actor))
      localStorage->m_PropAssembly->RemovePart(localStorage->m_Actor);

    vtkCoordinate *tcoord = vtkCoordinate::New();
    tcoord->SetCoordinateSystemToWorld();
    localStorage->m_HandleMapper->SetTransformCoordinate(tcoord);
    tcoord->Delete();

    if (localStorage->m_Cutter->GetOutput()->GetNumberOfPoints() > 0) // if plane is visible in the renderwindow
    {
      mitk::DoubleProperty::Pointer handleSizeProperty =
        dynamic_cast<mitk::DoubleProperty *>(this->GetDataNode()->GetProperty("Bounding Shape.Handle Size Factor"));

      ScalarType initialHandleSize;
      if (handleSizeProperty != nullptr)
        initialHandleSize = handleSizeProperty->GetValue();
      else
        initialHandleSize = 1.0 / 40.0;

      mitk::Point2D displaySize = renderer->GetDisplaySizeInMM();
      double handleSize = ((displaySize[0] + displaySize[1]) / 2.0) * initialHandleSize;

      auto appendPoly = vtkSmartPointer<vtkAppendPolyData>::New();
      unsigned int i = 0;

      // add handles and their assigned properties to the local storage
      mitk::IntProperty::Pointer activeHandleId =
        dynamic_cast<mitk::IntProperty *>(node->GetProperty("Bounding Shape.Active Handle ID"));

      bool visible = false;
      bool selected = false;
      for (auto handle : localStorage->m_Handles)
      {
        Point3D handleCenter = m_Impl->HandlePropertyList[i].GetPosition();

        handle->SetRadius(handleSize);
        handle->SetCenter(handleCenter[0], handleCenter[1], handleCenter[2]);

        vtkMath::Normalize(normal);
        double angle = vtkMath::DegreesFromRadians(acos(vtkMath::Dot(normal, result0)));
        double angle1 = vtkMath::DegreesFromRadians(acos(vtkMath::Dot(normal, result1)));
        double angle2 = vtkMath::DegreesFromRadians(acos(vtkMath::Dot(normal, result2)));

        // show handles only if the corresponding face is aligned to the render window
        if ((((std::abs(angle - 0) < 0.001) || (std::abs(angle - 180) < 0.001)) && i != 0 && i != 1) ||
          (((std::abs(angle1 - 0) < 0.001) || (std::abs(angle1 - 180) < 0.001)) && i != 2 && i != 3) ||
          (((std::abs(angle2 - 0) < 0.001) || (std::abs(angle2 - 180) < 0.001)) && i != 4 && i != 5))
        {
          if (activeHandleId == nullptr)
          {
            appendPoly->AddInputConnection(handle->GetOutputPort());
          }
          else
          {
            if ((activeHandleId->GetValue() != m_Impl->HandlePropertyList[i].GetIndex()))
            {
              appendPoly->AddInputConnection(handle->GetOutputPort());
            }
            else
            {
              handle->Update();
              localStorage->m_SelectedHandleMapper->SetInputData(handle->GetOutput());
              localStorage->m_SelectedHandleActor->VisibilityOn();
              selected = true;
            }
          }
          visible = true;
        }

        i++;
      }

      if (visible)
      {
        appendPoly->Update();
      }
      else
      {
        localStorage->m_HandleActor->VisibilityOff();
        localStorage->m_SelectedHandleActor->VisibilityOff();
      }

      auto stripper = vtkSmartPointer<vtkStripper>::New();
      stripper->SetInputData(localStorage->m_Cutter->GetOutput());
      stripper->Update();

      auto cutPolyData = vtkSmartPointer<vtkPolyData>::New();
      cutPolyData->SetPoints(stripper->GetOutput()->GetPoints());
      cutPolyData->SetPolys(stripper->GetOutput()->GetLines());

      localStorage->m_Actor->GetMapper()->SetInputDataObject(cutPolyData);
      mitk::ColorProperty::Pointer selectedColor = dynamic_cast<mitk::ColorProperty *>(node->GetProperty("color"));
      if (selectedColor != nullptr)
      {
        mitk::Color color = selectedColor->GetColor();
        localStorage->m_Actor->GetProperty()->SetColor(color[0], color[1], color[2]);
      }

      if (activeHandleId != nullptr)
      {
        localStorage->m_HandleActor->GetProperty()->SetColor(1, 0, 0);
      }
      else
      {
        localStorage->m_HandleActor->GetProperty()->SetColor(1, 1, 1);
      }
      localStorage->m_HandleActor->GetMapper()->SetInputDataObject(appendPoly->GetOutput());

      // add parts to the overall storage
      localStorage->m_PropAssembly->AddPart(localStorage->m_Actor);
      localStorage->m_PropAssembly->AddPart(localStorage->m_HandleActor);
      if (selected)
      {
        localStorage->m_PropAssembly->AddPart(localStorage->m_SelectedHandleActor);
      }

      localStorage->m_PropAssembly->VisibilityOn();
      localStorage->m_Actor->VisibilityOn();
      localStorage->m_HandleActor->VisibilityOn();
    }
    else
    {
      localStorage->m_PropAssembly->VisibilityOff();
      localStorage->m_Actor->VisibilityOff();
      localStorage->m_HandleActor->VisibilityOff();
      localStorage->m_SelectedHandleActor->VisibilityOff();
      localStorage->UpdateGenerateDataTime();
    }
    localStorage->UpdateGenerateDataTime();
  }
}
Пример #12
0
int facebook_json_parser::parse_thread_messages(std::string *data, std::vector< facebook_message* >* messages, std::map< std::string, facebook_chatroom* >* chatrooms, bool unreadOnly, bool inboxOnly)
{
	std::string jsonData = data->substr(9);

	JSONNode root = JSONNode::parse(jsonData.c_str());
	if (!root)
		return EXIT_FAILURE;

	const JSONNode &payload = root["payload"];
	if (!payload)
		return EXIT_FAILURE;

	const JSONNode &actions = payload["actions"];
	const JSONNode &threads = payload["threads"];
	if (!actions || !threads)
		return EXIT_FAILURE;

	const JSONNode &roger = payload["roger"];
	for (auto it = roger.begin(); it != roger.end(); ++it) {
		std::string id = (*it).name();

		// Ignore "wrong" (duplicit) identifiers - these that doesn't begin with "id."
		if (id.substr(0, 3) == "id.") {
			facebook_chatroom *room = new facebook_chatroom(id);
			chatrooms->insert(std::make_pair(id, room));
		}
	}

	std::map<std::string, std::string> thread_ids;
	for (auto it = threads.begin(); it != threads.end(); ++it) {
		const JSONNode &is_canonical_user = (*it)["is_canonical_user"];
		const JSONNode &canonical = (*it)["canonical_fbid"];
		const JSONNode &thread_id = (*it)["thread_id"];
		const JSONNode &name = (*it)["name"];
		//const JSONNode &message_count = (*it)["message_count");
		//const JSONNode &unread_count = (*it)["unread_count"); // TODO: use it to check against number of loaded messages... but how?
		const JSONNode &folder = (*it)["folder"];

		if (!canonical || !thread_id)
			continue;

		std::string id = canonical.as_string();
		std::string tid = thread_id.as_string();

		std::map<std::string, facebook_chatroom*>::iterator iter = chatrooms->find(tid);
		if (iter != chatrooms->end()) {
			if (is_canonical_user.as_bool()) {
				chatrooms->erase(iter); // this is not chatroom
			}
			else {
				iter->second->chat_name = std::tstring(ptrT(mir_utf8decodeT(name.as_string().c_str()))); // TODO: create name from users if there is no name...

				const JSONNode &participants = (*it)["participants"];
				for (auto jt = participants.begin(); jt != participants.end(); ++jt) {
					std::string user_id = (*jt).name();
					iter->second->participants.insert(std::make_pair(user_id, user_id)); // TODO: get name somehow
				}
			}
		}

		iter = chatrooms->find(id);
		if (iter != chatrooms->end())
			chatrooms->erase(iter); // this is not chatroom

		if (inboxOnly && folder.as_string() != "inbox")
			continue;

		if (id == "null")
			continue;

		thread_ids.insert(std::make_pair(tid, id));
	}

	for (auto it = actions.begin(); it != actions.end(); ++it) {
		const JSONNode &author = (*it)["author"];
		const JSONNode &author_email = (*it)["author_email"];
		const JSONNode &body = (*it)["body"];
		const JSONNode &tid = (*it)["thread_id"];
		const JSONNode &mid = (*it)["message_id"];
		const JSONNode &timestamp = (*it)["timestamp"];
		const JSONNode &filtered = (*it)["is_filtered_content"];
		const JSONNode &folder = (*it)["folder"];
		const JSONNode &is_unread = (*it)["is_unread"];

		if (!author || !body || !mid || !tid || !timestamp)
			continue;

		if (inboxOnly && folder.as_string() != "inbox")
			continue;

		std::string thread_id = tid.as_string();
		std::string message_id = mid.as_string();
		std::string message_text = body.as_string();
		std::string author_id = author.as_string();
		std::string::size_type pos = author_id.find(":");
		if (pos != std::string::npos)
			author_id = author_id.substr(pos + 1);

		// Process attachements and stickers
		parseAttachments(proto, &message_text, *it, thread_id, ""); // FIXME: is here supported other_user_fbid ?

		if (filtered.as_bool() && message_text.empty())
			message_text = Translate("This message is no longer available, because it was marked as abusive or spam.");

		message_text = utils::text::trim(utils::text::slashu_to_utf8(message_text), true);
		if (message_text.empty())
			continue;

		bool isUnread = is_unread.as_bool();

		// Ignore read messages if we want only unread messages
		if (unreadOnly && !isUnread)
			continue;

		facebook_message* message = new facebook_message();
		message->message_text = message_text;
		if (author_email)
			message->sender_name = author_email.as_string();
		message->time = utils::time::from_string(timestamp.as_string());
		message->thread_id = thread_id;
		message->message_id = message_id;
		message->isIncoming = (author_id != proto->facy.self_.user_id);
		message->isUnread = isUnread;

		std::map<std::string, facebook_chatroom*>::iterator iter = chatrooms->find(thread_id);
		if (iter != chatrooms->end()) {
			// this is chatroom message
			message->isChat = true;
			message->user_id = author_id;
		}
		else {
			// this is standard message
			message->isChat = false;
			std::map<std::string, std::string>::iterator iter = thread_ids.find(thread_id);
			if (iter != thread_ids.end()) {
				message->user_id = iter->second; // TODO: Check if we have contact with this ID in friendlist and otherwise do something different?
			} else {
				delete message;
				continue;
			}
		}

		messages->push_back(message);
	}

	return EXIT_SUCCESS;
}
Пример #13
0
int facebook_json_parser::parse_messages(std::string *data, std::vector< facebook_message* >* messages, std::map< std::string, facebook_notification* >* notifications, bool inboxOnly)
{
	// remove old received messages from map		
	for (std::map<std::string, int>::iterator it = proto->facy.messages_ignore.begin(); it != proto->facy.messages_ignore.end();) {
		if (it->second > FACEBOOK_IGNORE_COUNTER_LIMIT) {
			it = proto->facy.messages_ignore.erase(it);
		}
		else {
			it->second++; // increase counter on each request
			++it;
		}
	}

	std::string jsonData = data->substr(9);

	JSONNode root = JSONNode::parse(jsonData.c_str());
	if (!root)
		return EXIT_FAILURE;

	const JSONNode &ms = root["ms"];
	if (!ms)
		return EXIT_FAILURE;

	for (auto it = ms.begin(); it != ms.end(); ++it) {
		const JSONNode &type = (*it)["type"];
		if (!type)
			continue;

		std::string t = type.as_string();
		if (t == "messaging") {
			// various messaging stuff (received and sent messages, getting seen info)

			const JSONNode &type = (*it)["event"];
			if (!type)
				continue;

			std::string t = type.as_string();
			if (t == "read_receipt") {
				// user read message
				const JSONNode &reader_ = (*it)["reader"];
				const JSONNode &time_ = (*it)["time"];
				if (!reader_ || !time_)
					continue;

				time_t timestamp = utils::time::from_string(time_.as_string());
				MCONTACT hContact = NULL;
				std::tstring reader;

				std::string readerId = reader_.as_string();
				const JSONNode &threadid = (*it)["tid"];
				if (!threadid) {
					// classic contact
					hContact = proto->ContactIDToHContact(readerId);
				} else {
					// multi user chat
					if (!proto->m_enableChat)
						continue;

					std::string tid = threadid.as_string();

					std::map<std::string, facebook_chatroom*>::iterator it = proto->facy.chat_rooms.find(tid);
					if (it != proto->facy.chat_rooms.end()) {
						facebook_chatroom *chatroom = it->second;
						std::map<std::string, std::string> participants = chatroom->participants;

						std::map<std::string, std::string>::const_iterator participant = participants.find(readerId);
						if (participant == participants.end()) {
							// TODO: load name of this participant
							std::string name = readerId;
							participants.insert(std::make_pair(readerId, name));
							proto->AddChatContact(tid.c_str(), readerId.c_str(), name.c_str());
						}

						participant = participants.find(readerId);
						if (participant != participants.end()) {
							// TODO: remember just reader ids to avoid eventual duplication of names
							reader = _A2T(participant->second.c_str(), CP_UTF8);
							hContact = proto->ChatIDToHContact(tid);
						}
					}
				}

				if (hContact)
					proto->facy.insert_reader(hContact, timestamp, reader);
			}
			else if (t == "deliver") {
				// inbox message (multiuser or direct)

				const JSONNode &msg = (*it)["message"];
				const JSONNode &folder = (*it)["folder"];				

				if (inboxOnly && folder.as_string() != "inbox")
					continue;

				const JSONNode &sender_fbid = msg["sender_fbid"];
				const JSONNode &sender_name = msg["sender_name"];
				const JSONNode &body = msg["body"];

				// looks like there is either "tid" or "other_user_fbid" (or both)
				const JSONNode &tid = msg["tid"];
				const JSONNode &mid = msg["mid"];
				const JSONNode &timestamp = msg["timestamp"];				
				if (!sender_fbid || !sender_name || !body || !mid || !timestamp)
					continue;

				const JSONNode &is_filtered = (*it)["is_filtered_content"]; // TODO: is it still here? perhaps it is replaced with msg["is_spoof_warning"] or something else?
				//const JSONNode &is_spoof_warning = msg["is_spoof_warning"];				
				//const JSONNode &is_silent = msg["is_silent"];
				//const JSONNode &is_unread = msg["is_unread"];

				std::string id = sender_fbid.as_string();
				std::string message_id = mid.as_string();
				std::string message_text = body.as_string();

				std::string thread_id = tid.as_string();
				std::string other_user_id = msg["other_user_fbid"].as_string();

				// Process attachements and stickers
				parseAttachments(proto, &message_text, msg, thread_id, other_user_id);

				// Ignore duplicits or messages sent from miranda
				if (!body || ignore_duplicits(proto, message_id, message_text))
					continue;

				if (is_filtered.as_bool() && message_text.empty())
					message_text = Translate("This message is no longer available, because it was marked as abusive or spam.");

				message_text = utils::text::trim(utils::text::slashu_to_utf8(message_text), true);
				if (message_text.empty())
					continue;

				facebook_message* message = new facebook_message();
				message->isUnread = true;
				message->isIncoming = (id != proto->facy.self_.user_id);
				message->message_text = message_text;
				message->time = utils::time::from_string(timestamp.as_string());
				message->user_id = id;
				message->message_id = message_id;
				message->sender_name = utils::text::slashu_to_utf8(sender_name.as_string()); // TODO: or if not incomming use my own name from facy.self_ ?
				message->thread_id = tid.as_string(); // TODO: or if not incomming use my own id from facy.self_ ?

				const JSONNode &gthreadinfo = msg["group_thread_info"];
				message->isChat = (gthreadinfo && gthreadinfo.as_string() != "null");

				if (!message->isChat && !message->isIncoming) {
					message->sender_name.clear();
					message->user_id = !other_user_id.empty() ? other_user_id : proto->ThreadIDToContactID(message->thread_id); // TODO: Check if we have contact with this user_id in friendlist and otherwise do something different?
				}

				messages->push_back(message);
			}
		}
		else if (t == "notification_json") {
			// event notification
			const JSONNode &nodes = (*it)["nodes"];

			// Create notifications chatroom (if it doesn't exists), because we will be writing to it new notifications here
			proto->PrepareNotificationsChatRoom();

			for (auto itNodes = nodes.begin(); itNodes != nodes.end(); ++itNodes) {
				const JSONNode &text_ = (*itNodes)["unaggregatedTitle"]; // notifications one by one, not grouped
				if (!text_)
					continue;
				
				const JSONNode &text = text_["text"];
				const JSONNode &url = (*itNodes)["url"];
				const JSONNode &alert_id = (*itNodes)["alert_id"];

				const JSONNode &time_ = (*itNodes)["timestamp"];
				if (!time_)
					continue;
				const JSONNode &time = time_["time"];
				if (!time || !text || !url || !alert_id)
					continue;

				time_t timestamp = utils::time::from_string(time.as_string());
				if (timestamp > proto->facy.last_notification_time_) {
					// Only new notifications
					proto->facy.last_notification_time_ = timestamp;

					facebook_notification* notification = new facebook_notification();
					notification->text = utils::text::slashu_to_utf8(text.as_string());
					notification->link = url.as_string();
					notification->id = alert_id.as_string();
					notification->time = timestamp;

					// Fix notification ID
					std::string::size_type pos = notification->id.find(":");
					if (pos != std::string::npos)
						notification->id = notification->id.substr(pos + 1);

					// Write notification to chatroom
					proto->UpdateNotificationsChatRoom(notification);

					// If it's unseen, remember it, otherwise forget it (here it will always be unseen)
					if (notifications->find(notification->id) == notifications->end() && !notification->seen)
						notifications->insert(std::make_pair(notification->id, notification));
					else
						delete notification;
				}
			}
		}
		else if (t == "m_notification") {
			const JSONNode &data = (*it)["data"];
			if (!data)
				continue;

			const JSONNode &appId_ = data["app_id"];
			const JSONNode &type_ = data["type"];

			if (appId_.as_string() == "2356318349" || type_.as_string() == "friend_confirmed") {
				// Friendship notifications

				const JSONNode &body_ = data["body"];
				const JSONNode &html_ = body_["__html"];

				const JSONNode &href_ = data["href"];
				const JSONNode &unread_ = data["unread"];
				const JSONNode &alertId_ = data["alert_id"];

				if (!html_ || !href_ || !unread_ || unread_.as_int() == 0)
					continue;
				
				std::string text = utils::text::remove_html(utils::text::slashu_to_utf8(html_.as_string()));
				std::string url = href_.as_string();
				std::string alert_id = alertId_.as_string();

				proto->NotifyEvent(proto->m_tszUserName, ptrT(mir_utf8decodeT(text.c_str())), NULL, FACEBOOK_EVENT_FRIENDSHIP, &url, alert_id.empty() ? NULL : &alert_id);
			}
		}
		else if (t == "jewel_requests_add") {
			// New friendship request, load them all with real names (because there is only user_id in "from" field)
			proto->ForkThread(&FacebookProto::ProcessFriendRequests, NULL);
		}
		else if (t == "typ") {
			// chat typing notification

			const JSONNode &from = (*it)["from"];
			if (!from)
				continue;

			facebook_user fbu;
			fbu.user_id = from.as_string();

			MCONTACT hContact = proto->AddToContactList(&fbu, CONTACT_FRIEND); // only friends are able to send typing notifications

			const JSONNode &st = (*it)["st"];
			if (st.as_int() == 1)
				proto->StartTyping(hContact);
			else
				proto->StopTyping(hContact);
		}
		else if (t == "ttyp") {
			// multi chat typing notification
			if (!proto->m_enableChat)
				continue;

			const JSONNode &from_ = (*it)["from"];
			const JSONNode &thread_ = (*it)["thread"];
			const JSONNode &st_ = (*it)["st"];
			if (!from_ || !thread_ || !st_)
				continue;

			std::string tid = thread_.as_string();
			std::string from_id = from_.as_string();

			std::map<std::string, facebook_chatroom*>::iterator it = proto->facy.chat_rooms.find(thread_.as_string());
			if (it != proto->facy.chat_rooms.end()) {
				facebook_chatroom *chatroom = it->second;
				std::map<std::string, std::string> participants = chatroom->participants;

				std::map<std::string, std::string>::const_iterator participant = participants.find(from_id);
				if (participant == participants.end()) {
					// TODO: load name of this participant
					std::string name = from_id;
					proto->AddChatContact(tid.c_str(), from_id.c_str(), name.c_str());
				}

				participant = participants.find(from_id);
				if (participant != participants.end()) {
					MCONTACT hChatContact = proto->ChatIDToHContact(tid);
					ptrT name(mir_utf8decodeT(participant->second.c_str()));

					if (st_.as_int() == 1) {
						StatusTextData st = { 0 };
						st.cbSize = sizeof(st);

						mir_sntprintf(st.tszText, _countof(st.tszText), TranslateT("%s is typing a message..."), name);

						CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)hChatContact, (LPARAM)&st);
					}
					else {
						CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)hChatContact);
					}

					// TODO: support proper MS_PROTO_CONTACTISTYPING service for chatrooms (when it will be implemented)
				}
			}
		}
		else if (t == "privacy_changed") {
			// settings changed

			const JSONNode &event_type = (*it)["event"];
			const JSONNode &event_data = (*it)["data"];
			if (!event_type || !event_data)
				continue;

			std::string t = event_type.as_string();
			if (t == "visibility_update") {
				// change of chat status
				const JSONNode &visibility = event_data["visibility"];

				bool isVisible = visibility && visibility.as_bool();
				proto->debugLogA("    Requested chat switch to %s", isVisible ? "Online" : "Offline");
				proto->SetStatus(isVisible ? ID_STATUS_ONLINE : ID_STATUS_INVISIBLE);
			}
		}
		else if (t == "buddylist_overlay") {
			// we opened/closed chat window - pretty useless info for us
			continue;
		} else if (t == "ticker_update:home") {
			const JSONNode &actor_ = (*it)["actor"];
			const JSONNode &story_ = (*it)["story_xhp"];

			std::string text = story_.as_string();
			text = utils::text::html_entities_decode(utils::text::slashu_to_utf8(text));

			std::string url = utils::text::source_get_value(&text, 3, "\"tickerStoryLink\"", "href=\"", "\"");
			std::string story_type = utils::text::source_get_value2(&text, "\"type\":\"", "\"");
			std::string story_class = utils::text::source_get_value2(&text, "\"entstory_class\":\"", "\"");

			text = utils::text::trim(utils::text::remove_html(text));

			std::string userId = actor_.as_string();

			MCONTACT hContact = proto->ContactIDToHContact(userId);

			proto->debugLogA("+++ Got ticker type='%s' class='%s'", story_type.c_str(), story_class.c_str());

			if (!text.empty())
				proto->NotifyEvent(proto->m_tszUserName, ptrT(mir_utf8decodeT(text.c_str())), hContact, FACEBOOK_EVENT_TICKER, &url);
		}
		else if (t == "mercury") {
			// rename multi user chat, video call, ...

			const JSONNode &actions_ = (*it)["actions"];
			if (!actions_)
				continue;

			for (unsigned int i = 0; i < actions_.size(); i++) {
				const JSONNode &action_ = actions_[i];

				const JSONNode &thread_id_ = action_["thread_id"];
				const JSONNode &log_body_ = action_["log_message_body"];
				const JSONNode &log_data_ = action_["log_message_data"];
				const JSONNode &log_type_ = action_["log_message_type"];
				if (!log_data_ || !log_body_ || !thread_id_ || !log_type_)
					continue;

				std::string thread_id = thread_id_.as_string();
				std::string type = log_type_.as_string();
				std::string message_text = log_body_.as_string();

				if (type == "log:video-call") {
					std::string id = action_["other_user_fbid"].as_string();
					std::string message_id = action_["message_id"].as_string();

					facebook_message* message = new facebook_message();
					message->isChat = false;
					message->isUnread = true;
					message->isIncoming = (id != proto->facy.self_.user_id);
					message->message_text = message_text;
					message->time = utils::time::from_string(action_["timestamp"].as_string());
					message->user_id = id;
					message->message_id = message_id;
					message->sender_name.clear();
					message->thread_id = thread_id;
					message->type = CALL;

					messages->push_back(message);
				}
				else {
					// TODO: check for other types, now we expect this is rename chat
					if (!proto->m_enableChat)
						continue;

					std::string name = log_data_["name"].as_string();

					// proto->RenameChat(thread_id.c_str(), name.c_str()); // this don't work, why?
					proto->setStringUtf(proto->ChatIDToHContact(thread_id), FACEBOOK_KEY_NICK, name.c_str());

					proto->UpdateChat(thread_id.c_str(), NULL, NULL, message_text.c_str());
				}
			}
		}
		else if (t == "notifications_read" || t == "notifications_seen") {
			ScopedLock s(proto->facy.notifications_lock_);

			const JSONNode &alerts = (*it)["alert_ids"];

			for (auto itAlerts = alerts.begin(); itAlerts != alerts.end(); ++itAlerts) {
				std::string id = (*itAlerts).as_string();

				std::map<std::string, facebook_notification*>::iterator it = notifications->find(id);
				if (it != notifications->end()) {
					if (it->second->hWndPopup != NULL)
						PUDeletePopup(it->second->hWndPopup); // close popup

					delete it->second;
					notifications->erase(it);
				}
			}
		}
		else
			continue;
	}

	return EXIT_SUCCESS;
}
Пример #14
0
void LoadJSONMesh(PP_Resource context,
                  PPB_OpenGLES2* gl,
                  const char* mesh,
                  Transformations* psMatrices,
                  int* piNumIndices,
                  int* piNumVertices,
                  GLuint* puiVBO,
                  GLuint* puiIBO)
{
    uint16_t* pui16Indices;
    float* pfVertices;
    float* pfTexCoords;
    float* pfNormals;
    int idx;
    int vtx;
    int iNumIndices;
    int iNumVertices;
    float fMinX;
    float fMinY;
    float fMinZ;
    float fMaxX;
    float fMaxY;
    float fMaxZ;
    float fCenterX;
    float fCenterY;
    float fCenterZ;
    cJSON *psIndices;
    cJSON *psVertices;
    cJSON *psTexCoords;
    cJSON *psNormals;
    cJSON* psBoundingBox;
    float fScale;

    cJSON *psRoot = cJSON_Parse(mesh);

    if(!psRoot)
    {
        DBG_LOG(DBG_LOG_PREFIX"No root JSON");
        return;
    }

    psIndices = cJSON_GetObjectItem(psRoot,"idx");

    if(!psIndices)
    {
        DBG_LOG(DBG_LOG_PREFIX"No indices JSON");
        cJSON_Delete(psRoot);
        return;
    }

    psVertices = cJSON_GetObjectItem(psRoot,"vtxpos");
    if(!psVertices)
    {
        DBG_LOG(DBG_LOG_PREFIX"No vertices JSON");
        cJSON_Delete(psRoot);
        return;
    }

    psTexCoords = cJSON_GetObjectItem(psRoot,"texcoord");
    if(!psTexCoords)
    {
        DBG_LOG(DBG_LOG_PREFIX"No texcoords JSON");
        cJSON_Delete(psRoot);
        return;
    }
    
    psNormals = cJSON_GetObjectItem(psRoot,"normal");
    if(!psNormals)
    {
        DBG_LOG(DBG_LOG_PREFIX"No normals JSON");
        cJSON_Delete(psRoot);
        return;
    }

    psBoundingBox = cJSON_GetObjectItem(psRoot, "bndbox");
    if(!psBoundingBox)
    {
        DBG_LOG(DBG_LOG_PREFIX"No no bndbox JSON");
        cJSON_Delete(psRoot);
        return;
    }

    iNumIndices = cJSON_GetArraySize(psIndices);

    pui16Indices = new uint16_t[iNumIndices];

    for(idx = 0; idx < iNumIndices; ++idx)
    {
        cJSON* psIndex = cJSON_GetArrayItem(psIndices, idx);
        pui16Indices[idx] = psIndex->valueint;
    }

    iNumVertices = cJSON_GetArraySize(psVertices) / 3; //GetArraySize will give the number of floats in vertex position array. Always XYZ.

    pfVertices = new float[iNumVertices * 3];
    pfTexCoords = new float[iNumVertices * 3];
    pfNormals = new float[iNumVertices * 3];
    for(vtx = 0; vtx < (iNumVertices * 3);)
    {
        cJSON* psVertex;
        cJSON* psTexC;
        cJSON* psNrm;

        psVertex = cJSON_GetArrayItem(psVertices, vtx);
        pfVertices[vtx] = psVertex->valuedouble;

        psTexC = cJSON_GetArrayItem(psTexCoords, vtx);
        pfTexCoords[vtx] = psTexC->valuedouble;

        psNrm = cJSON_GetArrayItem(psNormals, vtx);
        pfNormals[vtx] = psNrm->valuedouble;

        ++vtx;

        psVertex = cJSON_GetArrayItem(psVertices, vtx);
        pfVertices[vtx] = psVertex->valuedouble;

        psTexC = cJSON_GetArrayItem(psTexCoords, vtx);
        pfTexCoords[vtx] = 1 - psTexC->valuedouble;

        psNrm = cJSON_GetArrayItem(psNormals, vtx);
        pfNormals[vtx] = psNrm->valuedouble;

        ++vtx;

        psVertex = cJSON_GetArrayItem(psVertices, vtx);
        pfVertices[vtx] = psVertex->valuedouble;

        psTexC = cJSON_GetArrayItem(psTexCoords, vtx);
        pfTexCoords[vtx] = psTexC->valuedouble;

        psNrm = cJSON_GetArrayItem(psNormals, vtx);
        pfNormals[vtx] = psNrm->valuedouble;

        ++vtx;
    }

    fMinX = cJSON_GetArrayItem(psBoundingBox, 0)->valuedouble;
    fMinY = cJSON_GetArrayItem(psBoundingBox, 1)->valuedouble;
    fMinZ = cJSON_GetArrayItem(psBoundingBox, 2)->valuedouble;
    fMaxX = cJSON_GetArrayItem(psBoundingBox, 3)->valuedouble;
    fMaxY = cJSON_GetArrayItem(psBoundingBox, 4)->valuedouble;
    fMaxZ = cJSON_GetArrayItem(psBoundingBox, 5)->valuedouble;

    cJSON_Delete(psRoot);

    //Translation and scaling to get the object to the middle of the screen.

    Identity(psMatrices->rot);
    Identity(psMatrices->scale);
    Identity(psMatrices->xform);

	fScale = fMaxX-fMinX;
	fScale = max(fMaxY - fMinY,fScale);
	fScale = max(fMaxZ - fMinZ,fScale);
	fScale = 1.f / fScale;
    Scale(psMatrices->scale, fScale, fScale, fScale);

    fCenterX = (fMinX + fMaxX) / 2.0f;
    fCenterY = (fMinY + fMaxY) / 2.0f;
    fCenterZ = (fMinZ + fMaxZ) / 2.0f;
    Translate(psMatrices->xform, -fCenterX, -fCenterY, -fCenterZ );

    //Put the vertices and indices into device memory.

    gl->GenBuffers(context, 1, puiVBO);
    gl->GenBuffers(context, 1, puiIBO);

    gl->BindBuffer(context, GL_ARRAY_BUFFER, *puiVBO);
    gl->BufferData(context, GL_ARRAY_BUFFER, sizeof(GLfloat)*(iNumVertices*9), NULL, GL_STATIC_DRAW);
    gl->BufferSubData(context, GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*(iNumVertices*3), pfVertices);
    gl->BufferSubData(context, GL_ARRAY_BUFFER, sizeof(GLfloat)*(iNumVertices*3), sizeof(GLfloat)*(iNumVertices*3), pfTexCoords);
    gl->BufferSubData(context, GL_ARRAY_BUFFER, sizeof(GLfloat)*(iNumVertices*6), sizeof(GLfloat)*(iNumVertices*3), pfNormals);
    gl->BindBuffer(context, GL_ARRAY_BUFFER, 0);

    gl->BindBuffer(context, GL_ELEMENT_ARRAY_BUFFER, *puiIBO);
    gl->BufferData(context, GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort)*iNumIndices, pui16Indices, GL_STATIC_DRAW);
    gl->BindBuffer(context, GL_ELEMENT_ARRAY_BUFFER, 0);

    delete [] pui16Indices;
    delete [] pfVertices;
    delete [] pfTexCoords;

    *piNumIndices = iNumIndices;
    *piNumVertices = iNumVertices;
}
Пример #15
0
void RenderAll(wsWindow *window, guiItem *Items, int nrItems, char *db)
{
    guiItem *item;
    guiImage *image = NULL;
    int i, ofs;

    image_buffer = db;
    image_width  = window->Width;

    for (i = 0; i < nrItems + 1; i++) {
        item = &Items[i];

        switch (item->pressed) {
        case btnPressed:
            ofs = 0;
            break;

        case btnReleased:
            ofs = 1;
            break;

        default:
            ofs = 2;
            break;
        }

        switch (item->type) {
        case itButton:

            PutImage(&item->Bitmap, item->x, item->y, 3, ofs);
            break;

        case itPotmeter:

            if (item->numphases == 1)
                SimplePotmeterPutImage(&item->Bitmap, item->x, item->y, item->value / 100.0);
            else
                PutImage(&item->Bitmap, item->x, item->y, item->numphases, (item->numphases - 1) * (item->value / 100.0));

            break;

        case itHPotmeter:

            if (item->numphases == 1)
                SimplePotmeterPutImage(&item->Bitmap, item->x, item->y, item->value / 100.0);
            else
                PutImage(&item->Bitmap, item->x, item->y, item->numphases, (item->numphases - 1) * (item->value / 100.0));

            PutImage(&item->Mask, item->x + (item->width - item->pwidth) * (item->value / 100.0), item->y, 3, ofs);
            break;

        case itVPotmeter:

            PutImage(&item->Bitmap, item->x, item->y, item->numphases, item->numphases * (1.0 - item->value / 100.0));
            PutImage(&item->Mask, item->x, item->y + (item->height - item->pheight) * (1.0 - item->value / 100.0), 3, ofs);
            break;

        case itSLabel:

            if (item->width == -1)
                item->width = fntTextWidth(item->fontid, item->label);

            image = fntTextRender(item, 0, item->label);

            if (image)
                PutImage(image, item->x, item->y, 1, 0);

            break;

        case itDLabel:
        {
            int x;
            unsigned int d;
            char *t = Translate(item->label);

            if (!item->text || (strcmp(item->text, t) != 0)) {
                free(item->text);
                item->text      = strdup(t);
                item->textwidth = fntTextWidth(item->fontid, t);
                item->starttime = GetTimerMS();
                item->last_x    = 0;
            }

            d = GetTimerMS() - item->starttime;

            if (d < DLABEL_DELAY)
                x = item->last_x;                     // don't scroll yet
            else {
                int l;
                char c[2];

                l    = (item->textwidth ? item->textwidth : item->width);
                x    = (l ? l - ((d - DLABEL_DELAY) / 20) % l - 1 : 0);
                c[0] = *item->text;
                c[1] = '\0';

                if (x < (fntTextWidth(item->fontid, c) + 1) >> 1) {
                    item->starttime = GetTimerMS();   // stop again
                    item->last_x    = x;              // at current x pos
                }
            }

            image = fntTextRender(item, x, t);
        }

            if (image)
                PutImage(image, item->x, item->y, 1, 0);

            break;
        }
    }

    wsImageRender(window, db);
}
Пример #16
0
//---------------------------------------------------------------------------------
// Purpose: Update victim/attacker stats matrix
//---------------------------------------------------------------------------------
void ManiVictimStats::ShowChatStats(player_t *victim_ptr, player_t *attacker_ptr, int mode)
{
	// Normal player, dump stats out to them
	// Show attackers first

	int victim_index = victim_ptr->index - 1;

	if (mani_show_victim_stats_inflicted_only.GetInt() == 0)
	{
		for (int i = 0; i < max_players; i++)
		{
			if (damage_list[victim_index][i].shots_taken == 0)
			{
				continue;
			}

			char hit_groups[1024];

			Q_strcpy(hit_groups, " ");

			if (mode == 2)
			{
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_GENERIC], hit_groups, Translate(victim_ptr, M_VSTATS_BODY));
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_HEAD], hit_groups, Translate(victim_ptr, M_VSTATS_HEAD));
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_CHEST], hit_groups, Translate(victim_ptr, M_VSTATS_CHEST));
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_STOMACH], hit_groups, Translate(victim_ptr, M_VSTATS_STOMACH));
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_LEFTARM], hit_groups, Translate(victim_ptr, M_VSTATS_LEFT_ARM));
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_RIGHTARM], hit_groups, Translate(victim_ptr, M_VSTATS_RIGHT_ARM));
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_LEFTLEG], hit_groups, Translate(victim_ptr, M_VSTATS_LEFT_LEG));
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_RIGHTLEG], hit_groups, Translate(victim_ptr, M_VSTATS_RIGHT_LEG));
				AddHitGroup(damage_list[victim_index][i].hit_groups_taken[HITGROUP_GEAR], hit_groups, Translate(victim_ptr, M_VSTATS_GEAR));
			}

			char attacker_string[256];
			snprintf(attacker_string, sizeof(attacker_string), "%s", Translate(victim_ptr, 1109, "%s%c%c%i%i%s%s",
				damage_list[victim_index][i].name,
				0xC2, 0xBB,
				damage_list[victim_index][i].health_taken/* + damage_list[victim_index][i].armor_taken*/,
				damage_list[victim_index][i].shots_taken,
				(damage_list[victim_index][i].shots_taken == 1) ? Translate(victim_ptr, M_VSTATS_HIT_SINGLE):Translate(victim_ptr, M_VSTATS_HIT_PLURAL),
				hit_groups
				));

			SayToPlayer(ORANGE_CHAT, victim_ptr, "%s", attacker_string);
		}
	}

	for (int i = 0; i < max_players; i++)
	{
		if (damage_list[victim_index][i].shots_inflicted == 0)
		{
			continue;
		}


		if (damage_list[victim_index][i].killed)
		{
			continue;
		}

		char hit_groups[1024];

		Q_strcpy(hit_groups, " ");

		if (mode == 2)
		{
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_GENERIC], hit_groups, Translate(victim_ptr, M_VSTATS_BODY));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_HEAD], hit_groups, Translate(victim_ptr, M_VSTATS_HEAD));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_CHEST], hit_groups, Translate(victim_ptr, M_VSTATS_CHEST));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_STOMACH], hit_groups, Translate(victim_ptr, M_VSTATS_STOMACH));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_LEFTARM], hit_groups, Translate(victim_ptr, M_VSTATS_LEFT_ARM));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_RIGHTARM], hit_groups, Translate(victim_ptr, M_VSTATS_RIGHT_ARM));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_LEFTLEG], hit_groups, Translate(victim_ptr, M_VSTATS_LEFT_LEG));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_RIGHTLEG], hit_groups, Translate(victim_ptr, M_VSTATS_RIGHT_LEG));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_GEAR], hit_groups, Translate(victim_ptr, M_VSTATS_GEAR));
		}

		char victim_string[256];

		snprintf(victim_string, sizeof(victim_string), "%s", Translate(victim_ptr, 1110, "%s%c%c%i%i%s%s",
			damage_list[victim_index][i].name,
			0xC2, 0xBB,
			damage_list[victim_index][i].health_inflicted/* + damage_list[victim_index][i].armor_inflicted*/,
			damage_list[victim_index][i].shots_inflicted,
			(damage_list[victim_index][i].shots_inflicted == 1) ? Translate(victim_ptr, M_VSTATS_HIT_SINGLE):Translate(victim_ptr, M_VSTATS_HIT_PLURAL),
			hit_groups));

		SayToPlayer(ORANGE_CHAT, victim_ptr, "%s", victim_string);
	}

	for (int i = 0; i < max_players; i++)
	{
		if (damage_list[victim_index][i].shots_inflicted == 0)
		{
			continue;
		}


		if (!damage_list[victim_index][i].killed)
		{
			continue;
		}

		char hit_groups[1024];

		Q_strcpy(hit_groups, " ");

		if (mode == 2)
		{
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_GENERIC], hit_groups, Translate(victim_ptr, M_VSTATS_BODY));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_HEAD], hit_groups, Translate(victim_ptr, M_VSTATS_HEAD));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_CHEST], hit_groups, Translate(victim_ptr, M_VSTATS_CHEST));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_STOMACH], hit_groups, Translate(victim_ptr, M_VSTATS_STOMACH));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_LEFTARM], hit_groups, Translate(victim_ptr, M_VSTATS_LEFT_ARM));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_RIGHTARM], hit_groups, Translate(victim_ptr, M_VSTATS_RIGHT_ARM));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_LEFTLEG], hit_groups, Translate(victim_ptr, M_VSTATS_LEFT_LEG));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_RIGHTLEG], hit_groups, Translate(victim_ptr, M_VSTATS_RIGHT_LEG));
			AddHitGroup(damage_list[victim_index][i].hit_groups_inflicted[HITGROUP_GEAR], hit_groups, Translate(victim_ptr, M_VSTATS_GEAR));
		}

		char victim_string[256];

		snprintf(victim_string, sizeof(victim_string), "%s", Translate(victim_ptr, 1111, "%s%s%c%c%i%i%s%s%.2f%.1f%s",
			(damage_list[victim_index][i].headshot) ? Translate(victim_ptr, M_VSTATS_HS):"",
			damage_list[victim_index][i].name,
			0xC2, 0xBB,
			damage_list[victim_index][i].health_inflicted/* + damage_list[victim_index][i].armor_inflicted*/,
			damage_list[victim_index][i].shots_inflicted,
			(damage_list[victim_index][i].shots_inflicted == 1) ? Translate(victim_ptr, M_VSTATS_HIT_SINGLE):Translate(victim_ptr, M_VSTATS_HIT_PLURAL),
			damage_list[victim_index][i].weapon_name,
			damage_list[victim_index][i].distance,
			(damage_list[victim_index][i].distance * 3.28),
			hit_groups
			));

		SayToPlayer(ORANGE_CHAT, victim_ptr, "%s", victim_string);
	}

	if (attacker_ptr == NULL) return;
	if (attacker_ptr->user_id <= 0) return;
	if (attacker_ptr->user_id == victim_ptr->user_id) return;
	// Show attacker health left
	SayToPlayer(ORANGE_CHAT, victim_ptr, "%s", Translate(victim_ptr, 1112, "%s%i", attacker_ptr->name, attacker_ptr->health));
}
Пример #17
0
// host edit
INT_PTR CALLBACK DlgProcDestEdit(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {
	HWND hw;
	int sel;
	char *strptr;

	switch ( msg ) {
	case WM_INITDIALOG: 
		{
			for(int i = ID_STATUS_OFFLINE; i <= ID_STATUS_OUTTOLUNCH; i++) {
				strptr = (char *)CallService(MS_CLIST_GETSTATUSMODEDESCRIPTION, (WPARAM)i, (LPARAM)0);
				hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT);
				SendMessage(hw, CB_INSERTSTRING, (WPARAM)-1, (LPARAM)strptr);
				hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT2);
				SendMessage(hw, CB_INSERTSTRING, (WPARAM)-1, (LPARAM)strptr);
			}

			hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT);
			SendMessage(hw, CB_SETCURSEL, 1, 0);
			hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT2);
			SendMessage(hw, CB_SETCURSEL, 0, 0);

			SetDlgItemText(hwndDlg, IDC_ED_DESTADDR, add_edit_addr.pszName);
			SetDlgItemText(hwndDlg, IDC_ED_DESTLAB, add_edit_addr.pszLabel);
			SetDlgItemText(hwndDlg, IDC_ED_COMMAND, add_edit_addr.pszCommand);
			SetDlgItemText(hwndDlg, IDC_ED_PARAMS, add_edit_addr.pszParams);

			CheckDlgButton(hwndDlg, IDC_CHK_DESTTCP, add_edit_addr.port != -1);
			if(add_edit_addr.port != -1) {
				hw = GetDlgItem(hwndDlg, IDC_ED_DESTPORT);
				EnableWindow(hw, TRUE);
				SetDlgItemInt(hwndDlg, IDC_ED_DESTPORT, add_edit_addr.port, FALSE);
			}
			{
				int num_protocols;
				PROTOCOLDESCRIPTOR **pppDesc;

				CallService(MS_PROTO_ENUMPROTOCOLS, (LPARAM)&num_protocols, (WPARAM)&pppDesc);
				hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTPROTO);
				SendMessage(hw, CB_INSERTSTRING, (WPARAM)-1, (LPARAM)Translate("<none>"));
				SendMessage(hw, CB_INSERTSTRING, (WPARAM)-1, (LPARAM)Translate("<all>"));
				for(int i = 0; i < num_protocols; i++) {
					if(pppDesc[i]->type == PROTOTYPE_PROTOCOL)
						SendMessage(hw, CB_INSERTSTRING, (WPARAM)-1, (LPARAM)pppDesc[i]->szName);
				}

				if(add_edit_addr.pszProto[0] == '\0') {
					SendMessage(hw, CB_SETCURSEL, 0, 0);
				} else {
					SendMessage(hw, CB_SELECTSTRING, 0, (LPARAM)add_edit_addr.pszProto);
					hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT);
					EnableWindow(hw, TRUE);
					SendMessage(hw, CB_SETCURSEL, (WPARAM)(add_edit_addr.set_status - ID_STATUS_OFFLINE), 0);
					hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT2);
					EnableWindow(hw, TRUE);
					SendMessage(hw, CB_SETCURSEL, (WPARAM)(add_edit_addr.get_status - ID_STATUS_OFFLINE), 0);
				}
			}
			// ? doesn't work? ?
			hw = GetDlgItem(hwndDlg, IDC_ED_DESTLAB);
			SetFocus(hw);
		}
		return FALSE;
	case WM_COMMAND:
		if (HIWORD( wParam ) == LBN_SELCHANGE && LOWORD(wParam) == IDC_COMBO_DESTPROTO) {
			hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTPROTO);
			sel = SendMessage(hw, CB_GETCURSEL, 0, 0);
			if(sel != CB_ERR) {
				hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT);
				EnableWindow(hw, sel != 0);
				hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT2);
				EnableWindow(hw, sel != 0);
			}
		}

		if ( HIWORD( wParam ) == BN_CLICKED ) {
			switch( LOWORD( wParam )) {
			case IDC_CHK_DESTTCP:
				hw = GetDlgItem(hwndDlg, IDC_ED_DESTPORT);
				EnableWindow(hw, IsDlgButtonChecked(hwndDlg, IDC_CHK_DESTTCP));
				break;
			case IDOK:
				GetDlgItemText(hwndDlg, IDC_ED_DESTADDR, add_edit_addr.pszName, MAX_PINGADDRESS_STRING_LENGTH);
				GetDlgItemText(hwndDlg, IDC_ED_DESTLAB, add_edit_addr.pszLabel, MAX_PINGADDRESS_STRING_LENGTH);
				GetDlgItemText(hwndDlg, IDC_ED_COMMAND, add_edit_addr.pszCommand, MAX_PATH);
				GetDlgItemText(hwndDlg, IDC_ED_PARAMS, add_edit_addr.pszParams, MAX_PATH);

				hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTPROTO);
				if(SendMessage(hw, CB_GETCURSEL, 0, 0) != -1) {
					GetDlgItemText(hwndDlg, IDC_COMBO_DESTPROTO, add_edit_addr.pszProto, MAX_PINGADDRESS_STRING_LENGTH);
					if(!strcmp(add_edit_addr.pszProto, Translate("<none>"))) add_edit_addr.pszProto[0] = '\0';
					else {
						hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT);
						sel = SendMessage(hw, CB_GETCURSEL, 0, 0);
						if(sel != -1)
							add_edit_addr.set_status = ID_STATUS_OFFLINE + sel;
						hw = GetDlgItem(hwndDlg, IDC_COMBO_DESTSTAT2);
						sel = SendMessage(hw, CB_GETCURSEL, 0, 0);
						if(sel != -1)
							add_edit_addr.get_status = ID_STATUS_OFFLINE + sel;
					}
				} else
					add_edit_addr.pszProto[0] = '\0';

				if(IsDlgButtonChecked(hwndDlg, IDC_CHK_DESTTCP)) {
					BOOL tr;
					int port = GetDlgItemInt(hwndDlg, IDC_ED_DESTPORT, &tr, FALSE);
					if(tr) add_edit_addr.port = port;
					else add_edit_addr.port = -1;
				} else
					add_edit_addr.port = -1;

				EndDialog(hwndDlg, IDOK);
				break;
			case IDCANCEL:
				EndDialog(hwndDlg, IDCANCEL);
				break;
			}
				
		}

		return TRUE;
	}
	return FALSE;
}
Пример #18
0
bool ShowMenuStatsFreePage::Render(player_t *victim_ptr, player_t *attacker_ptr, int timeout)
{
	// Horrible 'goto' hack in here to control output to the amx menu
	// Normal player, dump stats out to them
	// Show attackers first

	int	 menu_index = 1;
	int	 string_size = 0;
	bool found_victim = false;

	int victim_index = victim_ptr->index - 1;

	if ( attacker_ptr )
		this->user_id = attacker_ptr->user_id; // victim is "caller"
	else
		this->user_id = 0;

	this->timeout = timeout;

	if (mani_show_victim_stats_inflicted_only.GetInt() == 0)
	{
		bool found_attacker = false;

		for (int i = 0; i < max_players; i++)
		{
			if (gpManiVictimStats->damage_list[victim_index][i].shots_taken == 0)
			{
				continue;
			}

			// Ignore killer who attacked
			if (attacker_ptr && attacker_ptr->index - 1 == i)
			{
				continue;
			}

			char attacker_string[256];

			string_size += snprintf(attacker_string, sizeof(attacker_string), "%s", Translate(victim_ptr, 1114, "%s%i%i%s",
				gpManiVictimStats->damage_list[victim_index][i].name,
				gpManiVictimStats->damage_list[victim_index][i].health_taken,
				gpManiVictimStats->damage_list[victim_index][i].shots_taken,
				(gpManiVictimStats->damage_list[victim_index][i].shots_taken == 1) ? Translate(victim_ptr, M_VSTATS_HIT_SINGLE):Translate(victim_ptr, M_VSTATS_HIT_PLURAL)
				));

			if (string_size >= 512) goto nasty;
			if (!found_attacker)
			{
				char	menu_index_str[128];

				string_size += snprintf(menu_index_str, sizeof(menu_index_str), "%s", Translate(victim_ptr, 1113 ,"%i", menu_index++));
				if (string_size >= 512) goto nasty;
				DrawMenu (victim_ptr->index, timeout, 7, true, true, true, menu_index_str, false);
			}

			found_attacker = true;
			DrawMenu (victim_ptr->index, timeout, 7, true, true, true, attacker_string, false);
		}
	}

	for (int i = 0; i < max_players; i++)
	{
		if (gpManiVictimStats->damage_list[victim_index][i].shots_inflicted == 0)
		{
			continue;
		}


		if (gpManiVictimStats->damage_list[victim_index][i].killed)
		{
			continue;
		}

		char victim_string[256];

		string_size += snprintf(victim_string, sizeof(victim_string), "%s", Translate(victim_ptr, 1116, "%s%i%i%s",
			gpManiVictimStats->damage_list[victim_index][i].name,
			gpManiVictimStats->damage_list[victim_index][i].health_inflicted/* + damage_list[victim_index][i].armor_inflicted*/,
			gpManiVictimStats->damage_list[victim_index][i].shots_inflicted,
			(gpManiVictimStats->damage_list[victim_index][i].shots_inflicted == 1) ? Translate(victim_ptr, M_VSTATS_HIT_SINGLE):Translate(victim_ptr, M_VSTATS_HIT_PLURAL)
			));
		if (string_size >= 512) goto nasty;
		
		if (!found_victim)
		{
				char	menu_index_str[128];

				string_size += snprintf(menu_index_str, sizeof(menu_index_str), "%s", Translate(victim_ptr, 1115, "%i", menu_index++));
				if (string_size >= 512) goto nasty;
				DrawMenu (victim_ptr->index, timeout, 7, true, true, true, menu_index_str, false);
		}

		found_victim = true;
		DrawMenu (victim_ptr->index, timeout, 7, true, true, true, victim_string, false);
	}

	found_victim = false;

	for (int i = 0; i < max_players; i++)
	{
		if (gpManiVictimStats->damage_list[victim_index][i].shots_inflicted == 0)
		{
			continue;
		}


		if (!gpManiVictimStats->damage_list[victim_index][i].killed)
		{
			continue;
		}

		char victim_string[256];

		string_size += snprintf(victim_string, sizeof(victim_string), "%s", Translate(victim_ptr, 1118, "%s%s%i%i%s%s%.2f%.1f",
			gpManiVictimStats->damage_list[victim_index][i].name,
			(gpManiVictimStats->damage_list[victim_index][i].headshot) ? Translate(victim_ptr, M_VSTATS_HS):" ",
			gpManiVictimStats->damage_list[victim_index][i].health_inflicted/* + damage_list[victim_index][i].armor_inflicted*/,
			gpManiVictimStats->damage_list[victim_index][i].shots_inflicted,
			(gpManiVictimStats->damage_list[victim_index][i].shots_inflicted == 1) ? Translate(victim_ptr, M_VSTATS_HIT_SINGLE):Translate(victim_ptr, M_VSTATS_HIT_PLURAL),
			gpManiVictimStats->damage_list[victim_index][i].weapon_name,
			gpManiVictimStats->damage_list[victim_index][i].distance,
			(gpManiVictimStats->damage_list[victim_index][i].distance * 3.28)
			));

		if (string_size >= 512) goto nasty;

		if (!found_victim)
		{
				char	menu_index_str[128];

				string_size += snprintf(menu_index_str, sizeof(menu_index_str), "%s", Translate(victim_ptr, 1117, "%i", menu_index++));
				if (string_size >= 512) goto nasty;
				DrawMenu (victim_ptr->index, timeout, 7, true, true, true, menu_index_str, false);
		}

		found_victim = true;
		DrawMenu (victim_ptr->index, timeout, 7, true, true, true, victim_string, false);
	}

	if (attacker_ptr && attacker_ptr->user_id > 0 && attacker_ptr->user_id != victim_ptr->user_id)
	{
		char	menu_index_str[128];

		string_size += snprintf(menu_index_str, sizeof(menu_index_str), "%s", Translate(victim_ptr, 1119, "%i", menu_index++));
		if (string_size >= 512) goto nasty;
		DrawMenu (victim_ptr->index, timeout, 7, true, true, true, menu_index_str, false);

		char killer_string[256];

		string_size += snprintf(killer_string, sizeof(killer_string), "%s", Translate(victim_ptr, 1120, "%s%i%i%i%s",
					attacker_ptr->name, 
					attacker_ptr->health,
					gpManiVictimStats->damage_list[victim_index][attacker_ptr->index - 1].health_taken,
					gpManiVictimStats->damage_list[victim_index][attacker_ptr->index - 1].shots_taken,
					(gpManiVictimStats->damage_list[victim_index][attacker_ptr->index - 1].shots_taken == 1) ? Translate(victim_ptr, M_VSTATS_HIT_SINGLE):Translate(victim_ptr, M_VSTATS_HIT_PLURAL)
					));

		if (string_size >= 512) goto nasty;
		DrawMenu (victim_ptr->index, timeout, 7, true, true, true, killer_string, false);
	}

nasty:
	if (string_size > 0)
	{
		DrawMenu (victim_ptr->index, timeout, 7, true, true, true, "", true);
		return true;
	}

	return false;
}
Пример #19
0
void __cdecl CYahooProto::im_sendackfail(HANDLE hContact)
{
	SleepEx(1000, TRUE);
	ProtoBroadcastAck(m_szModuleName, hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, (HANDLE) 1, 
						(LPARAM) Translate("The message send timed out."));
}
Пример #20
0
bool TKPlayerPage::PopulateMenuPage(player_t *player_ptr)
{

	bool	is_bot;
	char	*name;

	this->params.GetParam("is_bot", &is_bot);
	this->params.GetParam("name", &name);

	this->SetEscLink("%s", Translate(player_ptr, 620));
	this->SetTitle("%s", Translate(player_ptr, 631,"%s", name));

	// Some people don't want the forgive option
	if (IsMenuOptionAllowed(MANI_TK_FORGIVE, is_bot))
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 632, AddParam("punish", MANI_TK_FORGIVE));
	}

	// Some people don't want the slay option
	if (IsMenuOptionAllowed(MANI_TK_SLAY, is_bot))
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 633, AddParam("punish", MANI_TK_SLAY));
	}

	// Some people don't want the slap option
	if (IsMenuOptionAllowed(MANI_TK_SLAP, is_bot) && gpManiGameType->IsSlapAllowed())
	{
		MenuItem *ptr = new TKPlayerItem;
		ptr->SetDisplayText("%s", Translate(player_ptr, 634, "%i", mani_tk_slap_to_damage.GetInt()));
		ptr->params.AddParam("punish", MANI_TK_SLAP);
		this->AddItem(ptr);
	}

	// Some people don't want the beacon option
	if (IsMenuOptionAllowed(MANI_TK_BEACON, is_bot) && gpManiGameType->GetAdvancedEffectsAllowed())
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 643, AddParam("punish", MANI_TK_BEACON));
	}

	// Some people don't want the time bomb option
	if (IsMenuOptionAllowed(MANI_TK_TIME_BOMB, is_bot))
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 640, AddParam("punish", MANI_TK_TIME_BOMB));
	}

	// Some people don't want the fire bomb option
	if (IsMenuOptionAllowed(MANI_TK_FIRE_BOMB, is_bot) && gpManiGameType->IsFireAllowed())
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 641, AddParam("punish", MANI_TK_FIRE_BOMB));
	}

	// Some people don't want the freeze bomb option
	if (IsMenuOptionAllowed(MANI_TK_FREEZE_BOMB, is_bot))
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 642, AddParam("punish", MANI_TK_FREEZE_BOMB));
	}

	// Some people don't want the freeze option
	if (IsMenuOptionAllowed(MANI_TK_FREEZE, is_bot))
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 636, AddParam("punish", MANI_TK_FREEZE));
	}

	// Some people don't want the burn option
	if (IsMenuOptionAllowed(MANI_TK_BURN, is_bot)  && gpManiGameType->IsFireAllowed())
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 639, AddParam("punish", MANI_TK_BURN));
	}

	// Some people don't want the cash option
	if (IsMenuOptionAllowed(MANI_TK_CASH, is_bot) && gpManiGameType->CanUseProp(MANI_PROP_ACCOUNT))
	{
		MenuItem *ptr = new TKPlayerItem;
		ptr->SetDisplayText("%s", Translate(player_ptr, 637, "%i", mani_tk_cash_percent.GetInt()));
		ptr->params.AddParam("punish", MANI_TK_CASH);
		this->AddItem(ptr);
	}

	// Some people don't want the drug option
	if (IsMenuOptionAllowed(MANI_TK_DRUG, is_bot) && gpManiGameType->IsDrugAllowed())
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 638, AddParam("punish", MANI_TK_DRUG));
	}

	// Some people don't want the blind option
	if (IsMenuOptionAllowed(MANI_TK_BLIND, is_bot))
	{
		MENUOPTION_CREATE_PARAM(TKPlayerItem, 635, AddParam("punish", MANI_TK_BLIND));
	}

	return true;
}
Пример #21
0
void CYahooProto::ext_got_im(const char *me, const char *who, int protocol, const char *msg, 
								long tm, int stat, int utf8, int buddy_icon, 
								const char *seqn, int sendn)
{
	char 		*umsg;
	const char	*c = msg;
	int 		oidx = 0;
	CCSDATA 		ccs;
	PROTORECVEVENT 	pre;
	HANDLE 			hContact;


	LOG(("YAHOO_GOT_IM id:%s %s: %s (len: %d) tm:%lu stat:%i utf8:%i buddy_icon: %i", me, who, msg, lstrlenA(msg), tm, stat, utf8, buddy_icon));

	if(stat == 2) {
		char z[1024];

		snprintf(z, sizeof z, "Error sending message to %s", who);
		LOG((z));
		ShowError(Translate("Yahoo Error"), z);
		return;
	}

	if(!msg) {
		LOG(("Empty Incoming Message, exiting."));
		return;
	}

	if (GetByte( "IgnoreUnknown", 0 )) {

		/*
		* Check our buddy list to see if we have it there. And if it's not on the list then we don't accept any IMs.
		*/
		if (getbuddyH(who) == NULL) {
			LOG(("Ignoring unknown user messages. User '%s'. Dropping Message.", who));
			return;
		}
	}

	if ( BuddyIgnored( who )) {
		LOG(("User '%s' on our Ignore List. Dropping Message.", who));
		return;
	}

	// make a bigger buffer for \n -> \r\n conversion (x2)
	umsg = (char *) alloca(lstrlenA(msg) * 2 + 1); 

	while ( *c != '\0') {
		// Strip the font tag
		if (!_strnicmp(c,"<font ",6) || !_strnicmp(c,"</font>",6) ||
			// strip the fade tag
			!_strnicmp(c, "<FADE ",6) || !_strnicmp(c,"</FADE>",7) ||
			// strip the alternate colors tag
			!_strnicmp(c, "<ALT ",5) || !_strnicmp(c, "</ALT>",6)){ 
				while ((*c++ != '>') && (*c != '\0')); 
		} else
			// strip ANSI color combination
			if ((*c == 0x1b) && (*(c+1) == '[')){ 
				while ((*c++ != 'm') && (*c != '\0')); 
			} else

				if (*c != '\0'){
					umsg[oidx++] = *c;

					/* Adding \r to \r\n conversion */
					if (*c == '\r' && *(c + 1) != '\n') 
						umsg[oidx++] = '\n';

					c++;
				}
	}

	umsg[oidx++]= '\0';

	/* Need to strip off formatting stuff first. Then do all decoding/converting */
	LOG(("%s: %s", who, umsg));

	//if(!strcmp(umsg, "<ding>")) 
	//	:P("\a");

	ccs.szProtoService = PSR_MESSAGE;
	ccs.hContact = hContact = add_buddy(who, who, protocol, PALF_TEMPORARY);
	//SetWord(hContact, "yprotoid", protocol);
	Set_Protocol(hContact, protocol);

	ccs.wParam = 0;
	ccs.lParam = (LPARAM) &pre;
	pre.flags = (utf8) ? PREF_UTF : 0;

	if (tm) {
		HANDLE hEvent = (HANDLE)CallService(MS_DB_EVENT_FINDLAST, (WPARAM)hContact, 0);

		if (hEvent) { // contact has events
			DBEVENTINFO dbei;
			DWORD dummy;

			dbei.cbSize = sizeof (DBEVENTINFO);
			dbei.pBlob = (BYTE*)&dummy;
			dbei.cbBlob = 2;
			if (!CallService(MS_DB_EVENT_GET, (WPARAM)hEvent, (LPARAM)&dbei)) 
				// got that event, if newer than ts then reset to current time
				if ((DWORD)tm < dbei.timestamp) tm = (long)time(NULL);
		}

		pre.timestamp = (DWORD)time(NULL);
		
		if ((DWORD)tm < pre.timestamp)
			pre.timestamp = tm;
		
	} else
		pre.timestamp = (DWORD)time(NULL);

	pre.szMessage = umsg;
	pre.lParam = 0;

	// Turn off typing
	CallService(MS_PROTO_CONTACTISTYPING, (WPARAM) hContact, PROTOTYPE_CONTACTTYPING_OFF);
	CallService(MS_PROTO_CHAINRECV, 0, (LPARAM) & ccs);

	// ack the message we just got
	if (seqn)
		yahoo_send_im_ack(m_id, me, who, seqn, sendn);

	if (buddy_icon < 0) return;

	//?? Don't generate floods!!
	DBWriteContactSettingByte(hContact, m_szModuleName, "AvatarType", (BYTE)buddy_icon);
	if (buddy_icon != 2) {
		reset_avatar(hContact);
	} else if (DBGetContactSettingDword(hContact, m_szModuleName,"PictCK", 0) == 0) {
		/* request the buddy image */
		request_avatar(who); 
	} 
}
Пример #22
0
SceneGraph::SceneGraph(Model *_model, mat4 _prepareRotationMatrix, mat4 _modelOffset) {
  model = _model;
  prepareRotationMatrix = _prepareRotationMatrix;
  applyRotationMatrix = Translate(0.0, 0.0, 0.0);
  modelOffset = _modelOffset;
}
Пример #23
0
int TlenMUCRecvError(const char *from, XmlNode *errorNode) 
{
	int errCode;
	char str[512];
	JABBER_LIST_ITEM *item;
	MUCCEVENT mucce;
	mucce.cbSize = sizeof(MUCCEVENT);
	mucce.iType = MUCC_EVENT_ERROR;
	mucce.pszID = from;
	mucce.pszModule = jabberProtoName;
	errCode = atoi(JabberXmlGetAttrValue(errorNode, "code"));
	switch (errCode) {
		case 403:
			sprintf(str, Translate("You cannot join this chat room, because you are banned."));
			break;
		case 404:
			sprintf(str, Translate("Chat room not found."));
			break;
		case 407:
			sprintf(str, Translate("This is a private chat room and you are not one of the members."));
			break;
		case 408:
			sprintf(str, Translate("You cannot send any message unless you join this chat room."));
			break;
		case 410: 
			sprintf(str, Translate("Chat room with already created."));
			break;
		case 411: 
			sprintf(str, Translate("Nickname '%s' is already registered."),
				JabberXmlGetAttrValue(errorNode, "n"));
			break;
		case 412:
			sprintf(str, Translate("Nickname already in use, please try another one. Hint: '%s' is free."),
				JabberXmlGetAttrValue(errorNode, "free"));
			break;
		case 413:
			sprintf(str, Translate("You cannot register more than %s nicknames."),
				JabberXmlGetAttrValue(errorNode, "num"));
			break;
		case 414:
			sprintf(str, Translate("You cannot create more than %s chat rooms."),
				JabberXmlGetAttrValue(errorNode, "num"));
			break;
		case 415:
			sprintf(str, Translate("You cannot join more than %s chat rooms."),
				JabberXmlGetAttrValue(errorNode, "num"));
			break;
		case 601:
			sprintf(str, Translate("Anonymous nicknames are not allowed in this chat room."));
			break;
		default:
			sprintf(str, Translate("Unknown error code : %d"), errCode);
			break;
	}
	mucce.pszText = str;
	CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
	if (jabberOnline) {
		switch (errCode) {
			case 412:
				item = JabberListGetItemPtr(LIST_CHATROOM, from);
				if (item!=NULL) {
					mucce.iType = MUCC_EVENT_JOIN;
					mucce.dwFlags = MUCC_EF_ROOM_NICKNAMES;
					mucce.pszModule = jabberProtoName;
					mucce.pszID = from;
					mucce.pszName = item->roomName;
					mucce.pszNick = JabberXmlGetAttrValue(errorNode, "free");
					CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
				}
				break;
			case 601:
				item = JabberListGetItemPtr(LIST_CHATROOM, from);
				if (item!=NULL) {
					mucce.iType = MUCC_EVENT_JOIN;
					mucce.dwFlags = 0;
					mucce.pszModule = jabberProtoName;
					mucce.pszID = from;
					mucce.pszName = item->roomName;
					mucce.pszNick = NULL;
					CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
				}
				break;
		}
	}
	return 1;
}
Пример #24
0
// Encode the rectangle using zlib compression
inline UINT
vncEncodeZlib::EncodeOneRect(BYTE *source, BYTE *dest, const RECT &rect)
{
	int totalCompDataLen = 0;
	int previousTotalOut;
	int deflateResult;

	const int rectW = rect.right - rect.left;
	const int rectH = rect.bottom - rect.top;
	const int rawDataSize = (rectW*rectH*m_remoteformat.bitsPerPixel / 8);
	const int maxCompSize = (rawDataSize + (rawDataSize/100) + 8);

	// Send as raw if the update is too small to compress.
	if (rawDataSize < VNC_ENCODE_ZLIB_MIN_COMP_SIZE)
		return vncEncoder::EncodeRect(source, dest, rect, offsetx, offsety);

	// Create the rectangle header
	rfbFramebufferUpdateRectHeader *surh=(rfbFramebufferUpdateRectHeader *)dest;
	surh->r.x = (CARD16) rect.left ;
	surh->r.y = (CARD16) rect.top ;
	surh->r.w = (CARD16) (rectW);
	surh->r.h = (CARD16) (rectH);
	surh->r.x = Swap16IfLE(surh->r.x- offsetx);
	surh->r.y = Swap16IfLE(surh->r.y- offsety);
	surh->r.w = Swap16IfLE(surh->r.w);
	surh->r.h = Swap16IfLE(surh->r.h);
	surh->encoding = Swap32IfLE(rfbEncodingZlib);

	dataSize += ( rectW * rectH * m_remoteformat.bitsPerPixel) / 8;
	rectangleOverhead += sz_rfbFramebufferUpdateRectHeader;
	
	// create a space big enough for the Zlib encoded pixels
	if (m_bufflen < rawDataSize)
	{
		if (m_buffer != NULL)
		{
			delete [] m_buffer;
			m_buffer = NULL;
		}
		m_buffer = new BYTE [rawDataSize+1];
		if (m_buffer == NULL)
			return vncEncoder::EncodeRect(source, dest, rect, offsetx, offsety);
		m_bufflen = rawDataSize;
	}

	// Translate the data into our new buffer
	Translate(source, m_buffer, rect);

	// Initialize input/output buffer assignment for compressor state.
	compStream.avail_in = rawDataSize;
	compStream.next_in = m_buffer;
	compStream.avail_out = maxCompSize;
	compStream.next_out = (dest+sz_rfbFramebufferUpdateRectHeader+sz_rfbZlibHeader);
	compStream.data_type = Z_BINARY;

	// If necessary, the first time, initialize the compressor state.
	if ( compStreamInited == false )
	{

		compStream.total_in = 0;
		compStream.total_out = 0;
		compStream.zalloc = Z_NULL;
		compStream.zfree = Z_NULL;
		compStream.opaque = Z_NULL;

		vnclog.Print(LL_INTINFO, VNCLOG("calling deflateInit2 with zlib level:%d\n"), m_compresslevel);

		deflateResult = deflateInit2( &compStream,
			                          m_compresslevel,
					                  Z_DEFLATED,
					                  MAX_WBITS,
					                  MAX_MEM_LEVEL,
					                  Z_DEFAULT_STRATEGY );
		if ( deflateResult != Z_OK )
		{
			vnclog.Print(LL_INTINFO, VNCLOG("deflateInit2 returned error:%d:%s\n"), deflateResult, compStream.msg);
			return vncEncoder::EncodeRect(source, dest, rect, offsetx, offsety);
		}
		compStreamInited = true;
	}

	// Record previous total output size.
	previousTotalOut = compStream.total_out;

	// Compress the raw data into the result buffer.
	deflateResult = deflate( &compStream, Z_SYNC_FLUSH );

	if ( deflateResult != Z_OK )
	{
		vnclog.Print(LL_INTINFO, VNCLOG("deflate returned error:%d:%s\n"), deflateResult, compStream.msg);
		return vncEncoder::EncodeRect(source, dest, rect, offsetx, offsety);
	}

	// Calculate size of compressed data.
	totalCompDataLen = compStream.total_out - previousTotalOut;

	// Format the ZlibHeader
	rfbZlibHeader *zlibh=(rfbZlibHeader *)(dest+sz_rfbFramebufferUpdateRectHeader);
	zlibh->nBytes = Swap32IfLE(totalCompDataLen);

	// Update statistics
	encodedSize += sz_rfbZlibHeader + totalCompDataLen;

	// Return the amount of data sent	
	return sz_rfbFramebufferUpdateRectHeader +
		   sz_rfbZlibHeader +
		   totalCompDataLen;

}
Пример #25
0
WCHAR *ParseMultipartBody(char *src, char *bond)
{
	char *srcback = _strdup(src);
	size_t sizebond = strlen(bond);
	int numparts = 1;
	int i;
	char *courbond = srcback;
	WCHAR *dest;
	for (;(courbond=strstr(courbond,bond));numparts++,courbond+=sizebond);
	APartDataType *partData = new APartDataType[numparts];
	memset(partData, 0, sizeof(APartDataType)*numparts);
	partData[0].Src = courbond = srcback;
	for (i=1;(courbond=strstr(courbond,bond));i++,courbond+=sizebond) {
		*(courbond-2) = 0;
		partData[i].Src = courbond+sizebond;
		while (ENDLINE(partData[i].Src)) partData[i].Src++;
	}
	size_t resultSize=0;
	for (i=0;i<numparts;i++) {
		ParseAPart(&partData[i]);
		if (partData[i].body) {
			if (partData[i].TransEnc) {
				if (!_stricmp(partData[i].TransEnc,"base64")) partData[i].TransEncType=TE_BASE64;
				else if (!_stricmp(partData[i].TransEnc,"quoted-printable"))partData[i].TransEncType=TE_QUOTEDPRINTABLE;
			}
			if (partData[i].ContType) {
				char *CharSetStr;
				if (NULL != (CharSetStr=ExtractFromContentType(partData[i].ContType,"charset=")))
				{
					partData[i].CodePage=GetCharsetFromString(CharSetStr,strlen(CharSetStr));
					delete[] CharSetStr;
				}
			}
			if (partData[i].ContType && !_strnicmp(partData[i].ContType,"text",4)) {
				char *localBody=0;
				switch (partData[i].TransEncType) {
					case TE_BASE64:
					{
						int size =partData[i].bodyLen*3/4+5;
						localBody = new char[size+1];
						DecodeBase64(partData[i].body,localBody,size); 
					}break;
					case TE_QUOTEDPRINTABLE:
					{
						int size = partData[i].bodyLen+2;
						localBody = new char[size+1];
						DecodeQuotedPrintable(partData[i].body,localBody,size,FALSE); 
					}break;
				}
				ConvertStringToUnicode(localBody?localBody:partData[i].body,partData[i].CodePage,&partData[i].wBody);
				if (localBody) delete[] localBody;
			} else if (partData[i].ContType && !_strnicmp(partData[i].ContType,"multipart/",10)) {
				//Multipart in mulitipart recursive? should be SPAM. Ah well
				char *bondary=NULL;
				if (NULL != (bondary=ExtractFromContentType(partData[i].ContType,"boundary=")))
				{
					partData[i].wBody = ParseMultipartBody(partData[i].body,bondary);
					delete[] bondary;
				} else goto FailBackRaw; //multipart with no boundary? badly formatted messages.
			} else {
FailBackRaw:
				ConvertStringToUnicode(partData[i].body,partData[i].CodePage,&partData[i].wBody);
			}
			resultSize += wcslen(partData[i].wBody);
		}// if (partData[i].body)
		resultSize += 100+4+3; //cr+nl+100+ 3*bullet
	}
	dest = new WCHAR[resultSize+1];
	size_t destpos = 0;
	for (i=0;i<numparts;i++) {
		if (i) { // part before first boudary should not have headers
			char infoline[1024]; size_t linesize = 0;
			mir_snprintf(infoline, SIZEOF(infoline), "%s %d", Translate("Part"), i);
			linesize = strlen(infoline);
			if (partData[i].TransEnc) {
				mir_snprintf(infoline + linesize, SIZEOF(infoline) - linesize, "; %s", partData[i].TransEnc);
				linesize = strlen(infoline);
			}
			if (partData[i].ContType) {
				char *CharSetStr=strchr(partData[i].ContType,';');
				if (CharSetStr) {
					CharSetStr[0]=0;
					mir_snprintf(infoline + linesize, SIZEOF(infoline) - linesize, "; %s", partData[i].ContType);
					linesize = strlen(infoline);
					partData[i].ContType=CharSetStr+1;
					if (NULL != (CharSetStr=ExtractFromContentType(partData[i].ContType,"charset="))) {
						mir_snprintf(infoline + linesize, SIZEOF(infoline) - linesize, "; %s", CharSetStr);
						linesize = strlen(infoline);
						delete[] CharSetStr;
					}
					if (NULL != (CharSetStr=ExtractFromContentType(partData[i].ContType,"name="))) {
						mir_snprintf(infoline + linesize, SIZEOF(infoline) - linesize, "; \"%s\"", CharSetStr);
						linesize = strlen(infoline);
						delete[] CharSetStr;
					}
				}
				else {
					mir_snprintf(infoline + linesize, SIZEOF(infoline) - linesize, "; %s", partData[i].ContType);
					linesize = strlen(infoline);
				}
			}
			mir_snprintf(infoline + linesize, SIZEOF(infoline) - linesize, ".\r\n");
			{
				WCHAR *temp=0;
				dest[destpos] = dest[destpos+1] = dest[destpos+2] = 0x2022; // bullet;
				destpos += 3;
				ConvertStringToUnicode(infoline,CP_ACP,&temp);
				size_t wsize = wcslen(temp);
				wcscpy(&dest[destpos],temp);
				destpos += wsize;
				delete[] temp;
			}
		} // if (i)

		if (partData[i].wBody) {
			size_t wsize = wcslen(partData[i].wBody);
			wcscpy(&dest[destpos],partData[i].wBody);
			destpos += wsize;
			delete[] partData[i].wBody;
		}
	}

	free (srcback);
	delete[] partData;
	dest[resultSize] = 0;//just in case
	return dest;
}
Пример #26
0
		void GDIPlus::DrawFilledRect( gwen::Rect rect )
		{
			Translate( rect );
			Gdiplus::SolidBrush solidBrush( m_Colour );
			graphics->FillRectangle( &solidBrush, rect.x, rect.y, rect.w, rect.h );
		}
Пример #27
0
DWORD WINAPI BadConnection(LPVOID Param)
{
	MSG msg;
	HWND hBadConnect;
	HACCOUNT ActualAccount;
	struct BadConnectionParam MyParam;
	NOTIFYICONDATA nid;
	char *NotIconText = Translate(" - connection error"), *src;
	TCHAR *dest;
	int i;

	MyParam=*(struct BadConnectionParam *)Param;
	ActualAccount=MyParam.account;
#ifdef DEBUG_SYNCHRO
	DebugLog(SynchroFile,"BadConnect:Incrementing \"using threads\" %x (account %x)\n",ActualAccount->UsingThreads,ActualAccount);
#endif
	SCIncFcn(ActualAccount->UsingThreads);

//	we will not use params in stack anymore
	SetEvent(MyParam.ThreadRunningEV);

	__try
	{
		hBadConnect=CreateDialogParam(YAMNVar.hInst,MAKEINTRESOURCE(IDD_DLGBADCONNECT),NULL,DlgProcYAMNBadConnection,(LPARAM)&MyParam);
		SendMessage(hBadConnect,WM_SETICON,ICON_BIG,(LPARAM)g_LoadIconEx(3));
		SendMessage(hBadConnect,WM_SETICON,ICON_SMALL,(LPARAM)g_LoadIconEx(3));

		ZeroMemory(&nid,sizeof(nid));
		nid.cbSize=sizeof(NOTIFYICONDATA);
		nid.hWnd=hBadConnect;
		nid.hIcon=g_LoadIconEx(3);
		nid.uID=0;
		nid.uFlags=NIF_ICON | NIF_MESSAGE | NIF_TIP;
		nid.uCallbackMessage=WM_YAMN_NOTIFYICON;

#ifdef DEBUG_SYNCHRO
		DebugLog(SynchroFile,"BadConnect:ActualAccountSO-read wait\n");
#endif
		if (WAIT_OBJECT_0 != WaitToReadFcn(ActualAccount->AccountAccessSO))
		{
#ifdef DEBUG_SYNCHRO
			DebugLog(SynchroFile,"BadConnect:ActualAccountSO-read wait failed\n");
#endif
			return 0;
		}
#ifdef DEBUG_SYNCHRO
		DebugLog(SynchroFile,"BadConnect:ActualAccountSO-read enter\n");
#endif
		for (src=ActualAccount->Name,dest=nid.szTip,i=0;(*src != (TCHAR)0) && (i+1<sizeof(nid.szTip));*dest++=*src++);
		for (src=NotIconText;(*src != (TCHAR)0) && (i+1<sizeof(nid.szTip));*dest++=*src++);
		*dest=(TCHAR)0;

		if (ActualAccount->BadConnectN.Flags & YAMN_ACC_SND)
			CallService(MS_SKIN_PLAYSOUND,0,(LPARAM)YAMN_CONNECTFAILSOUND);
		if (ActualAccount->BadConnectN.Flags & YAMN_ACC_MSG)
			ShowWindow(hBadConnect,SW_SHOWNORMAL);
		if (ActualAccount->BadConnectN.Flags & YAMN_ACC_ICO)
			Shell_NotifyIcon(NIM_ADD,&nid);
#ifdef DEBUG_SYNCHRO
		DebugLog(SynchroFile,"BadConnect:ActualAccountSO-read done\n");
#endif
		ReadDoneFcn(ActualAccount->AccountAccessSO);

		UpdateWindow(hBadConnect);
		while(GetMessage(&msg,NULL,0,0))
		{
			TranslateMessage(&msg); 
			DispatchMessage(&msg);  
		}

//	now, write to file. Why? Because we want to write when was new mail last checked
		if ((ActualAccount->Plugin->Fcn != NULL) && (ActualAccount->Plugin->Fcn->WriteAccountsFcnPtr != NULL) && ActualAccount->AbleToWork)
			ActualAccount->Plugin->Fcn->WriteAccountsFcnPtr();
	}
	__finally
	{
#ifdef DEBUG_SYNCHRO
		DebugLog(SynchroFile,"BadConnect:Decrementing \"using threads\" %x (account %x)\n",ActualAccount->UsingThreads,ActualAccount);
#endif
		SCDecFcn(ActualAccount->UsingThreads);
	}
	return 0;
}
Пример #28
0
CMUSHclientDoc::CMUSHclientDoc()
  :	m_eventScriptFileChanged(FALSE, TRUE)

{    // constructor

int i;

  // each document will have a unique number
  m_iUniqueDocumentNumber = App.GetUniqueNumber ();

  AllocateConfigurationArrays ();

  m_bTrace = false;   // not tracing yet

// note - these initialisations merely make the hash lookup more efficient.
// until v 3.21 they were the default of 20, so this should help somewhat
// The number should be a prime number, hence the strange figures.

  m_VariableMap.InitHashTable (997); // allow for 1000 variables (at least)
  m_AliasMap.InitHashTable (293);    // probably won't have many more than 300 aliases
  m_TriggerMap.InitHashTable (293);  // probably won't have many more than 300 triggers
  m_TimerMap.InitHashTable (293);    // probably won't have many more than 300 timers

  SetDefaults (false);        // set up numeric/boolean defaults
  SetAlphaDefaults (false);   // set up alpha defaults

  m_strWorldID = GetUniqueID ();      // default world ID

  m_CurrentPlugin = NULL;     // no plugin active right now

  m_iBackgroundMode = 0;
  m_iForegroundMode = 0;
  m_iBackgroundColour = NO_COLOUR;

  m_TextRectangle = CRect (0, 0, 0, 0);
  m_TextRectangleBorderOffset = 0;           
  m_TextRectangleBorderColour = 0;           
  m_TextRectangleBorderWidth = 0;            
  m_TextRectangleOutsideFillColour = 0;      
  m_TextRectangleOutsideFillStyle = 0;   

  m_iCurrentActionSource = eUnknownActionSource;
  m_nBytesIn = 0;
  m_nBytesOut = 0;
  m_bTabCompleteFunctions = true;
  m_hSpecialFontHandle = 0;

  m_iTriggersEvaluatedCount = 0; 
  m_iTriggersMatchedCount = 0;   
  m_iAliasesEvaluatedCount = 0;  
  m_iAliasesMatchedCount = 0;    
  m_iTimersFiredCount = 0;       
  m_iTriggersMatchedThisSessionCount = 0;   
  m_iAliasesMatchedThisSessionCount = 0;    
  m_iTimersFiredThisSessionCount = 0;       

  m_bLoaded = false;
  m_bMapping = false;
  m_bRemoveMapReverses = true;
  m_MapFailureRegexp = NULL;
  m_bPluginProcessingCommand = false;
  m_bPluginProcessingSend = false;
  m_bPluginProcessingSent = false;
  m_iLastCommandCount = 0;
  m_iExecutionDepth = 0;
  m_iNextChatID = 0;
  m_tLastMessageTime = 0;
  m_tLastGroupMessageTime = 0;
  m_bOmitFromCommandHistory = false;
  m_bUTF_8 = false;
  m_bWorldClosing = false;
  m_bInSendToScript = true;

  m_bInPlaySoundFilePlugin = false;
  m_bInCancelSoundFilePlugin = false;

  m_strStatusMessage = Translate ("Ready");
  m_bShowingMapperStatus = false;
  m_iMCCP_type = 0;
  m_bSupports_MCCP_2 = false;
  m_bNoEcho = false;
  m_bDebugIncomingPackets = false;
  m_iInputPacketCount = 0;
  m_iOutputPacketCount = 0;
  m_iUTF8ErrorCount = 0;
  m_lastGoTo = 1;
  m_bNAWS_wanted = false;
  m_bCHARSET_wanted = false;
  m_bSuppressNewline = false;
  m_echo_colour = 9;
  m_bAlwaysRecordCommandHistory = false;
  m_bDoNotShowOutstandingLines = false;
  m_bDoNotTranslateIACtoIACIAC = false;
  m_bAutoResizeCommandWindow = false;
  m_iAutoResizeMinimumLines = 1;   
  m_iAutoResizeMaximumLines = 20;   
  m_bDoNotAddMacrosToCommandHistory = false;
  m_bCopySelectionToClipboard = false;
  m_bCarriageReturnClearsLine = false;
  m_bConvertGAtoNewline = false;
  m_bSendMXP_AFK_Response = true;
  m_bMudCanChangeOptions = true;
//  m_bShowGridLinesInListViews = true;  // NB - app-wide :P
  m_bEnableSpamPrevention = false;
  m_strSpamMessage = "look";
  m_iSpamLineCount = 20;
  m_iLastOutgoingChatPort = DEFAULT_CHAT_PORT;

  m_iSocksProcessing = 0;   // no socks processing wanted
  m_iProxyServerPort = 1080; // default socks port

  // deprecated options  - set to zero for saving comparison (for XML testing)

  m_page_colour = 0;
  m_whisper_colour= 0;
  m_mail_colour = 0;
  m_game_colour = 0;
  m_chat_colour = 0;
  m_remove_channels1 = 0;
  m_remove_channels2 = 0;
  m_remove_pages= 0;
  m_remove_whispers = 0;
  m_remove_set= 0;
  m_remove_mail = 0;
  m_remove_game = 0;

  // things I found to be not initialised in version 3.43

  m_timestamps = 0;
  m_iFlags1 = 0;
  m_iFlags2 = 0;
  m_iListMode = 0;
  m_iListCount = 0;
  m_iMXP_previousMode = eMXP_open;
  m_code = 0;

  // sound buffers
  for (i = 0; i < MAX_SOUND_BUFFERS; i++)
    m_pDirectSoundSecondaryBuffer [i] = NULL;

  /*---------------------------------------------------------
  I want to be able to time speed walking delays (for pulling things
  out of the list, so I need a window that can take timer events, however
  a CDocument isn't a window. Thus, I'll make a hidden window for this
  specific purpose.

  I previously had speed walking tied to the CSendView window but this was
  pretty crappy, because you could have multiple send views, thus the timers
  would be all over the shop, and it was very fiddly when firing a "send" from
  a trigger, because a trigger is not related to a particular send view.

  --------------------------------------------------------- */


  // create window that we can use for firing timers
  m_pTimerWnd = new CTimerWnd (this);

	m_pTimerWnd->m_hWnd = NULL;
	if (!m_pTimerWnd->CreateEx(0, AfxRegisterWndClass(0),
		_T("Document timer window"),
		WS_OVERLAPPED, 0, 0, 0, 0, NULL, NULL))
	  {
		TRACE0("Warning: unable to create document timer window!\n");
		AfxThrowResourceException();
  	}
	ASSERT(m_pTimerWnd->m_hWnd != NULL);
	ASSERT(CWnd::FromHandlePermanent(m_pTimerWnd->m_hWnd) == m_pTimerWnd);


  for (i = 0; i < 8; i++)  
    m_font [i] = NULL;
  m_input_font = NULL;
  m_FontHeight = 0;
  m_FontWidth = 0;
  m_InputFontHeight = 0;
  m_InputFontWidth = 0;
  m_total_lines = 0;
  m_last_line_with_IAC_GA = 0;
  m_nTotalLinesSent = 0;
  m_nTotalLinesReceived = 0;
  m_phase = NONE;
  m_version = VERSION;

  m_bVariablesChanged = false;

  m_view_number = 0;
  m_LastFlushTime = CTime::GetCurrentTime();

  m_bCompress = false;    // no compression yet
  m_bCompressInitOK = false;
  m_CompressInput = NULL;
  m_CompressOutput = NULL;

  // initialise zlib decompression 

  m_zCompress.next_in = Z_NULL; 
  m_zCompress.avail_in = 0; 
  m_zCompress.zalloc = Z_NULL; 
  m_zCompress.zfree = Z_NULL; 
  m_zCompress.opaque = Z_NULL; 
  m_nTotalUncompressed = 0;
  m_nTotalCompressed = 0;
  m_iCompressionTimeTaken = 0;

  // we will defer initialising zlib until we really have to

	m_pSocket = NULL;
  m_pChatListenSocket = NULL;    // no listening socket
  m_logfile = NULL;
  m_match_width = 30;

  m_bSelected = true;

  m_bNotesInRGB = false;    // notes are in palette colour right now
  m_iNoteStyle = NORMAL;    // notes are not bold right now

// MXP

  m_bMXP = false;   // no MXP yet
  m_bPuebloActive = false; // no Pueblo yet either <evil grin>
  m_bInParagraph = false;
  m_bMXP_script = false;
  m_bPreMode = false;
  m_iMXP_defaultMode = eMXP_open;
  m_iMXP_mode = m_iMXP_defaultMode;
  m_cLastChar = 0;

  // initial styles

  m_iFlags = 0;
  m_iForeColour = WHITE;
  m_iBackColour = BLACK;

  if (m_bCustom16isDefaultColour)
    {
    m_iForeColour = 15;   // use custom colour 16
    m_iBackColour = 15;
    m_iFlags |= COLOUR_CUSTOM;
    }

//  m_normalcolour [BLACK]    = RGB (192, 192, 192) | PALETTE;    // black   
//  m_normalcolour [RED]      = RGB (128,   0,  64) | PALETTE;    // red     
//  m_normalcolour [GREEN]    = RGB (128, 255, 128) | PALETTE;    // green   
//  m_normalcolour [YELLOW]   = RGB (255, 255, 128) | PALETTE;    // yellow  
//  m_normalcolour [BLUE]     = RGB (  0, 255, 255) | PALETTE;    // blue    
//  m_normalcolour [MAGENTA]  = RGB (255,   0, 128) | PALETTE;    // magenta 
//  m_normalcolour [CYAN]     = RGB (128, 255, 255) | PALETTE;    // cyan    
//  m_normalcolour [WHITE]    = RGB (  0, 128,   0) | PALETTE;    // white   

//  m_boldcolour [BLACK]      = RGB (  0,   0,   0) |  PALETTE;    // black   
//  m_boldcolour [RED]        = RGB (255,   0,   0) |  PALETTE;    // red     
//  m_boldcolour [GREEN]      = RGB (  0, 255,   0) |  PALETTE;    // green   
//  m_boldcolour [YELLOW]     = RGB (255, 255,   0) |  PALETTE;    // yellow  
//  m_boldcolour [BLUE]       = RGB (  0,  64, 128) |  PALETTE;    // blue    
//  m_boldcolour [MAGENTA]    = RGB (255,   0, 255) |  PALETTE;    // magenta 
//  m_boldcolour [CYAN]       = RGB (  0, 255, 255) |  PALETTE;    // cyan    
//  m_boldcolour [WHITE]      = RGB (255, 255, 255) |  PALETTE;    // white   

  // better use ANSI colours as the default

  SetDefaultAnsiColours (m_normalcolour, m_boldcolour);

  // and some nice custom colours
  SetDefaultCustomColours (m_customtext, m_customback);

  // default custom colour names
  for (i = 0; i < NUMITEMS (m_strCustomColourName); i++)
    m_strCustomColourName [i].Format ("Custom%i", i + 1);

  for (i = 0; i < NUMITEMS (m_macro_type); i++)
    m_macro_type [i] = SEND_NOW;

// printer styles for printing from the screen

  for (i = 0; i < 8; i++)
    {
     m_nNormalPrintStyle [i] = 0;
     m_nBoldPrintStyle [i] = FONT_BOLD;
    }

  m_bUseDefaultOutputFont = !App.m_strDefaultOutputFont.IsEmpty (); 

  m_bUseDefaultColours   = !App.m_strDefaultColoursFile.IsEmpty ();   
  m_bUseDefaultTriggers  = !App.m_strDefaultTriggersFile.IsEmpty ();   
  m_bUseDefaultAliases   = !App.m_strDefaultAliasesFile.IsEmpty ();    
  m_bUseDefaultMacros    = !App.m_strDefaultMacrosFile.IsEmpty ();     
  m_bUseDefaultTimers    = !App.m_strDefaultTimersFile.IsEmpty ();     
  m_bUseDefaultInputFont = !App.m_strDefaultInputFont.IsEmpty ();  
  
  setupstrings ();

  m_tStatusTime = CTime::GetCurrentTime(); 
  m_tConnectTime = CTime::GetCurrentTime();
  m_tLastPlayerInput = CTime::GetCurrentTime();
  m_timeScriptFileMod = 0;

  m_tsConnectDuration = CTimeSpan (0, 0, 0, 0);

  m_iConnectPhase = eConnectNotConnected;
                                      
  gdoccount++;

  m_pActiveCommandView = NULL;
  m_pActiveOutputView = NULL;

  m_new_lines = 0;

  m_last_prefs_page = 1;

  App.m_bUpdateActivity = TRUE;

// for looking up host names

  ZeroMemory (&m_sockAddr, sizeof m_sockAddr);
  ZeroMemory (&m_ProxyAddr, sizeof m_ProxyAddr);
  m_hNameLookup = NULL;
  m_pGetHostStruct = NULL;
  m_pLinePositions = NULL;

  m_pCurrentLine = NULL;
  m_total_lines = 0;

  // set up the dialog box headings for the finding dialogs
  m_DisplayFindInfo.m_strTitle    = "Find in output buffer...";
  m_MacrosFindInfo.m_strTitle     = "Find macro...";
  m_AliasesFindInfo.m_strTitle    = "Find alias...";
  m_TriggersFindInfo.m_strTitle   = "Find trigger...";
  m_TimersFindInfo.m_strTitle     = "Find timer...";
  m_VariablesFindInfo.m_strTitle  = "Find variable...";
  m_NotesFindInfo.m_strTitle  = "Find in notes...";
  m_RecallFindInfo.m_strTitle    = "Recall...";
          
  m_bRecallCommands = true;
  m_bRecallOutput = true;
  m_bRecallNotes = true;

  // set up column counts for use in the loading and saving of the column orders etc.
  m_MacrosFindInfo.m_iControlColumns    = CPrefsP6::eColumnCount;
  m_AliasesFindInfo.m_iControlColumns   = CPrefsP7::eColumnCount;
  m_TriggersFindInfo.m_iControlColumns  = CPrefsP8::eColumnCount;
  m_TimersFindInfo.m_iControlColumns    = CPrefsP16::eColumnCount;
  m_VariablesFindInfo.m_iControlColumns = CPrefsP18::eColumnCount;

  m_bDisconnectOK = true;    // so we don't try to reconnect to prematurely
  
  m_iMXPerrors = 0;     
  m_iMXPtags = 0;       
  m_iMXPentities = 0;   

  // scripting support

	EnableAutomation();     // not needed?

  if (!bWine)
  	AfxOleLockApp();        // not needed?

  m_ScriptEngine = NULL;

  m_bInScriptFileChanged = false;
  m_pThread = NULL;
  m_bSyntaxErrorOnly = false;

  m_dispidWorldOpen = DISPID_UNKNOWN;
  m_dispidWorldClose = DISPID_UNKNOWN;
  m_dispidWorldSave = DISPID_UNKNOWN;
  m_dispidWorldConnect = DISPID_UNKNOWN;
  m_dispidWorldDisconnect = DISPID_UNKNOWN;
  m_dispidWorldGetFocus = DISPID_UNKNOWN;
  m_dispidWorldLoseFocus = DISPID_UNKNOWN;
  m_dispidOnMXP_Start = DISPID_UNKNOWN;        
  m_dispidOnMXP_Stop = DISPID_UNKNOWN;         
  m_dispidOnMXP_OpenTag = DISPID_UNKNOWN;      
  m_dispidOnMXP_CloseTag = DISPID_UNKNOWN;     
  m_dispidOnMXP_SetVariable = DISPID_UNKNOWN;  
  m_dispidOnMXP_Error = DISPID_UNKNOWN;    

  m_iScriptTimeTaken = 0;   // time taken on scripts

  m_bPluginProcessesOpenTag = false;    
  m_bPluginProcessesCloseTag = false;   
  m_bPluginProcessesSetVariable = false;
  m_bPluginProcessesSetEntity = false;
  m_bPluginProcessesError = false;      

  ZeroMemory (&m_bClient_IAC_DO, sizeof m_bClient_IAC_DO);
  ZeroMemory (&m_bClient_IAC_DONT, sizeof m_bClient_IAC_DONT);
  ZeroMemory (&m_bClient_IAC_WILL, sizeof m_bClient_IAC_WILL);
  ZeroMemory (&m_bClient_IAC_WONT, sizeof m_bClient_IAC_WONT);

  // set up some default triggers for MUSHes

  /*
  The parameter are:

  Trigger Name
  Match Text 
  Response Text 
  Flags 
  Colour 
  Wildcard to copy to clipboard
  Sound File Name 
  Script Name
  */

  /*  No, don't. It just confuses Diku MUD people

  AddTrigger ("Game_messages", "GAME:*", "", eEnabled, 0, 0, "", ""); 
  AddTrigger ("Page_poses", "From afar,*", "", eEnabled, 1, 0, "", ""); 
  AddTrigger ("Pages", "^\\w+ pages.*$", "", eEnabled | eTriggerRegularExpression, 1, 0, "", ""); 
  AddTrigger ("Whisper_poses", "You sense:*", "", eEnabled, 2, 0, "", ""); 
  AddTrigger ("Whispers", "^\\w+ whispers.*$", "", eEnabled | eTriggerRegularExpression, 2, 0, "", ""); 
  AddTrigger ("Mail_messages", "MAIL:*", "", eEnabled, 3, 0, "", ""); 
  AddTrigger ("Chat_channel_1", "^\\<.+?\\>.*$", "", eEnabled | eTriggerRegularExpression, 4, 0, "", ""); 
  AddTrigger ("Chat_channel_2", "^\\[.+?\\].*$", "", eEnabled | eTriggerRegularExpression, 4, 0, "", ""); 
  */

  m_nextAcceleratorCommand = ACCELERATOR_FIRST_COMMAND;
  m_accelerator = NULL;

}  // end of CMUSHclientDoc::CMUSHclientDoc()
Пример #29
0
// MsnSendMessage - sends the message to a server
int __cdecl CMsnProto::SendMsg(MCONTACT hContact, int flags, const char* pszSrc)
{
	const char *errMsg = NULL;

	if (!msnLoggedIn) {
		errMsg = Translate("Protocol is offline");
		ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, 999999, errMsg, this));
		return 999999;
	}

	char tEmail[MSN_MAX_EMAIL_LEN];
	if (MSN_IsMeByContact(hContact, tEmail)) {
		errMsg = Translate("You cannot send message to yourself");
		ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, 999999, errMsg, this));
		return 999999;
	}

	char *msg = (char*)pszSrc;
	if (msg == NULL)
		return 0;

	int rtlFlag = (flags & PREF_RTL) ? MSG_RTL : 0;

	int seq = 0;
	int netId = Lists_GetNetId(tEmail);

	switch (netId) {
	case NETID_MOB:
		if (mir_strlen(msg) > 133) {
			errMsg = Translate("Message is too long: SMS page limited to 133 UTF8 chars");
			seq = 999997;
		}
		else {
			errMsg = NULL;
			seq = msnNsThread->sendMessage('1', tEmail, netId, msg, rtlFlag);
		}
		ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, seq, errMsg, this));
		break;

	case NETID_YAHOO:
		if (mir_strlen(msg) > 1202) {
			seq = 999996;
			errMsg = Translate("Message is too long: MSN messages are limited by 1202 UTF8 chars");
			ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, seq, errMsg, this));
		}
		else {
			seq = msnNsThread->sendMessage('1', tEmail, netId, msg, rtlFlag);
			ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, seq, NULL, this));
		}
		break;

	default:
		if (mir_strlen(msg) > 1202) {
			seq = 999996;
			errMsg = Translate("Message is too long: MSN messages are limited by 1202 UTF8 chars");
			ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, seq, errMsg, this));
		}
		else {
#ifdef OBSOLETE
			const char msgType = MyOptions.SlowSend ? 'A' : 'N';
			bool isOffline;
			ThreadData *thread = MSN_StartSB(tEmail, isOffline);
#else
			/* MSNP24 doesn't have a switchboard anymore */
			bool isOffline = true;
			ThreadData *thread = NULL;
#endif

			if (thread == NULL) {
				if (isOffline) {
					if (netId != NETID_LCS) {
						seq = msnNsThread->sendMessage('1', tEmail, netId, msg, rtlFlag | MSG_OFFLINE);
						ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, seq, NULL, this));
					}
					else {
						seq = 999993;
						errMsg = Translate("Offline messaging is not allowed for LCS contacts");
						ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, seq, errMsg, this));
					}
				}
#ifdef OBSOLETE
				else
					seq = MsgQueue_Add(tEmail, msgType, msg, 0, 0, rtlFlag);
			}
			else {
				seq = thread->sendMessage(msgType, tEmail, netId, msg, rtlFlag);
				if (!MyOptions.SlowSend)
					ForkThread(&CMsnProto::MsnFakeAck, new TFakeAckParams(hContact, seq, NULL, this));
#endif
			}
		}
		break;
	}

	return seq;
}
Пример #30
0
static INT_PTR icqGetName(WPARAM wParam, LPARAM lParam)
{
    strncpy((char*)lParam, Translate(protoName), wParam);
    return 0;
}