Example #1
0
void *SearchDialog::processEvent(Event *e)
{
    switch (e->type()){
    case EventClientsChanged:
    case EventClientChanged:
        fillClients();
        break;
	case EventCommandExec:{
		CommandDef *cmd = (CommandDef*)(e->param());
		if (cmd->menu_id == MenuSearchGroups){
			Group *grp = getContacts()->group(cmd->id - CmdContactGroup);
			if (grp){
				Contact *contact = NULL;
				if ((QWidget*)(cmd->param) == m_search->btnSearch){
            if (m_current){
                connect(this, SIGNAL(createContact(unsigned,Contact*&)), m_current, SLOT(createContact(unsigned,Contact*&)));
                emit createContact(CONTACT_TEMP, contact);
                disconnect(this, SIGNAL(createContact(unsigned,Contact*&)), m_current, SLOT(createContact(unsigned,Contact*&)));
            }
				}else{
					contact = createContact(CONTACT_TEMP);
				}
				if (contact){
					if ((contact->getFlags() & CONTACT_TEMP) == 0){
						QString err = i18n("%1 already in contact list") .arg(contact->getName());
						if ((QWidget*)(cmd->param) == m_search->btnAdd){
							BalloonMsg::message(err, m_search->btnAdd);
						}else if ((QWidget*)(cmd->param) == m_search->btnSearch){
							BalloonMsg::message(err, m_search->btnSearch);
						}else{
							QRect rc = m_result->itemRect((QListViewItem*)(e->param()));
							QPoint p = m_result->viewport()->mapToGlobal(QPoint(rc.left(), rc.top()));
							rc = QRect(p.x(), p.y(), rc.width(), rc.height());
							BalloonMsg::message(err, m_result, false, 150, &rc);
						}
						return e->param();
					}
					contact->setFlags(contact->getFlags() & ~CONTACT_TEMP);
					contact->setGroup(grp->id());
					Event e(EventContactChanged, contact);
					e.process();
				}
			}
			return e->param();
		}
		if (cmd->id == CmdSearchInfo){
	Contact *contact = createContact(CONTACT_TEMP);
	if (contact == NULL)
		return e->param();
	Command cmd;
	cmd->id		 = CmdInfo;
	cmd->menu_id = MenuContact;
	cmd->param   = (void*)(contact->id());
	CorePlugin::m_plugin->showInfo(cmd);
	return e->param();
		}
		if (cmd->id == CmdSearchMsg){
	Contact *contact = createContact(CONTACT_TEMP);
	if (contact == NULL)
		return e->param();
                Message *m = new Message(MessageGeneric);
                m->setContact(contact->id());
                Event e(EventOpenMessage, &m);
                e.process();
                delete m;
		}
		break;
		}
Example #2
0
bool NameServiceOnTriples::cmdQuery(NameTripleState& act, bool nested) {
    ConstString port = act.cmd.get(1).asString();

    ParseName parser;
    parser.apply(port.c_str());
    port = parser.getPortName();

    /*
    // port names may be prefixed - sort that out
    string base = port.c_str();
    string pat = "";
    if (base.find("/net=") == 0 || base.find("/NET=") == 0) {
        int patStart = 5;
        int patEnd = base.find('/',patStart);
        if (patEnd>=patStart) {
            pat = base.substr(patStart,patEnd-patStart);
            base = base.substr(patEnd);
        }
        port = base.c_str();
    }
    */

    if (act.reply.size()==0 && !act.bottleMode) {
        act.reply.addString("old");
    }
    Bottle& q=(act.bottleMode&&!act.nestedMode)?
        act.reply :
        act.reply.addList();
    Contact c = query(port.c_str(),act,parser.getNetworkChoice(),nested);
    string host = c.getHost().c_str();
    string carrier = c.getCarrier().c_str();
    int sock = c.getPort();
    if (c.isValid()) {
        if (!act.bottleMode) {
            q.addString("registration");
            q.addString("name");
            q.addString(port.c_str());
            q.addString("ip");
            q.addString(host.c_str());
            q.addString("port");
            q.addInt(sock);
            q.addString("type");
            q.addString(carrier.c_str());
        } else {
            Bottle bname;
            bname.addString("name");
            bname.addString(port.c_str());
            Bottle bip;
            bip.addString("ip");
            bip.addString(host.c_str());
            Bottle bnum;
            bnum.addString("port_number");
            bnum.addInt(sock);
            Bottle bcarrier;
            bcarrier.addString("carrier");
            bcarrier.addString(carrier.c_str());
            q.addString("port");
            q.addList() = bname;
            q.addList() = bip;
            q.addList() = bnum;
            q.addList() = bcarrier;
        }
    } else {
        if (act.bottleMode) {
            Bottle bstate;
            bstate.addString("error");
            bstate.addInt(-2);
            bstate.addString("port not known");
            q.addString("port");
            q.addList() = bstate;
        }
    }
    return true;
}
Example #3
0
Contact NameServiceOnTriples::query(const yarp::os::ConstString& portName, 
                                    NameTripleState& act,
                                    const yarp::os::ConstString& prefix,
                                    bool nested) {
    if (!nested) lock();
    Triple t;
    t.setNameValue("port",portName.c_str());
    int result = act.mem.find(t,NULL);
    TripleContext context;
    context.setRid(result);
    if (result!=-1) {
        string host = "";
        if (string(prefix)!="") {
            printf("LOOKING AT IPS FOR %s\n", prefix.c_str());
            t.setNameValue("ips","*");
            list<Triple> lst = act.mem.query(t,&context);
            for (list<Triple>::iterator it=lst.begin();it!=lst.end();it++) {
                printf("LOOKING AT IPS %s\n", it->value.c_str());
                if (it->value.find(prefix)==0) {
                    host = it->value;
                    break;
                }
            }
        }
        if (host=="") {
            t.setNameValue("host","*");
            list<Triple> lst = act.mem.query(t,&context);
            if (lst.size()>0) {
                host = lst.begin()->value.c_str();
            }
        }
        if (host=="") {
            host = "localhost";
        }
        t.setNameValue("socket","*");
        list<Triple> lst = act.mem.query(t,&context);
        int sock = 10000;
        if (lst.size()>0) {
            sock = atoi(lst.begin()->value.c_str());
        }
        t.setNameValue("carrier","*");
        string carrier = "tcp";
        lst = act.mem.query(t,&context);
        if (lst.size()>0) {
            carrier = lst.begin()->value.c_str();
        }
        t.setNameValue("type","*");
        string typ = "*";
        lst = act.mem.query(t,&context);
        if (lst.size()>0) {
            typ = lst.begin()->value.c_str();
        }
        if (!nested) unlock();
        Contact result = Contact::byName(portName).addSocket(carrier.c_str(),
                                                             host.c_str(),
                                                             sock);
        if (typ!="" && typ!="*") {
            NestedContact nc;
            nc.fromString(result.getName());
            nc.setTypeName(typ);
            result.setNested(nc);
        }
        return result;
    }
    if (!nested) unlock();
    if (delegate && !nested) {
        return delegate->queryName(portName);
    }
    return Contact::invalid();
}
Example #4
0
void *ICQSearchResult::processEvent(Event *e)
{
    if ((e->type() > EventUser) && m_id && (m_id != SEARCH_FAIL)){
        ICQPlugin *plugin = static_cast<ICQPlugin*>(m_client->protocol()->plugin());
        if (e->type() == plugin->EventSearch){
            SearchResult *result = (SearchResult*)(e->param());
            if ((result->id == m_id) && (result->client == m_client)){
                new UserTblItem(tblUser, m_client, &result->data);
                m_nFound++;
                setStatus();
            }
        }
        if (e->type() == plugin->EventSearchDone){
            SearchResult *result = (SearchResult*)(e->param());
            if ((result->id == m_id) && (result->client == m_client))
                setRequestId(0);
        }
    }
    if (e->type() == EventCommandExec){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->menu_id == static_cast<ICQPlugin*>(m_client->protocol()->plugin())->MenuSearchResult){
            Contact *contact;
            if (cmd->id == static_cast<ICQPlugin*>(m_client->protocol()->plugin())->CmdSendMessage){
                contact = createContact(CONTACT_TEMP);
                if (!contact) return NULL;
                Message msg(MessageGeneric);
                msg.setContact(contact->id());
                Event e(EventOpenMessage, &msg);
                e.process();
            }
            if (cmd->id == CmdInfo){
                contact = createContact(CONTACT_TEMP);
                if (!contact) return NULL;
                m_client->addFullInfoRequest(atol(tblUser->currentItem()->text(0).latin1()), true);
                Command cmd;
                cmd->id = CmdInfo;
                cmd->menu_id = MenuContact;
                cmd->param   = (void*)contact->id();
                Event e(EventCommandExec, cmd);
                e.process();
            }
            return e->param();
        }
        if (cmd->menu_id == static_cast<ICQPlugin*>(m_client->protocol()->plugin())->MenuGroups){
            Contact *contact = createContact(0);
            if (!contact) return NULL;
            contact->setGroup(cmd->id - 1);
            Event eContact(EventContactChanged, contact);
            eContact.process();
            return e->param();
        }
    }
    if (e->type() == EventCheckState){
        CommandDef *cmd = (CommandDef*)(e->param());
        if ((cmd->menu_id == static_cast<ICQPlugin*>(m_client->protocol()->plugin())->MenuGroups) &&
            (cmd->id == static_cast<ICQPlugin*>(m_client->protocol()->plugin())->CmdGroups)){
            unsigned n = 1;
            ContactList::GroupIterator it;
            while (++it)
                n++;
            CommandDef *cmds = new CommandDef[n];
            memset(cmds, 0, sizeof(CommandDef) * n);
            n = 0;
            it.reset();
            Group *grp;
            while ((grp = ++it) != NULL){
                cmds[n].id		 = grp->id() + 1;
                cmds[n].text	 = "_";
                QString name = grp->getName();
                if (grp->id() == 0)
                    name = i18n("Not in list");
                cmds[n].text_wrk = strdup(name.utf8());
                n++;
            }
            cmd->param = cmds;
            cmd->flags |= COMMAND_RECURSIVE;
            return e->param();
        }
    }
    return NULL;
}
Example #5
0
bool ForwardPlugin::processEvent(Event *e)
{
    if (e->type() == eEventMessageReceived){
        EventMessage *em = static_cast<EventMessage*>(e);
        Message *msg = em->msg();
        if (msg->type() == MessageStatus)
            return false;
        QString text = msg->getPlainText();
        if (text.isEmpty())
            return false;
        if (msg->type() == MessageSMS){
            SMSMessage *sms = static_cast<SMSMessage*>(msg);
            QString phone = sms->getPhone();
            bool bMyPhone;
            SIM::PropertyHubPtr data = getContacts()->getUserData("forward");
            bMyPhone = ContactList::cmpPhone(phone, data->value("Phone").toString());
            if (!bMyPhone){
                Group *grp;
                ContactList::GroupIterator it;
                while ((grp = ++it) != NULL){
                    data = grp->getUserData("forward", false);
                    if (data && !data->value("Phone").toString().isEmpty()){
                        bMyPhone = ContactList::cmpPhone(phone, data->value("Phone").toString());
                        break;
                    }
                }
            }
            if (!bMyPhone){
                Contact *contact;
                ContactList::ContactIterator it;
                while ((contact = ++it) != NULL){
                    data = contact->getUserData("forward", false);
                    if (data && !data->value("Phone").toString().isEmpty())
                    {
                        bMyPhone = ContactList::cmpPhone(phone, data->value("Phone").toString());
                        break;
                    }
                }
            }
            if (bMyPhone){
                int n = text.indexOf(": ");
                if (n > 0){
                    QString name = text.left(n);
                    QString msg_text = text.mid(n + 2);
                    Contact *contact;
                    ContactList::ContactIterator it;
                    while ((contact = ++it) != NULL){
                        if (contact->getName() == name){
                            Message *msg = new Message(MessageGeneric);
                            msg->setContact(contact->id());
                            msg->setText(msg_text);
                            void *data;
                            ClientDataIterator it(contact->clientData);
                            while ((data = ++it) != NULL){
                                if (it.client()->send(msg, data))
                                    break;
                            }
                            if (data == NULL)
                                delete msg;
                            return true;
                        }
                    }
                }
            }
        }
        Contact *contact = getContacts()->contact(msg->contact());
        if (contact == NULL)
            return false;
        SIM::PropertyHubPtr data = contact->getUserData("forward");
        if (!data || data->value("Key").toString().isEmpty())
            return false;
        CorePlugin *core = GET_CorePlugin();
        unsigned status = core->getManualStatus();
        if ((status == STATUS_AWAY) || (status == STATUS_NA)){
            text = contact->getName() + ": " + text;
            unsigned flags = MESSAGE_NOHISTORY;
            if (data->value("Send1st").toBool())
                flags |= MESSAGE_1ST_PART;
            if (data->value("Translit").toBool())
                flags |= MESSAGE_TRANSLIT;
            SMSMessage *m = new SMSMessage;
            m->setPhone(data->value("Phone").toString());
            m->setText(text);
            m->setFlags(flags);
            unsigned i;
            for (i = 0; i < getContacts()->nClients(); i++){
                Client *client = getContacts()->getClient(i);
                if (client->send(m, NULL))
                    break;
            }
            if (i >= getContacts()->nClients())
                delete m;
        }
    }
    return false;
}
Example #6
0
void *Container::processEvent(Event *e)
{
    UserWnd *userWnd;
    Contact *contact;
    CommandDef *cmd;
    Message *msg;
    switch (e->type()){
    case EventMessageReceived:
        msg = (Message*)(e->param());
        if (msg->type() == MessageStatus){
            contact = getContacts()->contact(msg->contact());
            if (contact)
                contactChanged(contact);
            return NULL;
        }
        if (CorePlugin::m_plugin->getContainerMode()){
            if (isActiveWindow()){
                userWnd = m_tabBar->currentWnd();
                if (userWnd && (userWnd->id() == msg->contact()))
                    userWnd->markAsRead();
            }
#ifdef WIN32
            if (!isActiveWindow()){
                msg = (Message*)(e->param());
                userWnd = wnd(msg->contact());
                if (userWnd){
                    if (!initFlash){
                        HINSTANCE hLib = GetModuleHandleA("user32");
                        if (hLib != NULL)
                            (DWORD&)FlashWindowEx = (DWORD)GetProcAddress(hLib,"FlashWindowEx");
                        initFlash = true;
                    }
                    if (FlashWindowEx){
                        FLASHWINFO fInfo;
                        fInfo.cbSize = sizeof(fInfo);
                        fInfo.dwFlags = 0x0E;
                        fInfo.hwnd = winId();
                        fInfo.uCount = 0;
                        FlashWindowEx(&fInfo);
                    }
                }
            }
#endif
        }
    case EventMessageRead:
        msg = (Message*)(e->param());
        userWnd = wnd(msg->contact());
        if (userWnd){
            bool bBold = false;
            for (list<msg_id>::iterator it = CorePlugin::m_plugin->unread.begin(); it != CorePlugin::m_plugin->unread.end(); ++it){
                if ((*it).contact != msg->contact())
                    continue;
                bBold = true;
                break;
            }
            m_tabBar->setBold(msg->contact(), bBold);
        }
        break;
    case EventActiveContact:
        if (!isActiveWindow())
            return NULL;
        userWnd = m_tabBar->currentWnd();
        if (userWnd)
            return (void*)(userWnd->id());
        break;
    case EventContactDeleted:
        contact = (Contact*)(e->param());
        userWnd = wnd(contact->id());
        if (userWnd)
            removeUserWnd(userWnd);
        break;
    case EventContactChanged:
        contact = (Contact*)(e->param());
        userWnd = wnd(contact->id());
        if (userWnd){
            if (contact->getIgnore()){
                removeUserWnd(userWnd);
                break;
            }
            m_tabBar->changeTab(contact->id());
            contactChanged(contact);
        }
    case EventClientsChanged:
        setupAccel();
        break;
    case EventContactStatus:
        contact = (Contact*)(e->param());
        userWnd = m_tabBar->wnd(contact->id());
        if (userWnd){
            unsigned style = 0;
            string wrkIcons;
            const char *statusIcon = NULL;
            contact->contactInfo(style, statusIcon, &wrkIcons);
            bool bTyping = false;
            while (!wrkIcons.empty()){
                if (getToken(wrkIcons, ',') == "typing"){
                    bTyping = true;
                    break;
                }
            }
            if (userWnd->m_bTyping != bTyping){
                userWnd->m_bTyping = bTyping;
                if (bTyping){
                    userWnd->setStatus(i18n("Contact typed message"));
                }else{
                    userWnd->setStatus("");
                }
                userWnd = m_tabBar->currentWnd();
                if (userWnd && (contact->id() == userWnd->id()))
                    m_status->message(userWnd->status());
            }
        }
        break;
    case EventContactClient:
        contactChanged((Contact*)(e->param()));
        break;
    case EventInit:
        init();
        break;
    case EventCommandExec:
        cmd = (CommandDef*)(e->param());
        userWnd = m_tabBar->currentWnd();
        if (userWnd && ((unsigned)(cmd->param) == userWnd->id())){
            if (cmd->menu_id == MenuContainerContact){
                m_tabBar->raiseTab(cmd->id);
                return e->param();
            }
            if (cmd->id == CmdClose){
                delete userWnd;
                return e->param();
            }
            if (cmd->id == CmdInfo){
                CommandDef c = *cmd;
                c.menu_id = MenuContact;
                c.param   = (void*)userWnd->id();
                Event eExec(EventCommandExec, &c);
                eExec.process();
                return e->param();
            }
        }
        break;
    case EventCheckState:
        cmd = (CommandDef*)(e->param());
        userWnd = m_tabBar->currentWnd();
        if (userWnd && ((unsigned)(cmd->param) == userWnd->id()) &&
                (cmd->menu_id == MenuContainerContact) &&
                (cmd->id == CmdContainerContacts)){
            list<UserWnd*> userWnds = m_tabBar->windows();
            CommandDef *cmds = new CommandDef[userWnds.size() + 1];
            memset(cmds, 0, sizeof(CommandDef) * (userWnds.size() + 1));
            unsigned n = 0;
            for (list<UserWnd*>::iterator it = userWnds.begin(); it != userWnds.end(); ++it){
                cmds[n].id = (*it)->id();
                cmds[n].flags = COMMAND_DEFAULT;
                cmds[n].text_wrk = strdup((*it)->getName().utf8());
                cmds[n].icon  = (*it)->getIcon();
                cmds[n].text  = "_";
                cmds[n].menu_id = n + 1;
                if (n < sizeof(accels) / sizeof(const char*))
                    cmds[n].accel = accels[n];
                if (*it == m_tabBar->currentWnd())
                    cmds[n].flags |= COMMAND_CHECKED;
                n++;
            }
            cmd->param = cmds;
            cmd->flags |= COMMAND_RECURSIVE;
            return e->param();
        }
        break;
    }
    return NULL;
}
Example #7
0
void *OSDPlugin::processEvent(Event *e)
{
    OSDRequest osd;
    Contact *contact;
    Message *msg;
    OSDUserData *data;
    switch (e->type()){
    case EventContactOnline:
        contact = (Contact*)(e->param());
        if (contact->getIgnore()) break;
        osd.contact = contact->id();
        osd.type    = OSD_ALERT;
        queue.push_back(osd);
        processQueue();
        break;
    case EventMessageDeleted:
    case EventMessageRead:
    case EventMessageReceived:
        msg = (Message*)(e->param());
        if (msg->type() == MessageStatus)
            break;
        contact = getContacts()->contact(msg->contact());
        if (contact == NULL)
            break;
        data = (OSDUserData*)(contact->getUserData(user_data_id));
        if (data == NULL)
            break;
        osd.type    = OSD_MESSAGE;
        osd.contact = msg->contact();
        if ((m_request.type == OSD_MESSAGE) && (m_request.contact == msg->contact())){
            queue.push_front(osd);
            m_timer->stop();
            m_timer->start(100);
        }else{
            queue.push_back(osd);
            processQueue();
        }
        break;
    case EventContactStatus:
        contact = (Contact*)(e->param());
        if (contact->getIgnore()) break;
        data = (OSDUserData*)(contact->getUserData(user_data_id));
        if (data){
            unsigned style = 0;
            string wrkIcons;
            const char *statusIcon = NULL;
            contact->contactInfo(style, statusIcon, &wrkIcons);
            bool bTyping = false;
            while (!wrkIcons.empty()){
                if (getToken(wrkIcons, ',') == "typing"){
                    bTyping = true;
                    break;
                }
            }
            if (bTyping){
                list<unsigned>::iterator it;
                for (it = typing.begin(); it != typing.end(); ++it)
                    if ((*it) == contact->id())
                        break;
                if (it == typing.end()){
                    typing.push_back(contact->id());
                    osd.contact = contact->id();
                    osd.type    = OSD_TYPING;
                    queue.push_back(osd);
                    processQueue();
                }
            }else{
                list<unsigned>::iterator it;
                for (it = typing.begin(); it != typing.end(); ++it)
                    if ((*it) == contact->id())
                        break;
                if (it != typing.end())
                    typing.erase(it);
                if ((m_request.type == OSD_TYPING) && (m_request.contact == contact->id())){
                    m_timer->stop();
                    m_timer->start(100);
                }
            }
        }
        break;
    }
    return NULL;
}
Example #8
0
void ICQClient::snac_lists(unsigned short type, unsigned short seq)
{
    switch (type){
    case ICQ_SNACxLISTS_ERROR:
        break;
    case ICQ_SNACxLISTS_RIGHTS:
        log(L_DEBUG, "List rights");
        break;
    case ICQ_SNACxLISTS_ROSTER:{
            char c;
            unsigned short list_len;
            log(L_DEBUG,"Rosters");
            m_socket->readBuffer >> c;
            if (c){
                log(L_WARN, "Bad first roster byte %02X", c);
                break;
            }
            bool bIgnoreTime = false;
            if (!m_bRosters){
                m_bRosters = true;
                setContactsInvisible(0);
                Group *grp;
                ContactList::GroupIterator it_g;
                while ((grp = ++it_g) != NULL){
                    ICQUserData *data;
                    ClientDataIterator it(grp->clientData, this);
                    while ((data = (ICQUserData*)(++it)) != NULL){
                        if (data->IcqID == 0){
                            data->bChecked = true;
                            continue;
                        }
                        data->bChecked = false;
                    }
                }
                Contact *contact;
                ContactList::ContactIterator it_c;
                while ((contact = ++it_c) != NULL){
                    ICQUserData *data;
                    ClientDataIterator it(contact->clientData, this);
                    while ((data = (ICQUserData*)(++it)) != NULL){
                        data->bChecked = false;
                        data->GrpId = 0;
                        data->IgnoreId = 0;
                        data->VisibleId = 0;
                        data->InvisibleId = 0;
                    }
                }
            }
            m_socket->readBuffer >> list_len;
            for (unsigned i = 0; i < list_len; i++){
                string str;
                unsigned short id, grp_id, type, len;
                m_socket->readBuffer.unpackStr(str);
                m_socket->readBuffer >> grp_id >> id >> type >> len;
                TlvList *inf = NULL;
                if (len){
                    Buffer b(len);
                    b.pack(m_socket->readBuffer.data(m_socket->readBuffer.readPos()), len);
                    m_socket->readBuffer.incReadPos(len);
                    inf = new TlvList(b);
                }
                switch (type){
                case ICQ_USER: {
                        if (str.length()){
                            log(L_DEBUG, "User %s", str.c_str());
                            // check for own uin in contact lsit
                            if (atol(str.c_str()) == getUin()) {
                                log(L_DEBUG, "Own Uin in contact list - removing!");
                                seq = sendRoster(ICQ_SNACxLISTS_DELETE, "", grp_id, id);
                                m_listRequest = new ContactServerRequest(seq, number(id).c_str(), 0, 0);
                                break;
                            }
                            ListRequest *lr = findContactListRequest(str.c_str());
                            if (lr){
                                log(L_DEBUG, "Request found");
                                lr->icq_id = id;
                                lr->grp_id = grp_id;
                                Contact *contact;
                                ICQUserData *data = findContact(lr->screen.c_str(), NULL, false, contact);
                                if (data){
                                    data->IcqID = id;
                                    data->GrpId = grp_id;
                                }
                            }else{
                                bool bChanged = false;
                                string alias;
                                Tlv *tlv_name = NULL;
                                if (inf) tlv_name = (*inf)(TLV_ALIAS);
                                if (tlv_name)
                                    alias = (char*)(*tlv_name);
                                log(L_DEBUG, "User %s [%s] - %u", str.c_str(), alias.c_str(), grp_id);
                                Contact *contact;
                                Group *grp = NULL;
                                ICQUserData *data = findGroup(grp_id, NULL, grp);
                                data = findContact(str.c_str(), alias.c_str(), true, contact, grp);
                                if (inf && (*inf)(TLV_WAIT_AUTH)){
                                    if (!data->WaitAuth){
                                        data->WaitAuth = true;
                                        bChanged = true;
                                    }
                                }
                                data->IcqID = id;
                                data->GrpId = grp_id;
                                Tlv *tlv_phone = NULL;
                                if (inf) tlv_phone = (*inf)(TLV_CELLULAR);
                                if (tlv_phone){
                                    set_str(&data->Cellular, *tlv_phone);
                                    string phone = trimPhone(*tlv_phone);
                                    QString phone_str = quoteChars(QString::fromUtf8(phone.c_str()), ",");
                                    phone_str += ",Private Cellular,";
                                    phone_str += number(CELLULAR).c_str();
                                    bChanged |= contact->setPhones(phone_str, NULL);
                                }else{
                                    set_str(&data->Cellular, NULL);
                                }
                                if (atol(str.c_str()) == getUin()) {
                                    log(L_DEBUG,"Own Uin in contact list");
                                    Event e(EventContactDeleted, contact);
                                    e.process();
                                    break;
                                }
                                if (bChanged){
                                    Event e(EventContactChanged, contact);
                                    e.process();
                                }
                                if ((data->InfoFetchTime == 0) && data->Uin)
                                    addFullInfoRequest(data->Uin);
                            }
                        }else{
                            bIgnoreTime = true;
                        }
                        break;
                    }
                case ICQ_GROUPS:{
                        if (str.size() == 0) break;
                        log(L_DEBUG, "group %s %u", str.c_str(), grp_id);
                        ListRequest *lr = findGroupListRequest(grp_id);
                        if (lr){
                            lr->icq_id = grp_id;
                        }else{
                            Group *grp;
                            ICQUserData *data = findGroup(grp_id, str.c_str(), grp);
                            data->IcqID = grp_id;
                            data->bChecked = true;
                            if (grp->getName() != QString::fromUtf8(str.c_str())){
                                grp->setName(QString::fromUtf8(str.c_str()));
                                Event e(EventGroupChanged, grp);
                                e.process();
                            }
                        }
                        break;
                    }
                case ICQ_VISIBLE_LIST:{
                        if (str.length()){
                            log(L_DEBUG, "Visible %s", str.c_str());
                            ListRequest *lr = findContactListRequest(str.c_str());
                            if (lr)
                                lr->visible_id = id;
                            if ((lr == NULL) || (lr->type != LIST_USER_DELETED)){
                                Contact *contact;
                                ICQUserData *data = findContact(str.c_str(), NULL, true, contact);
                                data->ContactVisibleId = id;
                                if ((lr == NULL) && (data->VisibleId != id)){
                                    data->VisibleId = id;
                                    Event e(EventContactChanged, contact);
                                    e.process();
                                }
                                if ((data->InfoFetchTime == 0) && data->Uin)
                                    addFullInfoRequest(data->Uin);
                            }
                        }
                        break;
                    }
                case ICQ_INVISIBLE_LIST:{
                        if (str.length()){
                            log(L_DEBUG, "Invisible %s", str.c_str());
                            ListRequest *lr = findContactListRequest(str.c_str());
                            if (lr)
                                lr->invisible_id = id;
                            if ((lr == NULL) || (lr->type != LIST_USER_DELETED)){
                                Contact *contact;
                                ICQUserData *data = findContact(str.c_str(), NULL, true, contact);
                                data->ContactInvisibleId = id;
                                if ((lr == NULL) && (data->InvisibleId != id)){
                                    data->InvisibleId = id;
                                    Event e(EventContactChanged, contact);
                                    e.process();
                                }
                                if ((data->InfoFetchTime == 0) && data->Uin)
                                    addFullInfoRequest(data->Uin);
                            }
                        }
                        break;
                    }
                case ICQ_IGNORE_LIST:{
                        if (str.length()){
                            log(L_DEBUG, "Ignore %s", str.c_str());
                            ListRequest *lr = findContactListRequest(str.c_str());
                            if (lr)
                                lr->ignore_id = id;
                            Contact *contact;
                            ICQUserData *data = findContact(str.c_str(), NULL, true, contact);
                            if (data->IgnoreId != id){
                                data->IgnoreId = id;
                                if (lr == NULL){
                                    contact->setIgnore(true);
                                    Event e(EventContactChanged, contact);
                                    e.process();
                                }
                            }
                        }
                        break;
                    }
                case ICQ_INVISIBLE_STATE:
                    setContactsInvisible(id);
                    break;
                case 0x0009:
                case 0x0011:
                case 0x0013:
                    break;
                default:
                    log(L_WARN,"Unknown roster type %04X", type);
                }
                if (inf) delete inf;
            }
            unsigned long time;
            m_socket->readBuffer >> time;
            if ((time == 0) && list_len && !bIgnoreTime)
                break;

            setContactsTime(time);

            Group *grp;
            ContactList::GroupIterator it_g;
            list<Group*> forRemove;
            while ((grp = ++it_g) != NULL){
                ICQUserData *data = (ICQUserData*)(grp->clientData.getData(this));
                if ((data == NULL) || data->bChecked)
                    continue;
                ListRequest *lr = findGroupListRequest(data->IcqID);
                if (lr)
                    continue;
                forRemove.push_back(grp);
            }
            for (list<Group*>::iterator it = forRemove.begin(); it != forRemove.end(); ++it){
                delete *it;
            }

            Contact *contact;
            ContactList::ContactIterator it_c;
            while ((contact = ++it_c) != NULL){
                ICQUserData *data;
                ClientDataIterator it_d(contact->clientData);
                bool bOther = false;
                unsigned long newGroup = 0;
                while ((data = (ICQUserData*)(++it_d)) != NULL){
                    if (it_d.client() != this){
                        bOther = true;
                        continue;
                    }
                    unsigned grpId = data->GrpId;
                    ContactList::GroupIterator it_g;
                    while ((grp = ++it_g) != NULL){
                        ICQUserData *data = (ICQUserData*)(grp->clientData.getData(this));
                        if (data && (data->IcqID == grpId))
                            break;
                    }
                    if (grp)
                        newGroup = grp->id();
                }
                if (newGroup != contact->getGroup()){
                    if ((newGroup == 0) && bOther){
                        addContactRequest(contact);
                    }else{
                        contact->setGroup(newGroup);
                    }
                    Event e(EventContactChanged, contact);
                    e.process();
                }
            }
        }
    case ICQ_SNACxLISTS_ROSTERxOK:	// FALLTHROUGH
        {
            log(L_DEBUG, "Rosters OK");
            snac(ICQ_SNACxFAM_LISTS, ICQ_SNACxLISTS_UNKNOWN);
            sendPacket();
            sendCapability();
            sendICMB(1, 11);
            sendICMB(0, 3);
            sendLogonStatus();
            sendClientReady();
            sendMessageRequest();
            if (getContactsInvisible() == 0){
                snac(ICQ_SNACxFAM_LISTS, ICQ_SNACxLISTS_EDIT);
                sendPacket();
                snac(ICQ_SNACxFAM_LISTS, ICQ_SNACxLISTS_CREATE, true);
                m_socket->writeBuffer
                << 0x00000000L << 0x00000001L
                << 0x000400C8L << (unsigned short)0;
                sendPacket();
                snac(ICQ_SNACxFAM_LISTS, ICQ_SNACxLISTS_SAVE);
                sendPacket();
            }
            break;
        }
    case ICQ_SNACxLISTS_ADDED:{
            string screen = m_socket->readBuffer.unpackScreen();
            messageReceived(new AuthMessage(MessageAdded), screen.c_str());
            break;
        }
    case ICQ_SNACxLISTS_AUTHxREQUEST:{
            string screen = m_socket->readBuffer.unpackScreen();
            string message;
            string charset;
            unsigned short have_charset;
            m_socket->readBuffer.unpackStr(message);
            m_socket->readBuffer >> have_charset;
            if (have_charset){
                m_socket->readBuffer.incReadPos(2);
                m_socket->readBuffer.unpackStr(charset);
            }
            log(L_DEBUG, "Auth request %s", screen.c_str());
            ICQAuthMessage *msg = new ICQAuthMessage(MessageICQAuthRequest);
            msg->setServerText(message.c_str());
            msg->setCharset(charset.c_str());
            messageReceived(msg, screen.c_str());
            Contact *contact;
            ICQUserData *data = findContact(screen.c_str(), NULL, false, contact);
            if (data)
                data->WantAuth = true;
            break;
        }
    case ICQ_SNACxLISTS_AUTH:{
            string screen = m_socket->readBuffer.unpackScreen();
            char auth_ok;
            m_socket->readBuffer >> auth_ok;
            string message;
            string charset;
            unsigned short have_charset;
            m_socket->readBuffer.unpackStr(message);
            m_socket->readBuffer >> have_charset;
            if (have_charset){
                m_socket->readBuffer.incReadPos(2);
                m_socket->readBuffer.unpackStr(charset);
            }
            log(L_DEBUG, "Auth %u %s", auth_ok, screen.c_str());
            ICQAuthMessage *msg = new ICQAuthMessage(auth_ok ? MessageICQAuthGranted : MessageICQAuthRefused);
            msg->setServerText(message.c_str());
            msg->setCharset(charset.c_str());
            messageReceived(msg, screen.c_str());
            if (auth_ok){
                Contact *contact;
                ICQUserData *data = findContact(screen.c_str(), NULL, false, contact);
                if (data){
                    data->WaitAuth = false;
                    Event e(EventContactChanged, contact);
                    e.process();
                    addPluginInfoRequest(data->Uin, PLUGIN_QUERYxSTATUS);
                    addPluginInfoRequest(data->Uin, PLUGIN_QUERYxINFO);
                }
            }
            break;
        }
    case ICQ_SNACxLISTS_DONE:
        if (m_listRequest && m_listRequest->seq() == seq){
            unsigned short res;
            m_socket->readBuffer >> res;
            log(L_DEBUG, "List request answer %u", res);
            m_listRequest->process(this, res);
            delete m_listRequest;
            m_listRequest = NULL;
            processListRequest();
        }
        break;
    default:
        log(L_WARN, "Unknown lists family type %04X", type);
    }
Example #9
0
void ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB)
{
	FixtureProxy* proxyA = (FixtureProxy*)proxyUserDataA;
	FixtureProxy* proxyB = (FixtureProxy*)proxyUserDataB;

	Fixture* fixtureA = proxyA->fixture;
	Fixture* fixtureB = proxyB->fixture;

	s32 indexA = proxyA->childIndex;
	s32 indexB = proxyB->childIndex;

	Body* bodyA = fixtureA->GetBody();
	Body* bodyB = fixtureB->GetBody();

	// Are the fixtures on the same body?
	if (bodyA == bodyB)
	{
		return;
	}

	// TODO_ERIN use a hash table to remove a potential bottleneck when both
	// bodies have a lot of contacts.
	// Does a contact already exist?
	ContactEdge* edge = bodyB->GetContactList();
	while (edge)
	{
		if (edge->other == bodyA)
		{
			Fixture* fA = edge->contact->GetFixtureA();
			Fixture* fB = edge->contact->GetFixtureB();
			s32 iA = edge->contact->GetChildIndexA();
			s32 iB = edge->contact->GetChildIndexB();

			if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB)
			{
				// A contact already exists.
				return;
			}

			if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA)
			{
				// A contact already exists.
				return;
			}
		}

		edge = edge->next;
	}

	// Does a joint override collision? Is at least one body dynamic?
	if (bodyB->ShouldCollide(bodyA) == false)
	{
		return;
	}

	// Check user filtering.
	if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false)
	{
		return;
	}

	// Call the factory.
	Contact* c = Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator);
	if (c == NULL)
	{
		return;
	}

	// Contact creation may swap fixtures.
	fixtureA = c->GetFixtureA();
	fixtureB = c->GetFixtureB();
	indexA = c->GetChildIndexA();
	indexB = c->GetChildIndexB();
	bodyA = fixtureA->GetBody();
	bodyB = fixtureB->GetBody();

	// Insert into the world.
	c->m_prev = NULL;
	c->m_next = m_contactList;
	if (m_contactList != NULL)
	{
		m_contactList->m_prev = c;
	}
	m_contactList = c;

	// Connect to island graph.

	// Connect to body A
	c->m_nodeA.contact = c;
	c->m_nodeA.other = bodyB;

	c->m_nodeA.prev = NULL;
	c->m_nodeA.next = bodyA->m_contactList;
	if (bodyA->m_contactList != NULL)
	{
		bodyA->m_contactList->prev = &c->m_nodeA;
	}
	bodyA->m_contactList = &c->m_nodeA;

	// Connect to body B
	c->m_nodeB.contact = c;
	c->m_nodeB.other = bodyA;

	c->m_nodeB.prev = NULL;
	c->m_nodeB.next = bodyB->m_contactList;
	if (bodyB->m_contactList != NULL)
	{
		bodyB->m_contactList->prev = &c->m_nodeB;
	}
	bodyB->m_contactList = &c->m_nodeB;

	// Wake up the bodies
	if (fixtureA->IsSensor() == false && fixtureB->IsSensor() == false)
	{
		bodyA->SetAwake(true);
		bodyB->SetAwake(true);
	}

	++m_contactCount;
}
Example #10
0
unsigned CollisionDetector::boxAndHalfSpace(
    const CollisionBox &box,
    const CollisionPlane &plane,
    CollisionData *data
    )
{
    // Make sure we have contacts
    if (data->contactsLeft <= 0) return 0;

    // Check for intersection
    if (!IntersectionTests::boxAndHalfSpace(box, plane))
    {
        return 0;
    }

    // We have an intersection, so find the intersection points. We can make
    // do with only checking vertices. If the box is resting on a plane
    // or on an edge, it will be reported as four or two contact points.

    // Go through each combination of + and - for each half-size
    static real mults[8][3] = {{1,1,1},{-1,1,1},{1,-1,1},{-1,-1,1},
                               {1,1,-1},{-1,1,-1},{1,-1,-1},{-1,-1,-1}};

    Contact* contact = data->contacts;
    unsigned contactsUsed = 0;
    for (unsigned i = 0; i < 8; i++) {

        // Calculate the position of each vertex
        Vector3 vertexPos(mults[i][0], mults[i][1], mults[i][2]);
        vertexPos.componentProductUpdate(box.halfSize);
        vertexPos = box.transform.transform(vertexPos);

        // Calculate the distance from the plane
        real vertexDistance = vertexPos * plane.direction;

        // Compare this to the plane's distance
        if (vertexDistance <= plane.offset)
        {
            // Create the contact data.

            // The contact point is halfway between the vertex and the
            // plane - we multiply the direction by half the separation
            // distance and add the vertex location.
            contact->contactPoint  = plane.direction;
            contact->contactPoint *= (vertexDistance-plane.offset);
            contact->contactPoint += vertexPos;
            contact->contactNormal = plane.direction;
            contact->penetration = plane.offset - vertexDistance;

            // Write the appropriate data
            contact->setBodyData(box.body, NULL,
                data->friction, data->restitution);

            // Move onto the next contact
            contact++;
            contactsUsed++;
            if (contactsUsed == (unsigned)data->contactsLeft) return contactsUsed;
        }
    }

	data->addContacts(contactsUsed);
    return contactsUsed;
}
Example #11
0
QString MsgViewBase::messageText(Message *msg, bool bUnread)
{
    QString options;
    QString info;
    QString status;

    const char *icon = "message";
    const CommandDef *def = CorePlugin::m_plugin->messageTypes.find(msg->type());
    if (def)
        icon = def->icon;
    bool bDirection = false;
    if (msg->type() == MessageStatus){
        icon = "empty";
        StatusMessage *sm = static_cast<StatusMessage*>(msg);
        Client *client = NULL;
        string clientStr;
        if (msg->client())
            clientStr = msg->client();
        int n = clientStr.find_last_of('.');
        if (n >= 0){
            clientStr = clientStr.substr(0, n);
        }else{
            clientStr = "";
        }
        if (!clientStr.empty()){
            for (unsigned i = 0; i < getContacts()->nClients(); i++){
                string n = getContacts()->getClient(i)->name();
                if (n.length() < clientStr.length())
                    continue;
                n = n.substr(0, clientStr.length());
                if (clientStr == n){
                    client = getContacts()->getClient(i);
                    break;
                }
            }
        }
        if ((client == NULL) && getContacts()->nClients())
            client = getContacts()->getClient(0);
        if (client){
            for (def = client->protocol()->statusList(); def->text; def++){
                if (def->id == sm->getStatus()){
                    icon = def->icon;
                    status = i18n(def->text);
                    break;
                }
            }
        }
        options += " direction=\"2\"";
        bDirection = true;
    }else{
        MessageDef *m_def = (MessageDef*)(def->param);
        if (m_def->flags & MESSAGE_INFO){
            options += " direction=\"2\"";
            bDirection = true;
        }
    }
    info = QString("<icon>%1</icon>") .arg(icon);

    QString contactName;
    if (msg->getFlags() & MESSAGE_RECEIVED){
        if (!bDirection)
            options += " direction=\"1\"";
        Contact *contact = getContacts()->contact(msg->contact());
        if (contact){
            contactName = contact->getName();
            if (contactName.isEmpty()){
                Client *client = NULL;
                ClientDataIterator it(contact->clientData);
                void *data;
                while ((data = ++it) != NULL){
                    if (it.client()->dataName(data) == msg->client()){
                        client = it.client();
                        break;
                    }
                }
            }
        }
        if (!bUnread){
            for (list<msg_id>::iterator it = CorePlugin::m_plugin->unread.begin(); it != CorePlugin::m_plugin->unread.end(); ++it){
                msg_id &m = (*it);
                if ((m.id == msg->id()) &&
                        (m.contact == msg->contact()) &&
                        (m.client == msg->client())){
                    bUnread = true;
                    break;
                }
            }
        }
        if (bUnread)
            options += " unread=\"1\"";
    }else{
        if (!bDirection)
            options += " direction=\"0\"";
        contactName = getContacts()->owner()->getName();
    }
    if (contactName.isEmpty())
        contactName = "???";
    info += QString("<from>%1</from>") .arg(quoteString(contactName));
    QString id = QString::number(msg->id());
    id += ",";
    if (msg->getBackground() != msg->getForeground())
        id += QString::number(msg->getBackground() & 0xFFFFFF);
    string client_str;
    if (msg->client())
        client_str = msg->client();
    if (!client_str.empty()){
        id += ",";
        id += quoteString(client_str.c_str());
    }
    if (m_cut.size()){
        id += ",";
        id += QString::number(m_cut.size());
    }
    info += "<id>";
    info += id;
    info += "</id>";

    QString icons;
    if (msg->getFlags() & MESSAGE_SECURE)
        options += " encrypted=\"1\"";
    if (msg->getFlags() & MESSAGE_URGENT)
        options += " urgent=\"1\"";
    if (msg->getFlags() & MESSAGE_LIST)
        options += " list=\"1\"";

    QString s;
    QDateTime t;
    t.setTime_t(msg->getTime());
    info += s.sprintf("<time><date>%%1</date><hour>%02u</hour><minute>%02u</minute><second>%02u</second></time>",
                      t.time().hour(), t.time().minute(), t.time().second()) .arg(formatDate(msg->getTime()));

    s = "<?xml version=\"1.0\"?><message";
    s += options;
    s += ">";
    s += info;

    QString msgText;
    if (msg->type() != MessageStatus){
        msgText = msg->presentation();
        if (msgText.isEmpty()){
            unsigned type = msg->baseType();
            CommandDef *cmd = CorePlugin::m_plugin->messageTypes.find(type);
            if (cmd){
                MessageDef *def = (MessageDef*)(cmd->param);
                msgText = i18n(def->singular, def->plural, 1);
                int n = msgText.find("1 ");
                if (n == 0){
                    msgText = msgText.mid(2);
                }else if (n > 0){
                    msgText = msgText.left(n);
                }
                msgText = QString("<p>") + msgText + "</p>";
            }
            QString text = msg->getRichText();
            msgText += text;
        }
    }else{
        msgText = status;
    }

    Event e(EventEncodeText, &msgText);
    e.process();
    msgText = parseText(msgText, CorePlugin::m_plugin->getOwnColors(), CorePlugin::m_plugin->getUseSmiles());
    msgText = QString(MSG_BEGIN) + msgText;
    s += "<body>";
    s += quoteString(msgText);
    s += "</body>";
    s += "</message>";
    XSL *p = xsl;
    if (p == NULL)
        p = CorePlugin::m_plugin->historyXSL;
    QString anchor = MSG_ANCHOR;
    anchor += id;
    anchor += "\">";
    QString res = p->process(s);
    if (res.left(3) == "<p>"){
        res = QString("<p>") + anchor + res.mid(3);
    }else{
        res = anchor + res;
    }
    return res;
}
Example #12
0
unsigned CollisionDetector::boxAndBox(
    const CollisionBox &one,
    const CollisionBox &two,
    CollisionData *data
    )
{
    //if (!IntersectionTests::boxAndBox(one, two)) return 0;

    // Find the vector between the two centres
    Vector3 toCentre = two.getAxis(3) - one.getAxis(3);

    // We start assuming there is no contact
    real pen = REAL_MAX;
    unsigned best = 0xffffff;

    // Now we check each axes, returning if it gives us
    // a separating axis, and keeping track of the axis with
    // the smallest penetration otherwise.
    CHECK_OVERLAP(one.getAxis(0), 0);
    CHECK_OVERLAP(one.getAxis(1), 1);
    CHECK_OVERLAP(one.getAxis(2), 2);

    CHECK_OVERLAP(two.getAxis(0), 3);
    CHECK_OVERLAP(two.getAxis(1), 4);
    CHECK_OVERLAP(two.getAxis(2), 5);

    // Store the best axis-major, in case we run into almost
    // parallel edge collisions later
    unsigned bestSingleAxis = best;

    CHECK_OVERLAP(one.getAxis(0) % two.getAxis(0), 6);
    CHECK_OVERLAP(one.getAxis(0) % two.getAxis(1), 7);
    CHECK_OVERLAP(one.getAxis(0) % two.getAxis(2), 8);
    CHECK_OVERLAP(one.getAxis(1) % two.getAxis(0), 9);
    CHECK_OVERLAP(one.getAxis(1) % two.getAxis(1), 10);
    CHECK_OVERLAP(one.getAxis(1) % two.getAxis(2), 11);
    CHECK_OVERLAP(one.getAxis(2) % two.getAxis(0), 12);
    CHECK_OVERLAP(one.getAxis(2) % two.getAxis(1), 13);
    CHECK_OVERLAP(one.getAxis(2) % two.getAxis(2), 14);

    // Make sure we've got a result.
    assert(best != 0xffffff);

    // We now know there's a collision, and we know which
    // of the axes gave the smallest penetration. We now
    // can deal with it in different ways depending on
    // the case.
    if (best < 3)
    {
        // We've got a vertex of box two on a face of box one.
        fillPointFaceBoxBox(one, two, toCentre, data, best, pen);
        data->addContacts(1);
        return 1;
    }
    else if (best < 6)
    {
        // We've got a vertex of box one on a face of box two.
        // We use the same algorithm as above, but swap around
        // one and two (and therefore also the vector between their
        // centres).
        fillPointFaceBoxBox(two, one, toCentre*-1.0f, data, best-3, pen);
        data->addContacts(1);
        return 1;
    }
    else
    {
        // We've got an edge-edge contact. Find out which axes
        best -= 6;
        unsigned oneAxisIndex = best / 3;
        unsigned twoAxisIndex = best % 3;
        Vector3 oneAxis = one.getAxis(oneAxisIndex);
        Vector3 twoAxis = two.getAxis(twoAxisIndex);
        Vector3 axis = oneAxis % twoAxis;
        axis.normalise();

        // The axis should point from box one to box two.
        if (axis * toCentre > 0) axis = axis * -1.0f;

        // We have the axes, but not the edges: each axis has 4 edges parallel
        // to it, we need to find which of the 4 for each object. We do
        // that by finding the point in the centre of the edge. We know
        // its component in the direction of the box's collision axis is zero
        // (its a mid-point) and we determine which of the extremes in each
        // of the other axes is closest.
        Vector3 ptOnOneEdge = one.halfSize;
        Vector3 ptOnTwoEdge = two.halfSize;
        for (unsigned i = 0; i < 3; i++)
        {
            if (i == oneAxisIndex) ptOnOneEdge[i] = 0;
            else if (one.getAxis(i) * axis > 0) ptOnOneEdge[i] = -ptOnOneEdge[i];

            if (i == twoAxisIndex) ptOnTwoEdge[i] = 0;
            else if (two.getAxis(i) * axis < 0) ptOnTwoEdge[i] = -ptOnTwoEdge[i];
        }

        // Move them into world coordinates (they are already oriented
        // correctly, since they have been derived from the axes).
        ptOnOneEdge = one.transform * ptOnOneEdge;
        ptOnTwoEdge = two.transform * ptOnTwoEdge;

        // So we have a point and a direction for the colliding edges.
        // We need to find out point of closest approach of the two
        // line-segments.
        Vector3 vertex = contactPoint(
            ptOnOneEdge, oneAxis, one.halfSize[oneAxisIndex],
            ptOnTwoEdge, twoAxis, two.halfSize[twoAxisIndex],
            bestSingleAxis > 2
            );

        // We can fill the contact.
        Contact* contact = data->contacts;

        contact->penetration = pen;
        contact->contactNormal = axis;
        contact->contactPoint = vertex;
        contact->setBodyData(one.body, two.body,
            data->friction, data->restitution);
        data->addContacts(1);
        return 1;
    }
    return 0;
}
Example #13
0
void *FilterPlugin::processEvent(Event *e)
{
    if (e->type() == EventContactChanged){
        Contact *contact = (Contact*)(e->param());
        if (contact->getGroup()){
            Command cmd;
            cmd->id		= CmdIgnore;
            cmd->flags	= BTN_HIDE;
            cmd->param  = (void*)(contact->id());
            Event eShow(EventCommandShow, cmd);
            eShow.process();
        }
        return NULL;
    }
    if (e->type() == EventMessageReceived){
        Message *msg = (Message*)(e->param());
        if (!msg || (msg->type() == MessageStatus))
            return NULL;
        Contact *contact = getContacts()->contact(msg->contact());
        FilterUserData *data = NULL;
        // check if we accept only from users on the list
        if (getFromList() && ((contact == NULL) || (contact->getFlags() & CONTACT_TEMPORARY))){
            delete msg;
            delete contact;
            return msg;
        }
        if (!contact)
            return NULL;
        // check if the user is a ignored user
        if (contact->getIgnore()){
            delete msg;
            return msg;
        }
        // get filter-data
        data = (FilterUserData*)(contact->getUserData(user_data_id));
        if (data && data->SpamList.ptr && *data->SpamList.ptr){
            if (checkSpam(msg->getPlainText(), QString::fromUtf8(data->SpamList.ptr))){
                delete msg;
                return msg;
            }
        }
        return NULL;
    }
    if (e->type() == EventCheckState){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->id == CmdIgnore){
            cmd->flags &= ~BTN_HIDE;
            Contact *contact = getContacts()->contact((unsigned)(cmd->param));
            if (contact && contact->getGroup())
                cmd->flags |= BTN_HIDE;
            return e->param();
        }
        if (cmd->id == CmdIgnoreText){
            cmd->flags &= ~COMMAND_CHECKED;
            if (cmd->menu_id == MenuMsgView){
                MsgViewBase *edit = (MsgViewBase*)(cmd->param);
                if (edit->hasSelectedText())
                    return e->param();
            }else if (cmd->menu_id == MenuTextEdit){
                TextEdit *edit = ((MsgEdit*)(cmd->param))->m_edit;
                if (edit->hasSelectedText())
                    return e->param();
            }
            return NULL;
        }
        if (cmd->menu_id == MenuContactGroup){
            if (cmd->id == CmdIgnoreList){
                Contact *contact = getContacts()->contact((unsigned)(cmd->param));
                if (contact == NULL)
                    return NULL;
                cmd->flags &= COMMAND_CHECKED;
                if (contact->getIgnore())
                    cmd->flags |= COMMAND_CHECKED;
                return e->param();
            }
        }
    }
    if (e->type() == EventCommandExec){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->id == CmdIgnore){
            Contact *contact = getContacts()->contact((unsigned)(cmd->param));
            if (contact){
                QString text = i18n("Add %1 to ignore list?") .arg(contact->getName());
                Command cmd;
                cmd->id		= CmdIgnore;
                cmd->param	= (void*)(contact->id());
                Event e(EventCommandWidget, cmd);
                QWidget *w = (QWidget*)(e.process());
                BalloonMsg::ask((void*)(contact->id()), text, w, SLOT(addToIgnore(void*)), NULL, NULL, this);
            }
            return e->param();
        }
void *HistoryWindow::processEvent(Event *e)
{
    if (e->type() == EventContactDeleted){
        Contact *contact = (Contact*)(e->param());
        if (contact->id() == m_id)
            QTimer::singleShot(0, this, SLOT(close()));
    }
    if (e->type() == EventContactChanged){
        Contact *contact = (Contact*)(e->param());
        if (contact->id() == m_id)
            setName();
    }
    if (e->type() == EventCheckState){
        CommandDef *cmd = (CommandDef*)(e->param());
        if ((cmd->id == CmdHistoryDirection) && ((unsigned long)(cmd->param) == m_id)){
            cmd->flags &= ~COMMAND_CHECKED;
            if (m_bDirection)
                cmd->flags |= COMMAND_CHECKED;
            return e->param();
        }
        if (((cmd->id == CmdDeleteMessage) || (cmd->id == CmdCutHistory)) &&
                (cmd->param == m_view) && m_view->currentMessage()){
            cmd->flags &= ~COMMAND_CHECKED;
            return e->param();
        }
        return NULL;
    }
    if (e->type() == EventCommandExec){
        CommandDef *cmd = (CommandDef*)(e->param());
        if ((unsigned long)(cmd->param) != m_id)
            return NULL;
        if (cmd->id == CmdHistoryDirection){
            bool bDirection = ((cmd->flags & COMMAND_CHECKED) != 0);
            CorePlugin::m_plugin->setHistoryDirection(bDirection);
            if (bDirection != m_bDirection){
                m_bDirection = bDirection;
                m_page = 0;
                m_states.clear();
                fill();
            }
            return e->param();
        }
        if (cmd->id == CmdHistoryNext){
            if (m_page + 1 < m_states.size()){
                m_page++;
                fill();
            }
            return e->param();
        }
        if (cmd->id == CmdHistoryPrev){
            if (m_page > 0){
                m_page--;
                fill();
            }
            return e->param();
        }
        if (cmd->id == CmdHistorySave){
            QString str = QFileDialog::getSaveFileName(QString::null, i18n("Textfile (*.txt)"), this);
            if (str && !str.isEmpty()){
                bool res = true;
                if (QFile::exists(str)){
                    QMessageBox mb(i18n("Error"), i18n("File already exists. Overwrite?"),
                            QMessageBox::Warning,
                            QMessageBox::Yes | QMessageBox::Default,
                            QMessageBox::No,
                            QMessageBox::Cancel | QMessageBox::Escape);
                    mb.setButtonText(QMessageBox::Yes, i18n("&Overwrite"));
                    mb.setButtonText(QMessageBox::No, i18n("&Append"));
                    switch (mb.exec()){
                    case QMessageBox::Yes:
                        res = History::save(m_id, str, false);
                        break;
                    case QMessageBox::No:
                        res = History::save(m_id, str, true);
                        break;
                    case QMessageBox::Cancel:
                        break;
                    }
                }else
                    res = History::save(m_id, str);
                if (!res)
                    QMessageBox::critical(this, i18n("Error"), i18n("Save failed"), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
            }
            return e->param();
        }
        if (cmd->id == CmdHistoryFind){
            m_filter = "";
            if (cmd->flags & COMMAND_CHECKED){
                Command cmd;
                cmd->id		= CmdHistoryFind;
                cmd->param	= (void*)m_id;
                Event eWidget(EventCommandWidget, cmd);
                CToolCombo *cmbFind = (CToolCombo*)(eWidget.process());
                if (cmbFind){
                    QString text = cmbFind->lineEdit()->text();
                    if (!text.isEmpty()){
                        addHistory(text);
                        m_filter = text;
                    }
                }
            }
            m_page = 0;
            m_states.clear();
            m_view->setSelect(m_filter);
            fill();
            return e->param();
        }
    }
    return NULL;
}
Example #15
0
void HistoryConfig::fillPreview()
{
    m_bDirty = false;
    int cur = cmbStyle->currentItem();
    if ((cur < 0) || (cur >= (int)m_styles.size()))
        return;
    XSL *xsl = new XSL(m_styles[cur].name);
    if (!m_styles[cur].text.isEmpty())
        xsl->setXSL(m_styles[cur].text);
    Contact *contact = getContacts()->contact(0, true);
    contact->setName("Buddy");
    contact->setFlags(CONTACT_TEMP);
    edtPreview->clear();
    edtPreview->setXSL(xsl);
    time_t now;
    time(&now);
    bool saveSmiles = CorePlugin::m_plugin->getUseSmiles();
    bool saveOwn    = CorePlugin::m_plugin->getOwnColors();
    CorePlugin::m_plugin->setUseSmiles(chkSmile->isChecked());
    CorePlugin::m_plugin->setOwnColors(chkOwn->isChecked());
    Message m1;
    m1.setId((unsigned)(-1));
    m1.setFlags(MESSAGE_RECEIVED | MESSAGE_LIST);
    m1.setText(i18n("Hi! ;)"));
    m1.setTime(now - 360);
    m1.setContact(contact->id());
    edtPreview->addMessage(&m1);
    Message m2;
    m2.setId((unsigned)(-2));
    m2.setText(i18n("Hi!"));
    m2.setTime(now - 300);
    m2.setContact(contact->id());
    edtPreview->addMessage(&m2);
    Message m3;
    m3.setId((unsigned)(-3));
    m3.setText(i18n("<b><font color=\"#FF0000\">C</font><font color=\"#FFFF00\">olored</font></b> message"));
    m3.setTime(now - 120);
    m3.setFlags(MESSAGE_SECURE | MESSAGE_URGENT | MESSAGE_RICHTEXT);
    m3.setBackground(0xC0C0C0);
    m3.setForeground(0x008000);
    m3.setContact(contact->id());
    edtPreview->addMessage(&m3);
    Message m4;
    m4.setId((unsigned)(-4));
    m4.setText(i18n("New message"));
    m4.setFlags(MESSAGE_RECEIVED);
    m4.setTime(now - 60);
    m4.setContact(contact->id());
    edtPreview->addMessage(&m4, true);
    StatusMessage m5;
    m5.setId((unsigned)(-5));
    m5.setStatus(STATUS_OFFLINE);
    m5.setTime(now);
    m5.setContact(contact->id());
    if (getContacts()->nClients())
        m5.setClient((getContacts()->getClient(0)->name() + ".").c_str());
    edtPreview->addMessage(&m5);
    delete contact;
    CorePlugin::m_plugin->setUseSmiles(saveSmiles);
    CorePlugin::m_plugin->setOwnColors(saveOwn);
}
Example #16
0
// This is the top level collision call for the time step. Here
// all the narrow phase collision is processed for the world
// contact list.
void ContactManager::Collide()
{
	// Update awake contacts.
	Contact* c = m_contactList;
	while (c)
	{
		Fixture* fixtureA = c->GetFixtureA();
		Fixture* fixtureB = c->GetFixtureB();
		s32 indexA = c->GetChildIndexA();
		s32 indexB = c->GetChildIndexB();
		Body* bodyA = fixtureA->GetBody();
		Body* bodyB = fixtureB->GetBody();

		// Is this contact flagged for filtering?
		if (c->m_flags & Contact::filterFlag)
		{
			// Should these bodies collide?
			if (bodyB->ShouldCollide(bodyA) == false)
			{
				Contact* cNuke = c;
				c = cNuke->GetNext();
				Destroy(cNuke);
				continue;
			}

			// Check user filtering.
			if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false)
			{
				Contact* cNuke = c;
				c = cNuke->GetNext();
				Destroy(cNuke);
				continue;
			}

			// Clear the filtering flag.
			c->m_flags &= ~Contact::filterFlag;
		}

		bool activeA = bodyA->IsAwake() && bodyA->m_type != staticBody;
		bool activeB = bodyB->IsAwake() && bodyB->m_type != staticBody;

		// At least one body must be awake and it must be dynamic or kinematic.
		if (activeA == false && activeB == false)
		{
			c = c->GetNext();
			continue;
		}

		s32 proxyIdA = fixtureA->m_proxies[indexA].proxyId;
		s32 proxyIdB = fixtureB->m_proxies[indexB].proxyId;
		bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB);

		// Here we destroy contacts that cease to overlap in the broad-phase.
		if (overlap == false)
		{
			Contact* cNuke = c;
			c = cNuke->GetNext();
			Destroy(cNuke);
			continue;
		}

		// The contact persists.
		c->Update(m_contactListener);
		c = c->GetNext();
	}
}
Example #17
0
void RostersRequest::element_end(const char *el)
{
    if (strcmp(el, "group") == 0){
        m_data = NULL;
        return;
    }
    if (strcmp(el, "item") == 0){
        bool bChanged = false;
        JabberListRequest *lr = m_client->findRequest(m_jid.c_str(), false);
        Contact *contact;
        JabberUserData *data = m_client->findContact(m_jid.c_str(), NULL, m_name.c_str(), false, contact);
        if (data == NULL){
            if (lr && lr->bDelete){
                m_client->findRequest(m_jid.c_str(), true);
            }else{
                bChanged = true;
                data = m_client->findContact(m_jid.c_str(), NULL, m_name.c_str(), true, contact);
                if (m_bSubscription){
                    contact->setTemporary(CONTACT_TEMP);
                    Event eContact(EventContactChanged, contact);
                    eContact.process();
                    m_client->auth_request(m_jid.c_str(), MessageAuthRequest, m_subscription.c_str(), true);
                    data = m_client->findContact(m_jid.c_str(), NULL, m_name.c_str(), false, contact);
                }
            }
        }
        if (data == NULL)
            return;
        if (data->Subscribe != m_subscribe){
            bChanged = true;
            data->Subscribe = m_subscribe;
        }
        data->bChecked = true;
        if (lr == NULL){
            unsigned grp = 0;
            if (!m_grp.empty()){
                Group *group;
                ContactList::GroupIterator it;
                while ((group = ++it) != NULL){
                    if (m_grp == (const char*)(group->getName().utf8())){
                        grp = group->id();
                        break;
                    }
                }
            }
            if (contact->getGroup() != grp){
				if (grp == 0){
					void *d = NULL;
					ClientDataIterator it_d(contact->clientData);
					while ((d = ++it_d) != NULL){
						if (d != data)
							break;
					}
					if (d){
						grp = contact->getGroup();
						Group *group = getContacts()->group(grp);
						if (group)
							m_client->listRequest(data, contact->getName().utf8(), group->getName().utf8(), false);
					}
				}
                contact->setGroup(grp);
                bChanged = true;
            }
        }
        if (bChanged){
            Event e(EventContactChanged, contact);
            e.process();
        }
    }
}
Example #18
0
QString Parser::parse(const QString &s, BuddyOrContact buddyOrContact, const QObject * const object, bool escape)
{
    Buddy buddy = buddyOrContact.buddy();
    Contact contact = buddyOrContact.contact();

    kdebugmf(KDEBUG_DUMP, "%s escape=%i\n", qPrintable(s), escape);
    int index = 0, i, len = s.length();
    QList<ParserToken> parseStack;

    static QHash<QChar, bool> searchChars;

    if (!searchChars.value('%', false))
    {
        searchChars['%'] = true;
        searchChars['['] = true;
        searchChars['{'] = true;
        searchChars['\\'] = true;
        searchChars['$'] = true;
        searchChars['@'] = true;
        searchChars['#'] = true;
        searchChars['}'] = true;
        searchChars[']'] = true;
    }

    bool allowExec = config_file.readBoolEntry("General", "AllowExecutingFromParser", false);
    searchChars['`'] = allowExec;
    searchChars['\''] = allowExec;

    while (index < len)
    {
        ParserToken pe1, pe;

        for(i = index; i < len; ++i)
            if (searchChars.value(s.at(i), false))
                break;

//		this is the same, but code above is muuuuch faster
//		i=s.find(QRegExp("%|`|\\{|\\[|'|\\}|\\]"), index);

        if (i != index)
        {
            pe1.type = ParserToken::PT_STRING;
            pe1.content = s.mid(index, i - index);
            parseStack.push_back(pe1);

            if (i == len)
                break;
        }

        char c = s.at(i).toAscii();
        if (c == '%')
        {
            ++i;
            if (i == len)
                break;
            pe.type = ParserToken::PT_STRING;

            switch (s.at(i).toAscii())
            {
            case 's':
                ++i;
                if (contact)
                {
                    StatusType *type = StatusTypeManager::instance()->statusType(contact.currentStatus().type());
                    if (type)
                        pe.content = type->displayName();
                }
                break; // TODO: 't' removed
            case 'q':
                ++i;
                if (contact)
                {
                    StatusContainer *container = contact.contactAccount().statusContainer();
                    if (container)
                        pe.content = container->statusIconPath(contact.currentStatus().type());
                }
                break;
            case 'd':
                ++i;
                if (contact)
                    pe.content = contact.currentStatus().description();

                if (escape)
                    HtmlDocument::escapeText(pe.content);
                if (config_file.readBoolEntry("Look", "ShowMultilineDesc"))
                {
                    pe.content.replace('\n', QLatin1String("<br/>"));
                    pe.content.replace(QRegExp("\\s\\s"), QString(" &nbsp;"));
                }
                break;
            case 'i':
                ++i;
                if (contact)
                    pe.content = contact.address().toString();
                break;
            case 'v':
                ++i;
                if (contact)
                    pe.content = contact.dnsName();
                break;
            case 'o':
                ++i;
                if (contact && contact.port() == 2)
                    pe.content = ' ';
                break;
            case 'p':
                ++i;
                if (contact && contact.port())
                    pe.content = QString::number(contact.port());
                break;
            case 'u':
                ++i;
                if (contact)
                    pe.content = contact.id();
                else if (buddy)
                    pe.content = buddy.mobile().isEmpty() ? buddy.email() : buddy.mobile();
                break;
            case 'h':
                ++i;
                if (contact && !contact.currentStatus().isDisconnected())
                    pe.content = contact.protocolVersion();
                break;
            case 'n':
                ++i;
                pe.content = buddy.nickName();
                if (escape)
                    HtmlDocument::escapeText(pe.content);
                break;
            case 'a':
                ++i;
                pe.content = buddy.display();
                if (escape)
                    HtmlDocument::escapeText(pe.content);
                break;
            case 'f':
                ++i;
                pe.content = buddy.firstName();
                if (escape)
                    HtmlDocument::escapeText(pe.content);
                break;
            case 'r':
                ++i;
                pe.content = buddy.lastName();
                if (escape)
                    HtmlDocument::escapeText(pe.content);
                break;
            case 'm':
                ++i;
                pe.content = buddy.mobile();
                break;
            case 'g':
            {
                ++i;
                QStringList groups;
                foreach (const Group &group, buddy.groups())
                    groups << group.name();
                pe.content = groups.join(",");
                break;
            }
            case 'e':
                ++i;
                pe.content = buddy.email();
                break;
            case 'x':
                ++i;
                if (contact)
                    pe.content = contact.maximumImageSize();
                break;
            case 'z':
                ++i;
                if (buddy)
                    pe.content = QString::number(buddy.gender());
                break;
            case '%':
                ++i;
            default:
                pe.content = '%';
            }
            parseStack.push_back(pe);
        }
        else if (c == '[')
Example #19
0
void OSDPlugin::processQueue()
{
    if (m_timer->isActive())
        return;
    while (queue.size()){
        m_request = queue.front();
        queue.erase(queue.begin());
        Contact *contact = getContacts()->contact(m_request.contact);
        if ((contact == NULL) || contact->getIgnore()){
            continue;
        }
        QString text;
        OSDUserData *data = NULL;
        data = (OSDUserData*)contact->getUserData(user_data_id);
        switch (m_request.type){
        case OSD_ALERT:
            if (data->EnableAlert.bValue){
                unsigned style = 0;
                const char *statusIcon = NULL;
                if (contact->contactInfo(style, statusIcon) >= STATUS_ONLINE)
                    text = g_i18n("%1 is online", contact) .arg(contact->getName());
            }
            break;
        case OSD_TYPING:
            if (data->EnableTyping.bValue){
                unsigned style = 0;
                string wrkIcons;
                const char *statusIcon = NULL;
                contact->contactInfo(style, statusIcon, &wrkIcons);
                bool bTyping = false;
                while (!wrkIcons.empty()){
                    if (getToken(wrkIcons, ',') == "typing"){
                        bTyping = true;
                        break;
                    }
                }
                if (bTyping)
                    text = g_i18n("%1 is typing", contact) .arg(contact->getName());
            }
            break;
        case OSD_MESSAGE:
            if (data->EnableMessage.bValue && core){
                list<msg_id>::iterator it;
                TYPE_MAP types;
                TYPE_MAP::iterator itc;
                QString msg_text;
                for (it = core->unread.begin(); it != core->unread.end(); ++it){
                    if ((*it).contact != m_request.contact)
                        continue;
                    unsigned type = (*it).type;
                    itc = types.find(type);
                    if (itc == types.end()){
                        types.insert(TYPE_MAP::value_type(type, 1));
                    }else{
                        (*itc).second++;
                    }
                    if (!data->EnableMessageShowContent.bValue)
                        continue;
                    MessageID id;
                    id.id      = (*it).id;
                    id.contact = (*it).contact;
                    id.client  = (*it).client.c_str();
                    Event e(EventLoadMessage, &id);
                    Message *msg = (Message*)(e.process());
                    if (msg == NULL)
                        continue;
                    QString msgText = msg->getPlainText().stripWhiteSpace();
                    if (msgText.isEmpty())
                        continue;
                    if (!msg_text.isEmpty())
                        msg_text += "\n";
                    msg_text += msgText;
                }
                if (types.empty())
                    break;
                for (itc = types.begin(); itc != types.end(); ++itc){
                    CommandDef *def = core->messageTypes.find((*itc).first);
                    if (def == NULL)
                        continue;
                    MessageDef *mdef = (MessageDef*)(def->param);
                    QString msg = i18n(mdef->singular, mdef->plural, (*itc).second);
                    if ((*itc).second == 1){
                        int pos = msg.find("1 ");
                        if (pos > 0){
                            msg = msg.left(pos);
                        }else if (pos == 0){
                            msg = msg.mid(2);
                        }
                        msg = msg.left(1).upper() + msg.mid(1);
                    }
                    if (!text.isEmpty())
                        text += ", ";
                    text += msg;
                }
                text = i18n("%1 from %2") .arg(text) .arg(contact->getName());
                if (msg_text.isEmpty())
                    break;
                text += ":\n";
                text += msg_text;
            }
        }
        if (!text.isEmpty()){
            if (m_osd == NULL){
                m_osd = new OSDWidget;
                connect(m_osd, SIGNAL(dblClick()), this, SLOT(dblClick()));
            }
            static_cast<OSDWidget*>(m_osd)->showOSD(text, data);
            m_timer->start(data->Timeout.value * 1000);
            return;
        }
    }
    m_timer->stop();
    m_request.contact = 0;
    m_request.type = OSD_NONE;
}
Example #20
0
void ICQClient::snac_buddy(unsigned short type, unsigned short)
{
    unsigned long uin;
    Contact *contact;
    ICQUserData *data;
    switch (type){
    case ICQ_SNACxBDY_RIGHTSxGRANTED:
        log(L_DEBUG, "Buddy rights granted");
        break;
    case ICQ_SNACxBDY_USEROFFLINE:
        uin = m_socket->readBuffer.unpackUin();
        data = findContact(uin, NULL, false, contact);
        if (data && (data->Status != ICQ_STATUS_OFFLINE)){
            setOffline(data);
            StatusMessage m;
            m.setContact(contact->id());
            m.setClient(dataName(data).c_str());
            m.setStatus(STATUS_OFFLINE);
            m.setFlags(MESSAGE_RECEIVED);
            Event e(EventMessageReceived, &m);
            e.process();
        }
        break;
    case ICQ_SNACxBDY_USERONLINE:
        uin = m_socket->readBuffer.unpackUin();
        data = findContact(uin, NULL, false, contact);
        if (data){
            time_t now;
            time(&now);

            bool bChanged = false;
            unsigned long prevStatus = data->Status;

            unsigned short level, len;
            m_socket->readBuffer >> level >> len;

            TlvList tlv(m_socket->readBuffer);

            // Status TLV
            Tlv *tlvStatus = tlv(0x0006);
            if (tlvStatus){
                unsigned long status = *tlvStatus;
                if (status != data->Status){
                    data->Status = status;
                    if ((status & 0xFF) == 0)
                        set_str(&data->AutoReply, NULL);
                    data->StatusTime = (unsigned long)now;
                }
            }else if (data->Status == ICQ_STATUS_OFFLINE){
                data->Status = ICQ_STATUS_ONLINE;
                data->StatusTime = (unsigned long)now;
            }

            // Online time TLV
            Tlv *tlvOnlineTime = tlv(0x0003);
            if (tlvOnlineTime){
                unsigned long OnlineTime = *tlvOnlineTime;
                if (OnlineTime != data->OnlineTime){
                    data->OnlineTime = OnlineTime;
                    bChanged = true;
                }
            }
            Tlv *tlvNATime = tlv(0x0004);
            if (tlvNATime){
                unsigned short na_time = *tlvNATime;
                unsigned long StatusTime = (unsigned long)now - na_time * 60;
                if (StatusTime != data->StatusTime){
                    data->StatusTime = StatusTime;
                    bChanged = true;
                }
            }

            // IP TLV
            Tlv *tlvIP = tlv(0x000A);
            if (tlvIP)
                bChanged |= set_ip(&data->IP, htonl((unsigned long)(*tlvIP)));

            Tlv *tlvCapability = tlv(0x000D);
            if (tlvCapability){
                data->Caps = 0;
                Buffer info(*tlvCapability);
                for (; info.readPos() < info.size(); ){
                    capability cap;
                    info.unpack((char*)cap, sizeof(capability));
                    for (unsigned i = 0;; i++){
                        if (*capabilities[i] == 0) break;
                        unsigned size = sizeof(capability);
                        if (i == CAP_SIMOLD) size--;
                        if ((i == CAP_MICQ) || (i == CAP_LICQ) || (i == CAP_SIM)) size -= 4;
                        if (!memcmp(cap, capabilities[i], size)){
                            if (i == CAP_SIMOLD){
                                unsigned char build = cap[sizeof(capability)-1];
                                if (build && ((build == 0x92) || (build < (1 << 6)))) continue;
                                data->Build = build;
                            }
                            if ((i == CAP_MICQ) || (i == CAP_LICQ) || (i == CAP_SIM)){
                                unsigned char *p = (unsigned char*)cap;
                                p += 12;
                                data->Build = (p[0] << 24) + (p[1] << 16) + (p[2] << 8) + p[3];
                            }
                            data->Caps |= (1 << i);
                            break;
                        }
                    }
                }
            }

            unsigned long infoUpdateTime = 0;
            unsigned long pluginInfoTime = 0;
            unsigned long pluginStatusTime = 0;

            // Direct connection info
            Tlv *tlvDirect = tlv(0x000C);
            if (tlvDirect){
                Buffer info(*tlvDirect);
                unsigned long  realIP;
                unsigned short port;
                char mode, version, junk;
                info >> realIP;
                info.incReadPos(2);
                info >> port;
                if (realIP == 0x7F000001)
                    realIP = 0;
                bChanged |= set_ip(&data->RealIP, htonl(realIP));
                data->Port = port;
                unsigned long DCcookie;
                info >> mode >> junk >> version >> DCcookie;
                data->DCcookie = DCcookie;
                info.incReadPos(8);
                info
                >> infoUpdateTime
                >> pluginInfoTime
                >> pluginStatusTime;
                if (mode == MODE_DENIED) mode = MODE_INDIRECT;
                if ((mode != MODE_DIRECT) && (mode != MODE_INDIRECT))
                    mode = MODE_INDIRECT;
                data->Mode    = mode;
                data->Version = version;
            }

            Tlv *tlvPlugin = tlv(0x0011);
            if (tlvPlugin){
                Buffer info(*tlvPlugin);
                char type;
                unsigned long time;
                info >> type;
                info.unpack(time);
                plugin p;
                unsigned plugin_index;
                unsigned long plugin_status;
                switch (type){
                case 1:
                    addFullInfoRequest(uin);
                    break;
                case 2:
                    info.incReadPos(6);
                    info.unpack((char*)p, sizeof(p));
                    data->PluginInfoTime = time;
                    for (plugin_index = 0; plugin_index < PLUGIN_NULL; plugin_index++)
                        if (!memcmp(p, plugins[plugin_index], sizeof(p)))
                            break;
                    switch (plugin_index){
                    case PLUGIN_PHONEBOOK:
                        log(L_DEBUG, "Updated phonebook");
                        addPluginInfoRequest(data->Uin, plugin_index);
                        break;
                    case PLUGIN_PICTURE:
                        log(L_DEBUG, "Updated picture");
                        addPluginInfoRequest(data->Uin, plugin_index);
                        break;
                    case PLUGIN_QUERYxINFO:
                        log(L_DEBUG, "Updated info plugin list");
                        addPluginInfoRequest(data->Uin, plugin_index);
                        break;
                    default:
                        if (plugin_index >= PLUGIN_NULL)
                            log(L_WARN, "Unknown plugin sign");
                    }
                    break;
                case 3:
                    info.incReadPos(6);
                    info.unpack((char*)p, sizeof(p));
                    info.incReadPos(1);
                    info.unpack(plugin_status);
                    data->PluginStatusTime = time;
                    for (plugin_index = 0; plugin_index < PLUGIN_NULL; plugin_index++)
                        if (!memcmp(p, plugins[plugin_index], sizeof(p)))
                            break;
                    switch (plugin_index){
                    case PLUGIN_FOLLOWME:
                        if (data->FollowMe == plugin_status)
                            break;
                        data->FollowMe = plugin_status;
                        bChanged = true;
                        break;
                    case PLUGIN_FILESERVER:
                        if ((data->SharedFiles != 0) == (plugin_status != 0))
                            break;
                        data->SharedFiles = (plugin_status != 0);
                        bChanged = true;
                        break;
                    case PLUGIN_ICQPHONE:
                        if (data->ICQPhone == plugin_status)
                            break;
                        data->ICQPhone = plugin_status;
                        bChanged = true;
                        break;
                    default:
                        if (plugin_index >= PLUGIN_NULL)
                            log(L_WARN, "Unknown plugin sign");
                    }
                    break;

                }
            }else{
                data->InfoUpdateTime   = infoUpdateTime;
                data->PluginInfoTime   = pluginInfoTime;
                data->PluginStatusTime = pluginStatusTime;
                if (infoUpdateTime == 0)
                    infoUpdateTime = 1;
                if (infoUpdateTime != data->InfoFetchTime)
                    addFullInfoRequest(data->Uin);
                if (data->PluginInfoTime != data->PluginInfoFetchTime){
                    if (data->PluginInfoTime)
                        addPluginInfoRequest(data->Uin, PLUGIN_QUERYxINFO);
                }
                if ((data->PluginInfoTime != data->PluginInfoFetchTime) ||
					(data->PluginStatusTime != data->PluginStatusFetchTime)){
                    if (data->SharedFiles != 0){
                        data->SharedFiles = 0;
                        bChanged = true;
                    }
                    if (data->FollowMe != 0){
                        data->FollowMe = 0;
                        bChanged = true;
                    }
                    if (data->ICQPhone != 0){
                        data->ICQPhone = 0;
                        bChanged = true;
                    }
                    if (data->PluginStatusTime)
                        addPluginInfoRequest(data->Uin, PLUGIN_QUERYxSTATUS);
                }
            }
            if (data->bInvisible){
                data->bInvisible = false;
                bChanged = true;
            }
            if (bChanged){
                Event e(EventContactChanged, contact);
                e.process();
            }
            if (data->Status != prevStatus){
                unsigned status = STATUS_OFFLINE;
                if ((data->Status & 0xFFFF) != ICQ_STATUS_OFFLINE){
                    status = STATUS_ONLINE;
                    if (data->Status & ICQ_STATUS_DND){
                        status = STATUS_DND;
                    }else if (data->Status & ICQ_STATUS_OCCUPIED){
                        status = STATUS_OCCUPIED;
                    }else if (data->Status & ICQ_STATUS_NA){
                        status = STATUS_NA;
                    }else if (data->Status & ICQ_STATUS_AWAY){
                        status = STATUS_AWAY;
                    }else if (data->Status & ICQ_STATUS_FFC){
                        status = STATUS_FFC;
                    }
                }
                StatusMessage m;
                m.setContact(contact->id());
                m.setClient(dataName(data).c_str());
                m.setStatus(status);
                m.setFlags(MESSAGE_RECEIVED);
                Event e(EventMessageReceived, &m);
                e.process();
                if (((data->Status & 0xFF) == ICQ_STATUS_ONLINE) &&
                        ((prevStatus & 0xFF) != ICQ_STATUS_ONLINE) &&
                        (((prevStatus & 0xFFFF) != ICQ_STATUS_OFFLINE) ||
                         (data->OnlineTime > this->data.owner.OnlineTime))){
                    Event e(EventContactOnline, contact);
                    e.process();
                }
                if ((data->Status & 0xFF) != ICQ_STATUS_ONLINE){
                    if ((getInvisible() && data->VisibleId) ||
                            (!getInvisible() && (data->InvisibleId == 0)))
                        addPluginInfoRequest(data->Uin, PLUGIN_AR);
                }
            }
        }
        break;
    default:
        log(L_WARN, "Unknown buddy family type %04X", type);
    }
// Handles elastic collisions, static contacts (resting against surface) and moving interpenetrating objects
// out of each other. This is all done as a single step, as it improves the mathematical stability of the
// engine.
void Physics::HandleCollisions(float deltaT)
{
    XMVECTOR velDueToGrav = XMLoadFloat3(&m_velDueToAccel);
    XMVECTOR velocity = XMLoadFloat3(&m_velocity);
    XMVECTOR position = XMLoadFloat3(&m_position);
    XMVECTOR radius = XMVectorReplicatePtr(&m_radius);
    XMVECTOR maxRollingSpeed = XMVectorZero();
    XMVECTOR maxCollisionSpeed = XMVectorZero();
    XMVECTOR deltaTime = XMVectorReplicate(deltaT);

    const size_t MAX_COLLISION_ITERATIONS = 8;
    for (size_t i = 0; i < MAX_COLLISION_ITERATIONS; ++i)
    {
        // Find the collision with the biggest intrusion into the mesh, that is facing in the opposite direction to the
        // way the ball is moving (i.e. has a positive closing velocity).
        Contact* contact = m_collision->FindWorstInterpenetration();
        if (contact == nullptr)
            break;

        XMVECTOR surfaceNormal = contact->GetSurfaceNormal();

        XMVECTOR velocityDotNormal = XMVector3Dot(surfaceNormal, velocity);
        XMVECTOR velGravDotNormal = XMVector3Dot(surfaceNormal, velDueToGrav);

        // Estimate how much the ball would have fallen into the mesh due to gravity this frame, if it started out
        // resting against it. If it's almost the same as the actual penetration, we must have been resting to start
        // with, so we can immediately cancel out this contribution.
        XMVECTOR penetrationDistance = XMVectorReplicatePtr(&contact->penetrationDistance);
        XMVECTOR distDueToGrav = velGravDotNormal * deltaTime;
        const XMVECTOR tolerance = XMVectorSet(0.1f, 0.1f, 0.1f, 0.1f);
        if (XMVector3NearEqual(penetrationDistance, distDueToGrav, tolerance))
        {
            // Contact

            // Kill velocity in surface-normal direction entirely.
            velocity = velocity - surfaceNormal * velocityDotNormal;

            XMVECTOR speed = XMVector3Length(velocity);
            XMVECTOR velocityDir = XMVector3Normalize(velocity); // could optimize...

            // Find acceleration into surface
            XMVECTOR accel = XMLoadFloat3(&m_acceleration);
            XMVECTOR ADotN = XMVector3Dot(accel, surfaceNormal);
            XMVECTOR select = XMVectorLessOrEqual(ADotN, XMVectorZero());
            XMVECTOR accelSurface = XMVectorSelect(XMVectorZero(), -ADotN, select);

            // Handle friction
            XMVECTOR frictionResponse =  accelSurface * wallFrictionCoeff * deltaTime;
            velocity = velocity - velocityDir * XMVectorMin(speed, frictionResponse);

            maxRollingSpeed = XMVectorMax(XMVector3LengthSq(velocityDir * velocity), maxRollingSpeed);

            // Make sure we're no longer in the mesh.
            position = contact->Resolve(position, radius);
        }
        else
        {
            // Elastic collision - reflect our velocity in the direction of the normal.
            float negRestitutionScalar = - (1.0f + WallRestitutionCoefficient);
            XMVECTOR negRestitution = XMVectorReplicate(negRestitutionScalar);

            // Keep track of max collision speed for the audio sim.
            maxCollisionSpeed = XMVectorMax(maxCollisionSpeed, velocityDotNormal * velocityDotNormal);

            // Update the velocity.
            velocity = velocity + (negRestitution * velocityDotNormal * surfaceNormal);

            // Make sure we're no longer in the mesh.
            position = contact->Resolve(position, radius);
        }

        // Remove this contact from consideration for this iteration.
        contact->Invalidate();

        // Update the penetration of the ball.
        m_collision->UpdateInterpenetrations(position, radius, velocity);
    }

    XMStoreFloat3(&m_velocity, velocity);
    XMStoreFloat3(&m_position, position);
    XMStoreFloat3(&m_maxRollingSpeed, XMVectorSqrt(maxRollingSpeed));
    XMStoreFloat3(&m_maxCollisionSpeed, XMVectorSqrt(maxCollisionSpeed));
}
Example #22
0
bool SynPacket::answer(const char *_cmd, vector<string> &args)
{
    string cmd = _cmd;
    if (cmd == "SYN") {
        m_ver = atol(args[0].c_str());
        if (m_ver == m_client->getListVer())
            return false;
        ContactList::GroupIterator itg;
        Group *grp;
        while ((grp = ++itg) != NULL) {
            MSNUserData *data;
            ClientDataIterator it(grp->clientData, m_client);
            while ((data = (MSNUserData*)(++it)) != NULL) {
                data->sFlags.value = data->Flags.value;
                data->Flags.value  = 0;
            }
        }
        ContactList::ContactIterator itc;
        Contact *contact;
        while ((contact = ++itc) != NULL) {
            MSNUserData *data;
            ClientDataIterator it(contact->clientData, m_client);
            while ((data = (MSNUserData*)(++it)) != NULL) {
                data->sFlags.value = data->Flags.value;
                data->Flags.value  = 0;
            }
        }
        return true;
    }
    if (cmd == "GTC")
        return true;
    if (cmd == "BLP")
        return true;
    if (cmd == "PRP") {
        if (args.size() < 2) {
            log(L_WARN, "Bad PRP size");
            return true;
        }
        if (args[0] == "PHH")
            set_str(&m_client->data.owner.PhoneHome.ptr, m_client->unquote(QString::fromUtf8(args[1].c_str())).utf8());
        if (args[0] == "PHW")
            set_str(&m_client->data.owner.PhoneWork.ptr, m_client->unquote(QString::fromUtf8(args[1].c_str())).utf8());
        if (args[0] == "PHM")
            set_str(&m_client->data.owner.PhoneMobile.ptr, m_client->unquote(QString::fromUtf8(args[1].c_str())).utf8());
        if (args[0] == "MBE")
            m_client->data.owner.Mobile.bValue = (args[1] == "Y");
        return true;
    }
    if (cmd == "BPR") {
        if (args.size() < 2) {
            log(L_WARN, "Bad BPR size");
            return true;
        }
        if (m_data == NULL) {
            log(L_WARN, "BRP without LST");
            return true;
        }
        if (args[0] == "PHH")
            set_str(&m_data->PhoneHome.ptr, m_client->unquote(QString::fromUtf8(args[1].c_str())).utf8());
        if (args[0] == "PHW")
            set_str(&m_data->PhoneWork.ptr, m_client->unquote(QString::fromUtf8(args[1].c_str())).utf8());
        if (args[0] == "PHM")
            set_str(&m_data->PhoneMobile.ptr, m_client->unquote(QString::fromUtf8(args[1].c_str())).utf8());
        if (args[0] == "MBE")
            m_data->Mobile.bValue = (args[1] == "Y");
        return true;
    }
    if (cmd == "LSG") {
        if (args.size() < 3) {
            log(L_WARN, "Bad LSG size");
            return true;
        }
        unsigned id = atol(args[0].c_str());
        if (id == 0)
            return true;
        Group *grp;
        string grp_name;
        grp_name = m_client->unquote(QString::fromUtf8(args[1].c_str())).utf8();
        MSNListRequest *lr = m_client->findRequest(id, LR_GROUPxREMOVED);
        if (lr)
            return true;
        MSNUserData *data = m_client->findGroup(id, NULL, grp);
        if (data) {
            lr = m_client->findRequest(grp->id(), LR_GROUPxCHANGED);
            if (lr) {
                data->sFlags.value |= MSN_CHECKED;
                return true;
            }
        }
        data = m_client->findGroup(id, grp_name.c_str(), grp);
        data->sFlags.value |= MSN_CHECKED;
        return true;
    }
    if (cmd == "LST") {
        if (m_data) {
            Contact *contact;
            if (m_client->findContact(m_data->EMail.ptr, contact)) {
                m_client->setupContact(contact, m_data);
                Event e(EventContactChanged, contact);
                e.process();
            }
        }
        if (args.size() < 3) {
            log(L_WARN, "Bad size for LST");
            return true;
        }
        string mail;
        mail = m_client->unquote(QString::fromUtf8(args[0].c_str())).utf8();
        string name;
        name = m_client->unquote(QString::fromUtf8(args[1].c_str())).utf8();
        Contact *contact;
        MSNListRequest *lr = m_client->findRequest(mail.c_str(), LR_CONTACTxREMOVED);
        if (lr)
            return true;
        bool bNew = false;
        m_data = m_client->findContact(mail.c_str(), contact);
        if (m_data == NULL) {
            m_data = m_client->findContact(mail.c_str(), name.c_str(), contact);
            bNew = true;
        } else {
            set_str(&m_data->EMail.ptr, mail.c_str());
            set_str(&m_data->ScreenName.ptr, name.c_str());
            if (name != (const char*)(contact->getName().utf8()))
                contact->setName(QString::fromUtf8(name.c_str()));
        }
        m_data->sFlags.value |= MSN_CHECKED;
        lr = m_client->findRequest(mail.c_str(), LR_CONTACTxCHANGED);
        unsigned grp = NO_GROUP;
        if (args.size() > 3)
            grp = atol(args[3].c_str());
        m_data->Group.value = grp;
        m_data->Flags.value |= MSN_FORWARD;
        set_str(&m_data->PhoneHome.ptr, NULL);
        set_str(&m_data->PhoneWork.ptr, NULL);
        set_str(&m_data->PhoneMobile.ptr, NULL);
        m_data->Mobile.bValue = false;
        Group *group = NULL;
        if ((grp == 0) || (grp == NO_GROUP)) {
            group = getContacts()->group(0);
        } else {
            m_client->findGroup(grp, NULL, group);
        }
        if ((lr == NULL) && group && (group->id() != contact->getGroup())) {
            unsigned grp = group->id();
            if (grp == 0) {
                void *d;
                ClientDataIterator it_d(contact->clientData);
                while ((d = ++it_d) != NULL) {
                    if (d != m_data)
                        break;
                }
                if (d) {
                    grp = contact->getGroup();
                    m_client->findRequest(m_data->EMail.ptr, LR_CONTACTxCHANGED, true);
                    MSNListRequest lr;
                    lr.Type = LR_CONTACTxCHANGED;
                    lr.Name = m_data->EMail.ptr;
                    m_client->m_requests.push_back(lr);
                }
            }
            contact->setGroup(grp);
        }
        return true;
    }
    bDone = true;
    return false;
}
Example #23
0
bool Container::processEvent(Event *e)
{
    if (m_tabBar == NULL)
        return false;
    switch (e->type()){
    case eEventMessageReceived: {
        EventMessage *em = static_cast<EventMessage*>(e);
        Message *msg = em->msg();
        if (msg->type() == MessageStatus){
            Contact *contact = getContacts()->contact(msg->contact());
            if (contact)
                contactChanged(contact);
            return false;
        }
        if (msg->getFlags() & MESSAGE_NOVIEW)
            return false;
        if (CorePlugin::m_plugin->getContainerMode()){
            if (isActiveWindow() && !isMinimized()){
                UserWnd *userWnd = m_tabBar->currentWnd();
                if (userWnd && (userWnd->id() == msg->contact()))
                    userWnd->markAsRead();
            }else{
                UserWnd *userWnd = wnd(msg->contact());
                if (userWnd)
                    QTimer::singleShot(0, this, SLOT(flash()));
            }
        }
        // no break here - otherwise we have to duplicate the code below...
    }
    case eEventMessageRead: {
        EventMessage *em = static_cast<EventMessage*>(e);
        Message *msg = em->msg();
        UserWnd *userWnd = wnd(msg->contact());
        if (userWnd){
            bool bBold = false;
            for (list<msg_id>::iterator it = CorePlugin::m_plugin->unread.begin(); it != CorePlugin::m_plugin->unread.end(); ++it){
                if ((*it).contact != msg->contact())
                    continue;
                bBold = true;
                break;
            }
            m_tabBar->setBold(msg->contact(), bBold);
        }
        break;
    }
    case eEventActiveContact: {
        EventActiveContact *eac = static_cast<EventActiveContact*>(e);
        if (!isActiveWindow())
            return false;
        UserWnd *userWnd = m_tabBar->currentWnd();
        if (userWnd) {
            eac->setContactID(userWnd->id());
            return true;
        }
        break;
    }
    case eEventContact: {
        EventContact *ec = static_cast<EventContact*>(e);
        Contact *contact = ec->contact();
        UserWnd *userWnd = wnd(contact->id());
        if(!userWnd)
            break;
        switch(ec->action()) {
            case EventContact::eDeleted: {
                removeUserWnd(userWnd);
                break;
            }
            case EventContact::eChanged: {
                if (contact->getIgnore()){
                    removeUserWnd(userWnd);
                    break;
                }
                m_tabBar->changeTab(contact->id());
                contactChanged(contact);
                break;
            }
            case EventContact::eStatus: {
                unsigned style = 0;
                QString wrkIcons;
                QString statusIcon;
                contact->contactInfo(style, statusIcon, &wrkIcons);
                bool bTyping = false;
                while (!wrkIcons.isEmpty()){
                    if (getToken(wrkIcons, ',') == "typing"){
                        bTyping = true;
                        break;
                    }
                }
                if (userWnd->m_bTyping != bTyping){
                    userWnd->m_bTyping = bTyping;
                    if (bTyping){
                        userWnd->setStatus(g_i18n("%1 is typing", contact) .arg(contact->getName()));
                    }else{
                        userWnd->setStatus("");
                    }
                    userWnd = m_tabBar->currentWnd();
                    if (userWnd && (contact->id() == userWnd->id()))
                        m_status->message(userWnd->status());
                }
            }
            default:
                break;
        }
        break;
    }
    case eEventClientsChanged:
        setupAccel();
        break;
    case eEventContactClient: {
        EventContactClient *ecc = static_cast<EventContactClient*>(e);
        contactChanged(ecc->contact());
        break;
    }
    case eEventInit:
        init();
        break;
    case eEventCommandExec: {
        EventCommandExec *ece = static_cast<EventCommandExec*>(e);
        CommandDef *cmd = ece->cmd();
        UserWnd *userWnd = m_tabBar->currentWnd();
        if (userWnd && ((unsigned long)(cmd->param) == userWnd->id())){
            if (cmd->menu_id == MenuContainerContact){
                m_tabBar->raiseTab(cmd->id);
                return true;
            }
            if (cmd->id == CmdClose){
                delete userWnd;
                return true;
            }
            if (cmd->id == CmdInfo && cmd->menu_id != MenuContact){
                CommandDef c = *cmd;
                c.menu_id = MenuContact;
                c.param   = (void*)userWnd->id();
                EventCommandExec(&c).process();
                return true;
            }
        }
        break;
    }
    case eEventCheckCommandState: {
        EventCheckCommandState *ecs = static_cast<EventCheckCommandState*>(e);
        CommandDef *cmd = ecs->cmd();
        UserWnd *userWnd = m_tabBar->currentWnd();
        if (userWnd && ((unsigned long)(cmd->param) == userWnd->id()) &&
                (cmd->menu_id == MenuContainerContact) &&
                (cmd->id == CmdContainerContacts)){
            list<UserWnd*> userWnds = m_tabBar->windows();
            CommandDef *cmds = new CommandDef[userWnds.size() + 1];
            unsigned n = 0;
            for (list<UserWnd*>::iterator it = userWnds.begin(); it != userWnds.end(); ++it){
                cmds[n].id = (*it)->id();
                cmds[n].flags = COMMAND_DEFAULT;
                cmds[n].text_wrk = (*it)->getName();
                cmds[n].icon  = (*it)->getIcon();
                cmds[n].text  = "_";
                cmds[n].menu_id = n + 1;
                if (n < sizeof(accels) / sizeof(const char*))
                    cmds[n].accel = accels[n];
                if (*it == m_tabBar->currentWnd())
                    cmds[n].flags |= COMMAND_CHECKED;
                n++;
            }
            cmd->param = cmds;
            cmd->flags |= COMMAND_RECURSIVE;
            return true;
        }
        break;
    }
    default:
        break;
    }
    return false;
}
Example #24
0
bool JabberClient::send(Message *msg, void *_data)
{
    if (getState() != Connected)
        return false;
    JabberUserData *data = (JabberUserData*)_data;
    switch (msg->type()){
    case MessageAuthRefused:{
            string grp;
            Group *group = NULL;
            Contact *contact = getContacts()->contact(msg->contact());
            if (contact && contact->getGroup())
                group = getContacts()->group(contact->getGroup());
            if (group)
                grp = group->getName().utf8();
            listRequest(data, data->Name, grp.c_str(), false);
            if (data->Subscribe & SUBSCRIBE_FROM){
                m_socket->writeBuffer.packetStart();
                m_socket->writeBuffer
                << "<presence to=\""
                << data->ID;
                m_socket->writeBuffer
                << "\" type=\"unsubscribed\"><status>"
                << (const char*)(quoteString(msg->getPlainText(), false).utf8())
                << "</status></presence>";
                sendPacket();
                if ((msg->getFlags() & MESSAGE_NOHISTORY) == 0){
                    msg->setClient(dataName(data).c_str());
                    Event e(EventSent, msg);
                    e.process();
                }
                Event e(EventMessageSent, msg);
                e.process();
                delete msg;
                return true;
            }
        }
    case MessageGeneric:{
            Contact *contact = getContacts()->contact(msg->contact());
            if ((contact == NULL) || (data == NULL))
                return false;
            m_socket->writeBuffer.packetStart();
            m_socket->writeBuffer
            << "<message to=\""
            << data->ID;
            m_socket->writeBuffer
            << "\"><body>"
            << (const char*)msg->getPlainText().utf8()
            << "</body></message>";
            sendPacket();
            if ((msg->getFlags() & MESSAGE_NOHISTORY) == 0){
                msg->setClient(dataName(data).c_str());
                Event e(EventSent, msg);
                e.process();
            }
            Event e(EventMessageSent, msg);
            e.process();
            delete msg;
            return true;
        }
    case MessageAuthRequest:{
            m_socket->writeBuffer.packetStart();
            m_socket->writeBuffer
            << "<presence to=\""
            << data->ID;
            m_socket->writeBuffer
            << "\" type=\"subscribe\"><status>"
            << (const char*)(quoteString(msg->getPlainText(), false).utf8())
            << "</status></presence>";
            sendPacket();
            if ((msg->getFlags() & MESSAGE_NOHISTORY) == 0){
                msg->setClient(dataName(data).c_str());
                Event e(EventSent, msg);
                e.process();
            }
            Event e(EventMessageSent, msg);
            e.process();
            delete msg;
            return true;
        }
    case MessageAuthGranted:{
            m_socket->writeBuffer.packetStart();
            m_socket->writeBuffer
            << "<presence to=\""
            << data->ID;
            m_socket->writeBuffer
            << "\" type=\"subscribed\"></presence>";
            sendPacket();
            if ((msg->getFlags() & MESSAGE_NOHISTORY) == 0){
                msg->setClient(dataName(data).c_str());
                Event e(EventSent, msg);
                e.process();
            }
            Event e(EventMessageSent, msg);
            e.process();
            delete msg;
            return true;
        }
    case MessageJabberOnline:
        if (isAgent(data->ID) && (data->Status == STATUS_OFFLINE)){
            m_socket->writeBuffer.packetStart();
            m_socket->writeBuffer
            << "<presence to=\""
            << data->ID
            << "\"></presence>";
            sendPacket();
            delete msg;
            return true;
        }
        break;
    case MessageJabberOffline:
        if (isAgent(data->ID) && (data->Status != STATUS_OFFLINE)){
            m_socket->writeBuffer.packetStart();
            m_socket->writeBuffer
            << "<presence to=\""
            << data->ID
            << "\" type=\"unavailable\"></presence>";
            sendPacket();
            delete msg;
            return true;
        }
        break;
    }
    return false;
}
Example #25
0
void *Services::processEvent(Event *e)
{
    if (e->type() == static_cast<JabberPlugin*>(m_client->protocol()->plugin())->EventAgentFound){
        JabberAgentsInfo *data = (JabberAgentsInfo*)(e->param());
        if ((data->Client == m_client) && data->Register.bValue){
            AGENTS_MAP::iterator it = m_agents.find(data->ID.ptr);
            if (it == m_agents.end()){
                agentInfo info;
                info.search = NULL;
                info.name   = data->Name.ptr;
                m_agents.insert(AGENTS_MAP::value_type(data->ID.ptr, info));
                m_client->get_agent_info(data->ID.ptr, NULL, "register");
            }
        }
        return NULL;
    }
    if (e->type() == static_cast<JabberPlugin*>(m_client->protocol()->plugin())->EventAgentInfo){
        JabberAgentInfo *data = (JabberAgentInfo*)(e->param());
        if (data->ID.ptr == NULL)
            return NULL;
        AGENTS_MAP::iterator it = m_agents.find(data->ID.ptr);
        if (it != m_agents.end()){
            agentInfo &info = (*it).second;
            if (info.search == NULL){
                info.search = new JabberSearch(this, m_client, data->ID.ptr, NULL, QString::fromUtf8(info.name.c_str()), true);
                unsigned id = cmbAgents->count();
                wndInfo->addWidget(info.search, id + 1);
                cmbAgents->insertItem(QString::fromUtf8(info.name.c_str()));
                if (id == 0){
                    cmbAgents->setCurrentItem(0);
                    selectAgent(0);
                    textChanged("");
                }
            }
            info.search->addWidget(data);
        }
        return NULL;
    }
    if (e->type() == static_cast<JabberPlugin*>(m_client->protocol()->plugin())->EventAgentRegister){
        agentRegisterInfo *info = (agentRegisterInfo*)(e->param());
        if (m_reg_id != info->id)
            return NULL;
        if (info->err_code){
            QString err;
            if (info->error && *info->error)
                err = i18n(info->error);
            if (err.isEmpty())
                err = i18n("Error %1") .arg(info->err_code);
            BalloonMsg::message(err, btnRegister);
        }
        btnRegister->setEnabled(true);
        return NULL;
    }
    switch (e->type()){
    case EventClientChanged:
        if ((Client*)(e->param()) == m_client)
            statusChanged();
        break;
    case EventContactChanged:{
            Contact *contact = (Contact*)(e->param());
            ClientDataIterator it(contact->clientData, m_client);
            JabberUserData *data;
            while ((data = ((JabberUserData*)(++it))) != NULL){
                if (!m_client->isAgent(data->ID.ptr))
                    continue;
                QListViewItem *item;
                for (item = lstAgents->firstChild(); item; item = item->nextSibling())
                    if ((item->text(COL_JID) + "/registered") == QString::fromUtf8(data->ID.ptr))
                        break;
                if (item == NULL)
                    makeAgentItem(data, contact->id());
            }
            break;
        }
    case EventMessageReceived:{
            Message *msg = (Message*)(e->param());
            if (msg->type() != MessageStatus)
                break;
            Contact *contact = getContacts()->contact(msg->contact());
            if (contact == NULL)
                break;
            ClientDataIterator it(contact->clientData, m_client);
            JabberUserData *data;
            while ((data = ((JabberUserData*)(++it))) != NULL){
                if (!m_client->isAgent(data->ID.ptr))
                    continue;
                QListViewItem *item;
                for (item = lstAgents->firstChild(); item; item = item->nextSibling())
                    if ((item->text(COL_JID) + "/registered") == QString::fromUtf8(data->ID.ptr))
                        break;
                if (item)
                    setAgentStatus(data, item);
            }
            break;
        }
    case EventContactDeleted:{
            Contact *contact = (Contact*)(e->param());
            for (QListViewItem *item = lstAgents->firstChild(); item; ){
                QListViewItem *next = item->nextSibling();
                if (item->text(COL_ID) == QString::number(contact->id()))
                    delete item;
                item = next;
            }
            break;
        }
    }
    return NULL;
}
Example #26
0
void *JabberClient::processEvent(Event *e)
{
    if (e->type() == EventTemplateExpanded){
        TemplateExpand *t = (TemplateExpand*)(e->param());
        setStatus((unsigned)(t->param), quoteString(t->tmpl, false).utf8());
    }
    if (e->type() == EventContactChanged){
        Contact *contact = (Contact*)(e->param());
        string grpName;
        string name;
        name = contact->getName().utf8();
        Group *grp = NULL;
        if (contact->getGroup())
            grp = getContacts()->group(contact->getGroup());
        if (grp)
            grpName = grp->getName().utf8();
        ClientDataIterator it(contact->clientData, this);
        JabberUserData *data;
        while ((data = (JabberUserData*)(++it)) != NULL){
            if (!cmp(grpName, data->Group)){
                listRequest(data, name.c_str(), grpName.c_str(), false);
                continue;
            }
            if (data->Name && *data->Name){
                if (!cmp(name, data->Name))
                    listRequest(data, name.c_str(), grpName.c_str(), false);
                continue;
            }
            if (!cmp(name, data->ID))
                listRequest(data, name.c_str(), grpName.c_str(), false);
        }
        return NULL;
    }
    if (e->type() == EventContactDeleted){
        Contact *contact = (Contact*)(e->param());
        ClientDataIterator it(contact->clientData, this);
        JabberUserData *data;
        while ((data = (JabberUserData*)(++it)) != NULL){
            listRequest(data, NULL, NULL, true);
        }
        return NULL;
    }
    if (e->type() == EventGroupChanged){
        Group *grp = (Group*)(e->param());
        string grpName;
        grpName = grp->getName().utf8();
        ContactList::ContactIterator itc;
        Contact *contact;
        while ((contact = ++itc) != NULL){
            if (contact->getGroup() != grp->id())
                continue;
            ClientDataIterator it(contact->clientData, this);
            JabberUserData *data;
            while ((data = (JabberUserData*)(++it)) != NULL){
                if (!cmp(grpName, data->Group))
                    listRequest(data, contact->getName().utf8(), grpName.c_str(), false);
            }
        }
    }
    return NULL;
}
Example #27
0
bool NameServiceOnTriples::cmdRegister(NameTripleState& act) {
    ConstString port = act.cmd.get(1).asString();

    lock();
    Triple t;
    t.setNameValue("port",port.c_str());
    int result = act.mem.find(t,NULL);
    unlock();
    if (result!=-1) {
        // Hmm, we already have a registration.
        // This could be fine - maybe program crashed or was abruptly
        // terminated.  Classically, that is what YARP would assume.
        // Now, let us try checking instead to see if there is a port
        // alive at the registered address.  Note that this can lead
        // to delays...
#if 0
        Contact c = query(port.c_str());
        if (c.isValid()) {
            if (gonePublic) {
                printf(" ? checking prior registration, to avoid accidental collision\n");
                Bottle cmd("[ver]"), reply;
                double timeout = 3.0;
                double pre = Time::now();
                bool ok = Network::write(c,cmd,reply,true,true,timeout);
                double post = Time::now();
                if (post-pre>timeout-1) {
                    ok = false;
                }
                if (ok) {
                    printf(" ? prior registration seems to be live! Denying new registration.\n");
                    /*
                      printf("Got a live one! %s - said %s\n", 
                      port.c_str(),
                      reply.toString().c_str());
                    */
                    // oops! there is a live port!
                    // give back a blank query
                    act.cmd.fromString("query");
                    return cmdQuery(act);
                } else {
                    printf(" ! prior registration seems to be no longer valid, good!\n");
                }
            }
        }
#endif
        cmdUnregister(act);
        act.reply.clear();
    }

    act.reply.addString("old");
    
    int at = 2;
    int sock = -1;
    ConstString carrier = "...";
    ConstString machine = "...";
    ConstString typ = "*";
    if (act.cmd.size()>at) {
        carrier = act.cmd.get(at).asString();
        at++;
    }
    if (carrier=="...") {
        carrier = "tcp";
    }
    if (act.cmd.size()>at) {
        machine = act.cmd.get(at).asString();
        at++;
    }
    if (machine == "...") {
        if (carrier=="topic") {
            machine = serverContact.getHost().c_str();
        } else if (carrier!="mcast") {
            string remote = act.remote.getHost().c_str();
            if (remote==""||remote=="...") {
                //fprintf(stderr,"Not detecting real remote machine name, guessing local\n");
                machine = "localhost";
            } else {
                machine = remote.c_str();
            }
        }
    }
    if (act.cmd.size()>at) {
        sock = act.cmd.get(at).asInt();
        at++;
    } else {
        if (carrier=="topic") {
            sock = serverContact.getPort();
        }
    }
    if (act.cmd.size()>at) {
        typ = act.cmd.get(at).asString();
        at++;
    }
    lock();
    if (port=="..." || (port.length()>0 && port[0]=='=')) {
        Contact c = Contact::byName(port.c_str()).addSocket(carrier.c_str(),machine.c_str(),sock);
        c = alloc->completePortName(c);
        if (port =="...") {
            port = c.getName();
        } else {
            port = c.getName() + port;
        }
    }
    t.setNameValue("port",port.c_str());
    act.mem.remove_query(t,NULL);
    act.mem.insert(t,NULL);
    result = act.mem.find(t,NULL);
    TripleContext context;
    context.setRid(result);
    t.setNameValue("carrier",carrier.c_str());
    act.mem.update(t,&context);
    char buf[100];
    Contact c = Contact::byName(port.c_str()).addSocket(carrier.c_str(),machine.c_str(),sock);
    c = alloc->completeSocket(c);
    sock = c.getPort();
    machine = c.getHost().c_str();
    t.setNameValue("host",machine.c_str());
    act.mem.update(t,&context);
    sprintf(buf,"%d",sock);
    t.setNameValue("socket",buf);
    act.mem.update(t,&context);
    if (typ!="*") {
        t.setNameValue("type",typ.c_str());
        act.mem.update(t,&context);
    }
    // now, query to report that it worked
    act.mem.reset();
    act.cmd.clear();
    act.cmd.addString("query");
    act.cmd.addString(port.c_str());

    if (carrier!="mcast") {
        Bottle& event = act.event.addList();
        event.addVocab(Vocab::encode("add"));
        event.addString(port.c_str());
    }
    unlock();

    return cmdQuery(act);
}
Example #28
0
void JabberClient::setStatus(unsigned status, const char *ar)
{
    if (status  != m_status){
        time_t now;
        time(&now);
        data.owner.StatusTime = now;
        if (m_status == STATUS_OFFLINE)
            data.owner.OnlineTime = now;
        m_status = status;
        m_socket->writeBuffer.packetStart();
        const char *priority = "5";
        const char *show = NULL;
        const char *type = NULL;
        if (getInvisible()){
            type = "invisible";
        }else{
            switch (status){
            case STATUS_AWAY:
                show = "away";
                break;
            case STATUS_NA:
                show = "xa";
                break;
            case STATUS_DND:
                show = "dnd";
                break;
            case STATUS_FFC:
                show = "chat";
                break;
            case STATUS_OFFLINE:
                priority = NULL;
                type = "unavailable";
                break;
            }
        }
        m_socket->writeBuffer << "<presence";
        if (type)
            m_socket->writeBuffer << " type=\"" << type << "\"";
        m_socket->writeBuffer << ">\n";
        if (show && *show)
            m_socket->writeBuffer << "<show>" << show << "</show>\n";
        if (ar && *ar){
            m_socket->writeBuffer << "<status>" << ar << "</status>\n";
        }
        if (priority)
            m_socket->writeBuffer << "<priority>" << priority << "</priority>\n";
        m_socket->writeBuffer << "</presence>";
        sendPacket();
        Event e(EventClientChanged, static_cast<Client*>(this));
        e.process();
    }
    if (status == STATUS_OFFLINE){
        if (m_socket){
            m_socket->writeBuffer.packetStart();
            m_socket->writeBuffer
            << "</stream:stream>\n";
            sendPacket();
        }
        Contact *contact;
        ContactList::ContactIterator it;
        time_t now;
        time(&now);
        data.owner.StatusTime = now;
        while ((contact = ++it) != NULL){
            JabberUserData *data;
            ClientDataIterator it(contact->clientData, this);
            while ((data = (JabberUserData*)(++it)) != NULL){
                if (data->Status == STATUS_OFFLINE)
                    continue;
                data->StatusTime = now;
                setOffline(data);
                StatusMessage m;
                m.setContact(contact->id());
                m.setClient(dataName(data).c_str());
                m.setFlags(MESSAGE_RECEIVED);
                m.setStatus(STATUS_OFFLINE);
                Event e(EventMessageReceived, &m);
                e.process();
            }
        }
    }
}
Example #29
0
static int enactConnection(const Contact& src,
                           const Contact& dest,
                           const ContactStyle& style,
                           int mode,
                           bool reversed) {
    ContactStyle rpc;
    rpc.admin = true;
    rpc.quiet = style.quiet;
    rpc.timeout = style.timeout;

    if (style.persistent) {
        bool ok = false;
        // we don't talk to the ports, we talk to the nameserver
        NameSpace& ns = getNameSpace();
        if (mode==YARP_ENACT_CONNECT) {
            ok = ns.connectPortToPortPersistently(src,dest,style);
        } else if (mode==YARP_ENACT_DISCONNECT) {
            ok = ns.disconnectPortToPortPersistently(src,dest,style);
        } else {
            fprintf(stderr,"Failure: cannot check subscriptions yet\n");
            return 1;
        }
        if (!ok) {
            return 1;
        }
        if (!style.quiet) {
            fprintf(stderr,"Success: port-to-port persistent connection added.\n");
        }
        return 0;
    }

    if (mode==YARP_ENACT_EXISTS) {
        Bottle cmd, reply;
        cmd.addVocab(Vocab::encode("list"));
        cmd.addVocab(Vocab::encode(reversed?"in":"out"));
        cmd.addString(dest.getName().c_str());
        YARP_SPRINTF2(Logger::get(),debug,"asking %s: %s",
                      src.toString().c_str(), cmd.toString().c_str());
        bool ok = NetworkBase::write(src,cmd,reply,rpc);
        if (!ok) {
            noteDud(src);
            return 1;
        }
        if (reply.check("carrier")) {
            if (!style.quiet) {
                printf("Connection found between %s and %s\n",
                       src.getName().c_str(), dest.getName().c_str());
            }
            return 0;
        }
        return 1;
    }

    int act = (mode==YARP_ENACT_DISCONNECT)?VOCAB3('d','e','l'):VOCAB3('a','d','d');

    // Let's ask the destination to connect/disconnect to the source.
    // We assume the YARP carrier will reverse the connection if
    // appropriate when connecting.
    Bottle cmd, reply;
    cmd.addVocab(act);
    Contact c = dest;
    if (style.carrier!="") {
        c = c.addCarrier(style.carrier);
    }
    if (mode!=YARP_ENACT_DISCONNECT) {
        cmd.addString(c.toString());
    } else {
        cmd.addString(c.getName());
    }

    Contact c2 = src;
    if (c2.getPort()<=0) {
        c2 = NetworkBase::queryName(c2.getName());
    }
    if (c2.getCarrier()!="tcp") {
        YARP_SPRINTF2(Logger::get(),debug,"would have asked %s: %s",
                      src.toString().c_str(), cmd.toString().c_str());
        return 1;
    }

    YARP_SPRINTF2(Logger::get(),debug,"** asking %s: %s",
                  src.toString().c_str(), cmd.toString().c_str());
    bool ok = NetworkBase::write(c2,cmd,reply,rpc);
    if (!ok) {
        noteDud(src);
        return 1;
    }
    ok = false;
    ConstString msg = "";
    if (reply.get(0).isInt()) {
        ok = (reply.get(0).asInt()==0);
        msg = reply.get(1).asString();
    } else {
        // older protocol
        msg = reply.get(0).asString();
        ok = msg[0]=='A'||msg[0]=='R';
    }
    if (mode==YARP_ENACT_DISCONNECT && !ok) {
        msg = "no such connection\n";
    }
    if (mode==YARP_ENACT_CONNECT && !ok) {
        noteDud(dest);
    }
    if (!style.quiet) {
        if (style.verboseOnSuccess||!ok) {
            fprintf(stderr,"%s %s",
                    ok?"Success:":"Failure:",
                    msg.c_str());
        }
    }
    return ok?0:1;
}
void
RadioTraffic::DisplayMessage(RadioMessage* msg)
{
	if (!msg) return;

	char txt_buf[256];   txt_buf[0] = 0;
	char msg_buf[128];   msg_buf[0] = 0;
	char src_buf[64];    src_buf[0] = 0;
	char dst_buf[64];    dst_buf[0] = 0;
	char act_buf[64];    act_buf[0] = 0;
	int  vox_channel = 0;

	Ship*    dst_ship = msg->DestinationShip();
	Element* dst_elem = msg->DestinationElem();

	// BUILD SRC AND DST BUFFERS -------------------

	if (msg->Sender()) {
		const Ship* sender = msg->Sender();

		// orders to self?
		if (dst_elem && dst_elem->NumShips() == 1 && dst_elem->GetShip(1) == sender) {
			if (msg->Action() >= RadioMessage::CALL_ENGAGING) {
				sprintf_s(src_buf, "%s", sender->Name());

				if (sender->IsStarship())
				vox_channel = (sender->Identity()%3) + 5;
			}
		}

		// orders to other ships:
		else {
			if (sender->IsStarship()) {
				vox_channel = (sender->Identity()%3) + 5;
			}
			else {
				vox_channel = sender->GetElementIndex();
			}

			if (msg->Action() >= RadioMessage::CALL_ENGAGING) {
				sprintf_s(src_buf, "%s", sender->Name());
			}
			else {
				sprintf_s(src_buf, "This is %s", sender->Name());

				if (dst_ship) {
					// internal announcement
					if (dst_ship->GetElement() == sender->GetElement()) {
						dst_elem  = sender->GetElement();
						int index = sender->GetElementIndex();

						if (index > 1 && dst_elem) {
							sprintf_s(dst_buf, "%s Leader",     (const char*) dst_elem->Name());
							sprintf_s(src_buf, "this is %s %d", (const char*) dst_elem->Name(), index);
						}
						else {
							sprintf_s(src_buf, "this is %s leader", (const char*) dst_elem->Name());
						}
					}

					else {
						strcpy_s(dst_buf, (const char*) dst_ship->Name());
						src_buf[0] = tolower(src_buf[0]);
					}
				}

				else if (dst_elem) {
					// flight
					if (dst_elem->NumShips() > 1) {
						sprintf_s(dst_buf, "%s Flight", (const char*) dst_elem->Name());

						// internal announcement
						if (sender->GetElement() == dst_elem) {
							int index = sender->GetElementIndex();

							if (index > 1) {
								sprintf_s(dst_buf, "%s Leader",     (const char*) dst_elem->Name());
								sprintf_s(src_buf, "this is %s %d", (const char*) dst_elem->Name(), index);
							}
							else {
								sprintf_s(src_buf, "this is %s leader", (const char*) dst_elem->Name());
							}
						}
					}

					// solo
					else {
						strcpy_s(dst_buf, (const char*) dst_elem->Name());
						src_buf[0] = tolower(src_buf[0]);
					}
				}
			}
		}
	}

	// BUILD ACTION AND TARGET BUFFERS -------------------

	SimObject* target = 0;

	strcpy_s(act_buf, RadioMessage::ActionName(msg->Action()));

	if (msg->TargetList().size() > 0)
	target = msg->TargetList()[0];

	if (msg->Action() == RadioMessage::ACK ||
			msg->Action() == RadioMessage::NACK) {

		if (dst_ship == msg->Sender()) {
			src_buf[0] = 0;
			dst_buf[0] = 0;

			if (msg->Action() == RadioMessage::ACK)
			sprintf_s(msg_buf, "%s.", TranslateVox("Acknowledged").data());
			else
			sprintf_s(msg_buf, "%s.", TranslateVox("Unable").data());
		}
		else if (msg->Sender()) {
			dst_buf[0] = 0;

			if (msg->Info().length()) {
				sprintf_s(msg_buf, "%s. %s", 
				TranslateVox(act_buf).data(),
				(const char*) msg->Info());
			}
			else {
				sprintf_s(msg_buf, "%s.", TranslateVox(act_buf).data());
			}
		}
		else {
			if (msg->Info().length()) {
				sprintf_s(msg_buf, "%s. %s", 
				TranslateVox(act_buf).data(),
				(const char*) msg->Info());
			}
			else {
				sprintf_s(msg_buf, "%s.", TranslateVox(act_buf).data());
			}
		}
	}

	else if (msg->Action() == RadioMessage::MOVE_PATROL) {
		sprintf_s(msg_buf, TranslateVox("Move patrol.").data());
	}

	else if (target && dst_ship && msg->Sender()) {
		Contact* c = msg->Sender()->FindContact(target);

		if (c && c->GetIFF(msg->Sender()) > 10) {
			sprintf_s(msg_buf, "%s %s.", TranslateVox(act_buf).data(), TranslateVox("unknown contact").data());
		}

		else {
			sprintf_s(msg_buf, "%s %s.", 
			TranslateVox(act_buf).data(),
			target->Name());
		}
	}

	else if (target) {
		sprintf_s(msg_buf, "%s %s.", 
		TranslateVox(act_buf).data(),
		target->Name());
	}

	else if (msg->Info().length()) {
		sprintf_s(msg_buf, "%s %s", 
		TranslateVox(act_buf).data(),
		(const char*) msg->Info());
	}

	else {
		strcpy_s(msg_buf, TranslateVox(act_buf).data());
	}

	char last_char = msg_buf[strlen(msg_buf)-1];
	if (last_char != '!' && last_char != '.' && last_char != '?')
	strcat_s(msg_buf, ".");

	// final format:
	if (dst_buf[0] && src_buf[0]) {
		sprintf_s(txt_buf, "%s %s. %s", TranslateVox(dst_buf).data(), TranslateVox(src_buf).data(), msg_buf);
		txt_buf[0] = toupper(txt_buf[0]);
	}

	else if (src_buf[0]) {
		sprintf_s(txt_buf, "%s. %s", TranslateVox(src_buf).data(), msg_buf);
		txt_buf[0] = toupper(txt_buf[0]);
	}

	else if (dst_buf[0]) {
		sprintf_s(txt_buf, "%s %s", TranslateVox(dst_buf).data(), msg_buf);
		txt_buf[0] = toupper(txt_buf[0]);
	}

	else {
		strcpy_s(txt_buf, msg_buf);
	}

	// vox:
	const char* path[8] = { "1", "1", "2", "3", "4", "5", "6", "7" };

	RadioVox* vox = new(__FILE__,__LINE__) RadioVox(vox_channel, path[vox_channel], txt_buf);

	vox->AddPhrase(dst_buf);
	vox->AddPhrase(src_buf);
	vox->AddPhrase(act_buf);

	if (vox && !vox->Start()) {
		RadioView::Message(txt_buf);
		delete vox;
	}
}