womim * receive(trComm * aComm){ womim * msgExt; int nbRead, nbRead2; int length; int j; bool isPred; nbRead = commReadFully(aComm, &length, sizeof(length)); if (nbRead == sizeof(length)) { msgExt = calloc(length + sizeof(prefix), sizeof(char)); assert(msgExt != NULL); nbRead2 = commReadFully(aComm, ((char*) msgExt) + sizeof(prefix) + nbRead, (length - nbRead)); if (nbRead2 == length - nbRead) { pthread_mutex_init(&(msgExt->pfx.mutex), NULL ); msgExt->pfx.counter = 1; msgExt->msg.len = length; return (msgExt); } else { free(msgExt); } } //Connection has been closed //search the address which has vanished searchTComm(aComm, globalAddrArray, &j, &isPred); if (j == -1) { // It may happen when automaton has closed all the connections (thus // has erased aComm from globalAddrArray). As we are already aware of // this connection loss, there is nothing to do. return NULL ; } //create the DISCONNECT to return MType disconnectType; if (isPred) { disconnectType = DISCONNECT_PRED; } else { disconnectType = DISCONNECT_SUCC; } msgExt = calloc( sizeof(prefix) + sizeof(newMsg(disconnectType, rankToAddr(j))), sizeof(char)); pthread_mutex_init(&(msgExt->pfx.mutex), NULL ); msgExt->pfx.counter = 1; msgExt->msg = newMsg(disconnectType, rankToAddr(j)); //close the connection closeConnection(rankToAddr(j), isPred); return (msgExt); }
/** Constructor */ CreateForumMsg::CreateForumMsg(const std::string &fId, const std::string &pId) : QDialog(NULL), mForumId(fId), mParentId(pId) { /* Invoke the Qt Designer generated object setup routine */ ui.setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); QString text = pId.empty() ? tr("Start New Thread") : tr("Post Forum Message"); setWindowTitle(text); ui.headerFrame->setHeaderImage(QPixmap(":/images/konversation64.png")); ui.headerFrame->setHeaderText(text); Settings->loadWidgetInformation(this); connect( ui.forumMessage, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( forumMessageCostumPopupMenu( QPoint ) ) ); connect(ui.hashBox, SIGNAL(fileHashingFinished(QList<HashedFile>)), this, SLOT(fileHashingFinished(QList<HashedFile>))); // connect up the buttons. connect( ui.buttonBox, SIGNAL(accepted()), this, SLOT(createMsg())); connect( ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); connect( ui.emoticonButton, SIGNAL(clicked()), this, SLOT(smileyWidgetForums())); connect( ui.attachFileButton, SIGNAL(clicked() ), this , SLOT(addFile())); connect( ui.pastersButton, SIGNAL(clicked() ), this , SLOT(pasteLink())); setAcceptDrops(true); ui.hashBox->setDropWidget(this); ui.hashBox->setAutoHide(false); newMsg(); }
void ChatManager::SendSay(uint32_t clientNum, gemActor *actor, psChatMessage& msg,const char* who) { float range = 0; psSectorInfo * sectorinfo = NULL; iSector * sector = actor->GetMeshWrapper()->GetMovable()->GetSectors()->Get(0); if (sector) { sectorinfo = psserver->GetCacheManager()->GetSectorInfoByName(sector->QueryObject()->GetName()); if (sectorinfo) { range = sectorinfo->say_range; } } if (range == 0) // If 0 set default range = CHAT_SAY_RANGE; psChatMessage newMsg(clientNum, actor->GetEID(), who, 0, msg.sText, msg.iChatType, msg.translate); csArray<PublishDestination>& clients = actor->GetMulticastClients(); newMsg.Multicast(clients, 0, range); // The message is saved to the chat history of all the clients around (PS#2789) for (size_t i = 0; i < clients.GetSize(); i++) { Client *target = psserver->GetConnections()->Find(clients[i].client); if (target && clients[i].dist < range) target->GetActor()->LogChatMessage(actor->GetFirstName(), newMsg); } }
/** Constructor */ CreateForumMsg::CreateForumMsg(std::string fId, std::string pId) : QMainWindow(NULL), mForumId(fId), mParentId(pId) { /* Invoke the Qt Designer generated object setup routine */ ui.setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); Settings->loadWidgetInformation(this); connect( ui.forumMessage, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( forumMessageCostumPopupMenu( QPoint ) ) ); connect(ui.hashBox, SIGNAL(fileHashingFinished(QList<HashedFile>)), this, SLOT(fileHashingFinished(QList<HashedFile>))); // connect up the buttons. connect( ui.postmessage_action, SIGNAL( triggered (bool) ), this, SLOT( createMsg( ) ) ); connect( ui.close_action, SIGNAL( triggered (bool) ), this, SLOT( cancelMsg( ) ) ); connect( ui.emoticonButton, SIGNAL(clicked()), this, SLOT(smileyWidgetForums())); connect( ui.attachFileButton, SIGNAL(clicked() ), this , SLOT(addFile())); connect( ui.pastersButton, SIGNAL(clicked() ), this , SLOT(pasteLink())); setAcceptDrops(true); ui.hashBox->setDropWidget(this); ui.hashBox->setAutoHide(false); newMsg(); }
void TextMessageDlg::slotNewMessage(const TextMessage& textmsg) { if(textmsg.nFromUserID == m_userid) { newMsg(textmsg, true); } }
void GetMsg::m_handleNewMsg(QString msgId, QString content, QString fromUserNameStr, QString toUserNameStr, int createTime) { if (msgId.isEmpty() || content.isEmpty()) return; QString createTimeStr = QString::number(createTime); if (!m_map.contains(msgId)) { if (m_needSaveLog) m_saveLog(createTimeStr, fromUserNameStr, content); Q_EMIT newMsg(content, fromUserNameStr, toUserNameStr); } if ((fromUserNameStr == m_fromUserName && toUserNameStr == m_toUserName) || (fromUserNameStr == m_toUserName && toUserNameStr == m_fromUserName)) { if (!m_map.contains(msgId)) Q_EMIT received(content, fromUserNameStr); } if (m_map.size() > 64) { while (m_map.size() > 64 / 2) m_map.erase(m_map.begin()); } m_map.insert(msgId, createTime); }
//Use to send all the messages Msg, even the TRAIN ones, but in fact, TRAIN messages will never be created for the sending, but use only on reception... Thus, to send TRAIN messages, sendTrain will be used. //use globalAddrArray defined in management_addr.h int sendOther(address addr, bool isPred, MType type, address sender){ int length; int iovcnt = 1; struct iovec iov[1]; int rank = -1; trComm * aComm; int result; Msg * msg; if (type == TRAIN) { error_at_line(EXIT_FAILURE, errno, __FILE__, __LINE__, "Wrong MType given to sendOther"); return (-1); } else { msg = malloc(sizeof(newMsg(type, sender))); *msg = newMsg(type, sender); length = msg->len; rank = addrToRank(addr); if (rank != -1) { aComm = getTComm(rank, isPred, globalAddrArray); if (aComm == NULL ) { free(msg); return (-1); } //printf("Send message = %s on comm %p\n", msgTypeToStr(type), aComm); iov[0].iov_base = msg; iov[0].iov_len = length; result = commWritev(aComm, iov, iovcnt); if (result != length) fprintf(stderr, "result!=length\n"); free(msg); return (result); } else { //should return an error if the addr is out of rank free(msg); error_at_line(EXIT_FAILURE, errno, __FILE__, __LINE__, "Sending failure in sendOther (addr = %d)", addr); return (-1); //same error as commWritev !! } } }
/* start the given remote INDI driver connection. * exit if trouble. */ void startRemoteDvr (DvrInfo *dp) { Msg *mp; char dev[1024]; char host[1024]; char buf[1024]; int indi_port, sockfd; /* extract host and port */ indi_port = INDIPORT; if (sscanf (dp->name, "%[^@]@%[^:]:%d", dev, host, &indi_port) < 2) { fprintf (stderr, "Bad remote device syntax: %s\n", dp->name); Bye(); } /* connect */ sockfd = openINDIServer (host, indi_port); /* record flag pid, io channels, init lp and snoop list */ dp->pid = REMOTEDVR; dp->rfd = sockfd; dp->wfd = sockfd; dp->lp = newLilXML(); dp->msgq = newFQ(1); dp->sprops = (Property*) malloc (1); /* seed for realloc */ dp->nsprops = 0; dp->nsent = 0; dp->active = 1; dp->ndev = 1; dp->dev = (char **) malloc(sizeof(char *)); /* N.B. storing name now is key to limiting outbound traffic to this * dev. */ dp->dev[0] = (char *) malloc(MAXINDIDEVICE * sizeof(char)); strncpy (dp->dev[0], dev, MAXINDIDEVICE-1); dp->dev[0][MAXINDIDEVICE-1] = '\0'; /* Sending getProperties with device lets remote server limit its * outbound (and our inbound) traffic on this socket to this device. */ mp = newMsg(); pushFQ (dp->msgq, mp); sprintf (buf, "<getProperties device='%s' version='%g'/>\n", dp->dev[0], INDIV); setMsgStr (mp, buf); mp->count++; if (verbose > 0) fprintf (stderr, "%s: Driver %s: socket=%d\n", indi_tstamp(NULL), dp->name, sockfd); }
TextMessageDlg::TextMessageDlg(const User& user, const textmessages_t& msgs, QWidget * parent/* = 0*/) : QDialog(parent, QT_DEFAULT_DIALOG_HINTS | Qt::WindowMinMaxButtonsHint | Qt::WindowSystemMenuHint) , m_userid(user.nUserID) , m_textchanged(false) , m_remote_typing_id(0) { init(user); textmessages_t::const_iterator ii = msgs.begin(); for(;ii!=msgs.end();ii++) newMsg(*ii, false); }
void SvgView::mouseMoveEvent(QMouseEvent *event) { if (mPlan == NULL) return; // Search the group at the current mouse Y QPoint pos = event->pos(); int mouseGroup = pos.y() / mGroupHeight; // If mouse is outside the plan, nothing to do if ( (mouseGroup == 0) || (mouseGroup > mPlan->countGroups()) ) { if (QToolTip::isVisible()) QToolTip::hideText(); return; } vlePlanGroup *planGroup = mPlan->getGroup(mouseGroup - 1); QDate dateStart = mPlan->dateStart(); // Get mouse X position int currentX = horizontalScrollBar()->value() + pos.x(); int mouseTimePos = (currentX - 120); // Search if the mouse is over one acivity of the current group for (int j = 0; j < planGroup->count(); j++) { vlePlanActivity *planActivity = planGroup->getActivity(j); // Convert activity date to "days from the begining of the plan" int dataOffsetStart = dateStart.daysTo(planActivity->dateStart()); int dateOffsetEnd = dateStart.daysTo(planActivity->dateEnd()); // Convert this number of days to pixels/coordinates int startPos = (dataOffsetStart * mPixelPerDay * mZoomLevel); int endPos = (dateOffsetEnd * mPixelPerDay * mZoomLevel); // Compare activity start/end to the current mouse position if ( (mouseTimePos >= startPos) && (mouseTimePos <= endPos) ) { if ( ( planActivity->attributeCount() ) && ( ! QToolTip::isVisible()) ) { QString newMsg(planActivity->getName()); for (int k = 0; k < planActivity->attributeCount(); k++) newMsg += "\n" + planActivity->getAttribute(k); QRect tipPos(pos.x() - 10, pos.y() - 10, 20, 20); QToolTip::showText(event->globalPos(), newMsg, this, tipPos); } } } }
void RpcConnection::connIdMsgHandler(QtMsgType /*type*/, const char* msg) { if (connId.hasLocalData()) { QString newMsg(*connId.localData()); newMsg.append(msg); newMsg.replace(QChar('\n'), QString("\n").append(*connId.localData())); fprintf(stderr, "%s\n", qPrintable(newMsg)); fflush(stderr); return; } fprintf(stderr, "%s\n", msg); fflush(stderr); }
void ChatManager::SendGroup(Client * client, psChatMessage& msg) { csRef<PlayerGroup> group = client->GetActor()->GetGroup(); if (group) { psChatMessage newMsg(0, client->GetActor()->GetEID(), client->GetName(), 0, msg.sText, msg.iChatType, msg.translate); group->Broadcast(newMsg.msg); // Save chat message to grouped clients' history (PS#2789) for (size_t i=0; i<group->GetMemberCount(); i++) { group->GetMember(i)->LogChatMessage(client->GetActor()->GetFirstName(), newMsg); } } else { psserver->SendSystemInfo(client->GetClientNum(), "You are not part of any group."); } }
void ChatManager::SendAlliance(const csString & sender, EID senderEID, psGuildAlliance * alliance, psChatMessage& msg) { ClientIterator iter(*psserver->GetConnections()); psGuildMember * member; while(iter.HasNext()) { Client *client = iter.Next(); if (!client->IsReady()) continue; if (client->GetAllianceID() != alliance->GetID()) continue; member = client->GetCharacterData()->GetGuildMembership(); if ( (!member) || (!member->HasRights(RIGHTS_VIEW_CHAT_ALLIANCE)) ) continue; // Send the chat message psChatMessage newMsg(client->GetClientNum(), senderEID, sender, 0, msg.sText, msg.iChatType, msg.translate); newMsg.SendMessage(); // The message is saved to the chat history of all the clients in the same alliance (PS#2789) client->GetActor()->LogChatMessage(sender.GetData(), msg); } }
void TextMessageDlg::slotSendMsg(const QString& txt_msg) { if(txt_msg.isEmpty()) return; TextMessage msg; ZERO_STRUCT(msg); msg.nFromUserID = TT_GetMyUserID(ttInst); msg.nChannelID = 0; msg.nMsgType = MSGTYPE_USER; msg.nToUserID = m_userid; COPY_TTSTR(msg.szMessage, txt_msg); if(TT_DoTextMessage(ttInst, &msg)>0) { ui.newmsgTextEdit->setPlainText(""); newMsg(msg, true); emit(newMyselfTextMessage(msg)); m_textchanged = false; } }
void ChatManager::SendShout(Client *c, psChatMessage& msg) { psChatMessage newMsg(c->GetClientNum(), c->GetActor()->GetEID(), c->GetName(), 0, msg.sText, msg.iChatType, msg.translate); if (c->GetActor()->GetCharacterData()->GetTotalOnlineTime() > 3600 || c->GetActor()->GetSecurityLevel() >= GM_LEVEL_0) { csArray<PublishDestination>& clients = c->GetActor()->GetMulticastClients(); newMsg.Multicast(clients, 0, PROX_LIST_ANY_RANGE ); // The message is saved to the chat history of all the clients around for (size_t i = 0; i < clients.GetSize(); i++) { Client *target = psserver->GetConnections()->Find(clients[i].client); if (target && target->IsReady()) target->GetActor()->LogChatMessage(c->GetActor()->GetFirstName(), newMsg); } } else { psserver->SendSystemError(c->GetClientNum(), "You are not allowed to shout or auction until you have been in-game for at least 1 hour."); psserver->SendSystemInfo(c->GetClientNum(), "Please use the Help tab or /help if you need help."); } }
void CTe_manSuite::SendNgMsg(const TLbsNetInternalMsgBase& aMsg) { TInt err; if (aMsg.Type() == TLbsNetInternalMsgBase::ESessionComplete) { // Replace the session Id with the on from the most recent SelfLocationRequest const TLbsNetSessionCompleteAgpsMsg& reqMsg = reinterpret_cast<const TLbsNetSessionCompleteAgpsMsg&>(aMsg); TInt xxx = reqMsg.Reason(); TLbsNetSessionCompleteAgpsMsg newMsg(iSessionId, reqMsg.Reason()); err = ngDataBuffer.SendNgMsg(newMsg); } else { err = ngDataBuffer.SendNgMsg(aMsg); } if (err != KErrNone) { iCurrentStep->SetTestStepResult(EFail); iCurrentStep->ERR_PRINTF2(_L(" <font color=FF0000><b>Sending NG message failed. Error: %d.</b></font>"), err); } }
MainWidget::MainWidget( QWidget *parent , Qt::WindowFlags flags ) : QWidget( parent, flags ) , mpDatabase( new Database() ) , mpWebServer( new WebServer( this ) ) , mpMessageBuffer( new QListWidget( this ) ) , mpSatellite( Satellite::get() ) , mDelayList() , mMsg("-") , mTrackInfo() { QBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setContentsMargins( 3, 3, 3, 3 ); mainLayout->addWidget( mpMessageBuffer ); setLayout( mainLayout ); connect( mpWebServer, SIGNAL(request(QTcpSocket*,QHttpRequestHeader)), this, SLOT(request(QTcpSocket*,QHttpRequestHeader)) ); connect( this, SIGNAL(response(QTcpSocket*,QHttpResponseHeader,QByteArray)), mpWebServer, SLOT(response(QTcpSocket*,QHttpResponseHeader,QByteArray)) ); mpMessageBuffer->setAlternatingRowColors( true ); mpWebServer->start( 22222, QString(":/web/") ); mTrackInfo.mArtist = "-"; mTrackInfo.mTitle = "-"; mTrackInfo.mAlbum = "-"; if( mpSatellite ) { connect( mpSatellite, SIGNAL(received(QByteArray) ), this, SLOT(newMsg(QByteArray)) ); GenericSatelliteHandler *genericSatMsgHandler = new GenericSatelliteHandler( mpSatellite, GenericSatelliteHandler::WithoutPing, this ); genericSatMsgHandler->setConnectMsg( "P0R" ); } }
void ArpConfigureFile::MessageReceived(BMessage* message) { if( !message ) return; ArpD(cdb << ADH << "ArpConfigureFile received message: " << *message << endl); if( message->what == B_NODE_MONITOR && mWatcher.IsValid() ) { int32 opcode; if( message->FindInt32("opcode", &opcode) == B_OK && opcode == B_ENTRY_MOVED ) { entry_ref ref; const char* name; if( message->FindInt32("device", &ref.device) == B_OK && message->FindInt64("to directory", &ref.directory) == B_OK && message->FindString("name", &name) == B_OK ) { ref.set_name(name); mFile = ref; } } if( mWatchMessage ) { BMessage newMsg(*mWatchMessage); ArpUpdateMessage(newMsg, *message); mWatcher.SendMessage(&newMsg); } else { mWatcher.SendMessage(message); } return; } inherited::MessageReceived(message); }
void PApp::MessageReceived(BMessage *msg) { try { switch (msg->what) { case msg_SaveAll: { const doclist& lst = CDoc::DocList(); doclist::const_iterator di; for (di = lst.begin(); di != lst.end(); di++) { BWindow *w = dynamic_cast<PDoc*>(*di); if (w) w->PostMessage(msg_Save); } break; } case msg_CloseAll: { const doclist& lst = CDoc::DocList(); doclist::const_reverse_iterator di; for (di = lst.rbegin(); di != lst.rend(); di++) { PDoc *doc = dynamic_cast<PDoc*>(*di); if (doc && ! doc->IsWorksheet() && doc->Lock()) { if (doc->QuitRequested()) doc->Quit(); else { doc->Unlock(); break; } } } break; } case B_NODE_MONITOR: { CDoc::HandleFolderNodeMonitorMsg(msg); break; } case msg_OpenSelected: DialogCreator<COpenSelection>::CreateDialog(NULL); break; case msg_OpenInclude: { const char *i; FailOSErr(msg->FindString("include", &i)); const char *src = NULL; msg->FindString("from-source", &src); FindAndOpen(i, src); break; } case msg_FindCmd: { int c = 1 << current_workspace(); if (gPrefs->GetPrefInt(prf_I_SmartWorkspaces, 1)) FindDialog()->SetWorkspaces(c); FindDialog()->SetCaller(PDoc::TopWindow()); FindDialog()->Show(); FindDialog()->Activate(true); break; } case B_REFS_RECEIVED: case 'OpFi': RefsReceived(msg); break; case msg_About: { AboutWindow *abwin = new AboutWindow(); abwin->Show(); break; } case msg_IdeBringToFront: PDoc::IDEBringToFront(); break; case msg_IdeProjectToGroup: PDoc::IDEProject2Group(); break; case msg_FindDifferences: { BRect r(100,100,500,250); new CDiffWindow(r, "Differences"); break; } case msg_Open: { if (fOpenPanel->IsShowing()) { fOpenPanel->Window()->SetWorkspaces(1 << current_workspace()); fOpenPanel->Window()->Activate(); } else { BEntry entry; gCWD.GetEntry(&entry); BAutolock lock(fOpenPanel->Window()); entry_ref ref; entry.GetRef(&ref); fOpenPanel->SetPanelDirectory(&ref); fOpenPanel->Window()->SetWorkspaces(1 << current_workspace()); if (gPrefs->GetPrefInt(prf_I_ZoomOpenPanel, 0)) { BRect r = BScreen().Frame(); fOpenPanel->Window()->MoveTo(r.left + 80, r.top + 40); fOpenPanel->Window()->ResizeTo(480, r.Height() - 50); } fOpenPanel->Show(); } break; } case msg_CommandLineOpen: { entry_ref doc; FailOSErr (msg->FindRef("refs", &doc)); CDocWindow *w; BEntry e; if (e.SetTo(&doc) == B_OK && e.Exists()) w = dynamic_cast<CDocWindow*>(OpenWindow(doc)); else { w = NewWindow(NULL); w->SetEntryRef(&doc); } long lineNr; if (w && msg->FindInt32("line", &lineNr) == B_OK) { BMessage m(msg_SelectLines); FailOSErr(m.AddInt32("from", lineNr)); FailOSErr(m.AddInt32("to", lineNr - 1)); w->PostMessage(&m, w->PreferredHandler()); } if (w) { BMessage reply; reply.AddInt32("thread", w->Thread()); msg->SendReply(&reply); } break; } case B_SILENT_RELAUNCH: case msg_New: if (be_roster->IsRunning("application/x-vnd.dw-Paladin")) { BMessage newMsg(PALADIN_SHOW_ADD_NEW_PANEL); BMessenger msgr("application/x-vnd.dw-Paladin"); msgr.SendMessage(&newMsg); } else NewWindow(); break; case msg_Select: { PDoc *doc; if ((doc = PDoc::TopWindow()) != NULL) { BMessage copy(*msg); doc->PostMessage(©); } break; } case msg_DocClosed: if (CDoc::CountDocs() == 0) Quit(); break; case msg_Tile: PDoc::Tile(); break; case msg_Stack: PDoc::Stack(); break; case msg_Zoom: if (PDoc::TopWindow()) PDoc::TopWindow()->Zoom(); break; case msg_Worksheet: OpenWorksheet(); break; case msg_NewGroup: new PGroupWindow; break; case 1: puts(rcsid); break; case msg_Quit: PostMessage(B_QUIT_REQUESTED); break; case msg_Preferences: { long l; if (fPrefOpener) wait_for_thread(fPrefOpener, &l); fPrefOpener = (thread_id)NULL; if (fPrefsDialog) { BAutolock lock(fPrefsDialog); if (!lock.IsLocked()) { THROW(("Preferences panel failed to lock")); break; } int c = 1 << current_workspace(); if (gPrefs->GetPrefInt(prf_I_SmartWorkspaces, 1)) fPrefsDialog->SetWorkspaces(c); if (fPrefsDialog->IsHidden()) { fPrefsDialog->Show(); } fPrefsDialog->Activate(true); } else THROW(("Preferences panel failed to open")); break; } default: BApplication::MessageReceived(msg); } } catch (HErr& e) { e.DoError(); } } /* PApp::MessageReceived */
void ChatManager::HandleChatMessage(MsgEntry *me, Client *client) { psChatMessage msg(me); // Dont if (!msg.valid) { Debug2(LOG_NET,me->clientnum,"Received unparsable psChatMessage from client %u.\n",me->clientnum); return; } const char *pType = msg.GetTypeText(); if (msg.iChatType != CHAT_TELL && msg.iChatType != CHAT_AWAY) { Debug4(LOG_CHAT, client->GetClientNum(), "%s %s: %s\n", client->GetName(), pType, msg.sText.GetData()); } else { Debug5(LOG_CHAT,client->GetClientNum(), "%s %s %s: %s\n", client->GetName(), pType, msg.sPerson.GetData(),msg.sText.GetData()); } bool saveFlood = true; if (!client->IsMute()) { // Send Chat to other players switch (msg.iChatType) { case CHAT_GUILD: { SendGuild(client, msg); break; } case CHAT_ALLIANCE: { SendAlliance(client, msg); break; } case CHAT_GROUP: { SendGroup(client, msg); break; } case CHAT_AUCTION: case CHAT_SHOUT: { SendShout(client, msg); break; } case CHAT_CHANNEL: { csArray<uint32_t> subscribed = channelSubscriptions.GetAll(client->GetClientNum()); bool found = false; for(size_t i = 0; i < subscribed.GetSize(); i++) { if(subscribed[i] == msg.channelID) found = true; } if(!found) { psserver->SendSystemError(client->GetClientNum(), "You have not yet joined this channel."); break; } // channel 1 is public if(msg.channelID == 1) CPrintf (CON_WARNING, "Gossip %s: %s\n", client->GetName(), msg.sText.GetData()); psChatMessage newMsg(client->GetClientNum(), client->GetActor()->GetEID(), client->GetName(), 0, msg.sText, msg.iChatType, msg.translate, msg.channelID); csArray<uint32_t> subscribers = channelSubscribers.GetAll(msg.channelID); csArray<PublishDestination> destArray; for (size_t i = 0; i < subscribers.GetSize(); i++) { destArray.Push(PublishDestination(subscribers[i], NULL, 0, 0)); Client *target = psserver->GetConnections()->Find(subscribers[i]); if (target && target->IsReady()) target->GetActor()->LogChatMessage(client->GetActor()->GetFirstName(), newMsg); } newMsg.Multicast(destArray, 0, PROX_LIST_ANY_RANGE ); break; } case CHAT_PET_ACTION: { gemNPC *pet = NULL; // Check if a specific pet's name was specified, in one of these forms: // - /mypet Petname ... // - /mypet Petname's ... size_t numPets = client->GetNumPets(); for (size_t i = 0; i < numPets; i++) { if ((pet = dynamic_cast <gemNPC*>(client->GetPet(i))) && msg.sText.StartsWith(pet->GetCharacterData()->GetCharName(), true)) { size_t n = strlen(pet->GetCharacterData()->GetCharName()); if (msg.sText.Length() >= n + 1 && msg.sText.GetAt(n) == ' ') { msg.sText.DeleteAt(0, n); msg.sText.LTrim(); break; } else if (msg.sText.Length() >= n + 3 && msg.sText.GetAt(n) == '\'' && msg.sText.GetAt(n + 1) == 's' && msg.sText.GetAt(n + 2) == ' ') { msg.sText.DeleteAt(0, n); break; } } else pet = NULL; } // If no particular pet was specified, assume the default familiar... if (!pet) pet = dynamic_cast <gemNPC*>(client->GetFamiliar()); // Send the message or an appropriate error... if (!pet) psserver->SendSystemInfo(me->clientnum, "You have no familiar to command."); else SendSay(client->GetClientNum(), pet, msg, pet->GetCharacterData()->GetCharFullName()); break; } case CHAT_SAY: { // Send to all if there's no NPC response or the response is public SendSay(client->GetClientNum(), client->GetActor(), msg, client->GetName()); break; } case CHAT_NPC: { // Only the speaker sees his successful chatting with an npc. // This helps quests stay secret. //psChatMessage newMsg(client->GetClientNum(), client->GetName(), 0, // msg.sText, msg.iChatType, msg.translate); //newMsg.SendMessage(); saveFlood = false; gemObject *target = client->GetTargetObject(); gemNPC *targetnpc = dynamic_cast<gemNPC*>(target); NpcResponse *resp = CheckNPCResponse(msg,client,targetnpc); if (resp) { csTicks delay = resp->ExecuteScript(client->GetActor(), targetnpc); if (delay != (csTicks)-1 && resp->menu ) resp->menu->ShowMenu(client, delay, targetnpc); } break; } case CHAT_AWAY: { saveFlood = false; //do not check Away messages for flooding msg.iChatType = CHAT_TELL; //do regard it as tell message from now on //intentionally no break, so it falls through to CHAT_TELL } case CHAT_TELL: { if ( msg.sPerson.Length() == 0 ) { psserver->SendSystemError(client->GetClientNum(), "You must specify name of player."); break; } Client *target = FindPlayerClient(msg.sPerson); if (target && !target->IsSuperClient()) { if (!target->IsReady()) psserver->SendSystemError(client->GetClientNum(), "%s is not ready yet.", msg.sPerson.GetDataSafe()); else SendTell(msg, client->GetName(), client, target); } else psserver->SendSystemError(client->GetClientNum(), "%s is not found online.", msg.sPerson.GetDataSafe()); break; } case CHAT_REPORT: { // First thing to extract the name of the player to log csString targetName; int index = (int)msg.sText.FindFirst(' ', 0); targetName = (index == -1) ? msg.sText : msg.sText.Slice(0, index); targetName = NormalizeCharacterName(targetName); if ( targetName.Length() == 0 ) { psserver->SendSystemError(client->GetClientNum(), "You must specify name of player."); break; } Client * target = psserver->GetConnections()->Find(targetName); if ( !target ) { psserver->SendSystemError(client->GetClientNum(), "%s is not found online.", targetName.GetData()); break; } if (target->IsSuperClient()) { psserver->SendSystemError(client->GetClientNum(), "Can't report NPCs."); break; } // Add an active report to the target. if (target->GetActor()->AddChatReport(client->GetActor())) { // Add report removal event. psserver->GetEventManager()->Push(new psEndChatLoggingEvent(target->GetClientNum(), 300000)); psserver->SendSystemInfo(client->GetClientNum(), "Last 5 minutes of %s's chat were logged. Logging will continue for another 5 minutes.", targetName.GetData()); } else psserver->SendSystemError(client->GetClientNum(), "Could not start logging %s, due to a server error.", targetName.GetData()); break; } case CHAT_ADVISOR: case CHAT_ADVICE: break; default: { Error2("Unknown Chat Type: %d\n",msg.iChatType); break; } } } else { //User is muted but tries to chat anyway. Remind the user that he/she/it is muted psserver->SendSystemInfo(client->GetClientNum(),"You can't send messages because you are muted."); } if (saveFlood) client->FloodControl(msg.iChatType, msg.sText, msg.sPerson); }
/** The main function for the background thread * * Loops until the forground thread requests it to stop. Reads data from the *network, * parses it and stores the resulting events (and other metadata) in a temporary * workspace. */ void ISISLiveEventDataListener::run() { try { if (!m_isConnected) // sanity check { throw std::runtime_error(std::string("No connection to the DAE.")); } TCPStreamEventDataNeutron events; while (!m_stopThread) { // get the header with the type of the packet Receive(events.head, "Events header", "Corrupt stream - you should reconnect."); if (!(events.head.type == TCPStreamEventHeader::Neutron)) { // don't know what to do with it - stop throw std::runtime_error("Unknown packet type."); } CollectJunk(events.head); // get the header with the sream size Receive(events.head_n, "Neutrons header", "Corrupt stream - you should reconnect."); CollectJunk(events.head_n); // absolute pulse (frame) time Mantid::Kernel::DateAndTime pulseTime = m_startTime + static_cast<double>(events.head_n.frame_time_zero); // Save the pulse charge in the logs double protons = static_cast<double>(events.head_n.protons); m_eventBuffer[0] ->mutableRun() .getTimeSeriesProperty<double>(PROTON_CHARGE_PROPERTY) ->addValue(pulseTime, protons); events.data.resize(events.head_n.nevents); uint32_t nread = 0; // receive the events while (nread < events.head_n.nevents) { int ntoread = m_socket.available() / static_cast<int>(sizeof(TCPStreamEventNeutron)); if (ntoread > static_cast<int>(events.head_n.nevents - nread)) { ntoread = static_cast<int>(events.head_n.nevents - nread); } if (ntoread > 0) { m_socket.receiveBytes( &(events.data[nread]), ntoread * static_cast<int>(sizeof(TCPStreamEventNeutron))); nread += ntoread; } else { Poco::Thread::sleep(RECV_WAIT); } } if (!events.isValid()) { throw std::runtime_error("corrupt stream - you should reconnect"); } // store the events saveEvents(events.data, pulseTime, events.head_n.period); } } catch (std::runtime_error & e) { // exception handler for generic runtime exceptions g_log.error() << "Caught a runtime exception." << std::endl << "Exception message: " << e.what() << std::endl; m_isConnected = false; m_backgroundException = boost::make_shared<std::runtime_error>(e); } catch (std::invalid_argument & e) { // TimeSeriesProperty (and possibly some other things) can // can throw these errors g_log.error() << "Caught an invalid argument exception." << std::endl << "Exception message: " << e.what() << std::endl; m_isConnected = false; std::string newMsg( "Invalid argument exception thrown from the background thread: "); newMsg += e.what(); m_backgroundException = boost::make_shared<std::runtime_error>(newMsg); } catch (...) { // Default exception handler g_log.error() << "Uncaught exception in ISISLiveEventDataListener network " "read thread." << std::endl; m_isConnected = false; m_backgroundException = boost::shared_ptr<std::runtime_error>( new std::runtime_error("Unknown error in backgound thread")); } }
void RAIDProcess::executeProcess() { RAIDProcessState *myState = (RAIDProcessState*) getState(); RAIDRequest* recvEvent; while (true == haveMoreEvents()) { recvEvent = (RAIDRequest*) getEvent(); // int senderSimObjID = getObjectHandle(outputName)->getObjectID()->getSimulationObjectID(); if (recvEvent != NULL) { /*#if WHATISTHEPURPOSEOFTHIS if ( myState->getStopProcessing() == true) { return; } if (recvEvent->getTokenNumber() != myState->getNumRequests()) { myState->setStopProcessing(true); return; } #endif*/ /* This is not correct anymore. Because the number of disk requests outstanding is not critical, I am not fixing it at this time. // keep memory from being munged on errors and first event if ( (senderSimObjID - firstDiskId) >= 0 && (senderSimObjID - firstDiskId) < (unsigned) maxDisks) { myState->diskRequests[senderSimObjID-firstDiskId]++; } else if (senderSimObjID != getObjectID()->getSimulationObjectID()) { //cldebug::debugout << objectName << " ignoring event from " << senderSimObjID // << " in diskRequests count\n"; }*/ // cout << "State Size before::" << myState->get_size() // << " Parity Size before :: " << myState->getParitySize() // << endl; // If this is a write then parity information will be expected. if ((recvEvent->getRead() == false) && myState->getParitySize() == -1) { // our first write message comes back home, lets see how many // paritys were generated. //cout << "Waiting for First parity of Write" << endl; myState->setParitySize(recvEvent->getSizeParity()); // cout << "Parity Size = " << myState->getParitySize() << endl; } if (recvEvent->getParityMsg() == true) { // Its a parity msg so decrement the parity myState->setParitySize(myState->getParitySize() - 1); } else { myState->set_size(myState->get_size() - 1); } //Print Current State // cout << "State Size After::" << myState->get_size() // << " Parity Size After:: " << myState->getParitySize() // << endl; if (recvEvent->getRead() == true) { // see if the operation is complete if ((myState->get_size() == 0) && (myState->getParitySize() == -1)) { myState->setDiskOperationPending(false); myState->setNumReads(myState->getNumReads() + 1); myState->set_size(0); for (int i = 0; i < maxDisks; i++) { myState->diskRequests[i] = 0; } // cout // << "Read Completed------------------------------------------------------------------------------------" // << endl; if (myState->getNumRequests() < maxRequests) { newMsg(); } } } else { // event is a write // see if the operation is complete if ((myState->get_size() == 0)) { if ((myState->getParitySize() == 0)) { myState->setDiskOperationPending(false); myState->setNumWrites(myState->getNumWrites() + 1); myState->set_size(0); myState->setParitySize(-1); // cout // << "Write Completed------------------------------------------------------------------------------------" // << endl; for (int i = 0; i < maxDisks; i++) { myState->diskRequests[i] = 0; } if (myState->getNumRequests() < maxRequests) { newMsg(); } } else { //cout << "The Partity Condition is not met" << endl; } } // size and parity size is not equal to zero } // else (write) } } // while (haveMoreEvents() == true) }
/* start the given local INDI driver process. * exit if trouble. */ void startLocalDvr (DvrInfo *dp) { Msg *mp; char buf[32]; int rp[2], wp[2], ep[2]; int pid; #ifdef OSX_EMBEDED_MODE fprintf(stderr, "STARTING \"%s\"\n", dp->name); fflush(stderr); #endif /* build three pipes: r, w and error*/ if (pipe (rp) < 0) { fprintf (stderr, "%s: read pipe: %s\n", indi_tstamp(NULL), strerror(errno)); Bye(); } if (pipe (wp) < 0) { fprintf (stderr, "%s: write pipe: %s\n", indi_tstamp(NULL), strerror(errno)); Bye(); } if (pipe (ep) < 0) { fprintf (stderr, "%s: stderr pipe: %s\n", indi_tstamp(NULL), strerror(errno)); Bye(); } /* fork&exec new process */ pid = fork(); if (pid < 0) { fprintf (stderr, "%s: fork: %s\n", indi_tstamp(NULL), strerror(errno)); Bye(); } if (pid == 0) { /* child: exec name */ int fd; /* rig up pipes */ dup2 (wp[0], 0); /* driver stdin reads from wp[0] */ dup2 (rp[1], 1); /* driver stdout writes to rp[1] */ dup2 (ep[1], 2); /* driver stderr writes to e[]1] */ for (fd = 3; fd < 100; fd++) (void) close (fd); if (*dp->envDev) setenv("INDIDEV", dp->envDev, 1); /* Only reset environment variable in case of FIFO */ else if (fifo.fd > 0) unsetenv("INDIDEV"); if (*dp->envConfig) setenv("INDICONFIG", dp->envConfig, 1); else if (fifo.fd > 0) unsetenv("INDICONFIG"); if (*dp->envSkel) setenv("INDISKEL", dp->envSkel, 1); else if (fifo.fd > 0) unsetenv("INDISKEL"); char executable[MAXSBUF]; if (*dp->envPrefix) { setenv("INDIPREFIX", dp->envPrefix, 1); #ifdef OSX_EMBEDED_MODE snprintf(executable, MAXSBUF, "%s/Contents/MacOS/%s", dp->envPrefix, dp->name); #else snprintf(executable, MAXSBUF, "%s/bin/%s", dp->envPrefix, dp->name); #endif fprintf(stderr, "%s\n", executable); execlp (executable, dp->name, NULL); } else { if (fifo.fd > 0) unsetenv("INDIPREFIX"); execlp (dp->name, dp->name, NULL); } #ifdef OSX_EMBEDED_MODE fprintf(stderr, "FAILED \"%s\"\n", dp->name); fflush(stderr); #endif fprintf (stderr, "%s: Driver %s: execlp: %s\n", indi_tstamp(NULL), dp->name, strerror(errno)); _exit (1); /* parent will notice EOF shortly */ } /* don't need child's side of pipes */ close (wp[0]); close (rp[1]); close (ep[1]); /* record pid, io channels, init lp and snoop list */ dp->pid = pid; dp->rfd = rp[0]; dp->wfd = wp[1]; dp->efd = ep[0]; dp->lp = newLilXML(); dp->msgq = newFQ(1); dp->sprops = (Property*) malloc (1); /* seed for realloc */ dp->nsprops = 0; dp->nsent = 0; dp->active = 1; dp->ndev = 0; dp->dev = (char **) malloc(sizeof(char *)); /* first message primes driver to report its properties -- dev known * if restarting */ mp = newMsg(); pushFQ (dp->msgq, mp); sprintf (buf, "<getProperties version='%g'/>\n", INDIV); setMsgStr (mp, buf); mp->count++; if (verbose > 0) fprintf (stderr, "%s: Driver %s: pid=%d rfd=%d wfd=%d efd=%d\n", indi_tstamp(NULL), dp->name, dp->pid, dp->rfd, dp->wfd, dp->efd); }
//********************************************************************************************************************** void SimpleTerminal::modifyDspText(DspType type, const QString &text) { // Format text according to type of message static DspType last_type = DspType::NONE; // Need to end the last message? if (last_type != type && _is_msg_open) emit endMsg(); switch(type) { case DspType::READ_MESSAGE: { static QString prev_msg(""); // Parse message and look for EOM string(s) - there could be 0 - n in this message // Emit approriate details to system - end of message? Start of message? Append message? QString msg(text.toHtmlEscaped()); // Find all occurences of EOM int start_pos = 0; int eom_pos = 0; do { QString shared_msg(prev_msg + msg); eom_pos = shared_msg.indexOf(_eom, start_pos); if (eom_pos >= 0) { // Found EOM! if (!_is_msg_open) emit startMsg(); if (eom_pos < prev_msg.length()) // Found EOM start before start of actual message; need to correct start position // to be first character after previous message start_pos += prev_msg.length(); int len = (eom_pos + _eom.length()) - start_pos; emit appendMsg(shared_msg.mid(start_pos, len)); emit endMsg(); start_pos = eom_pos + _eom.length(); } else if (start_pos < shared_msg.length()) { // No EOMs left; send rest of message if (!_is_msg_open) emit startMsg(); emit appendMsg(shared_msg.mid(start_pos)); } } while(eom_pos >= 0); // Keep end of msg for next time if (_eom.length() > 0) { int num_prev_msg_keep = _eom.length() - msg.length(); if (num_prev_msg_keep > 0) prev_msg = prev_msg.right(num_prev_msg_keep) + msg; else prev_msg = msg.right(_eom.length() - 1); } else prev_msg = ""; break; } case DspType::WRITE_MESSAGE: { QString msg = "<span><b>" + text.toHtmlEscaped() + "</b></span>"; emit newMsg(msg); break; } case DspType::COMMAND: { QString msg = "<span style = \"color: blue;\"><b>$ " + text.toHtmlEscaped() + "</b></span>"; emit newMsg(msg); break; } case DspType::COMMAND_RSP: { QString msg = "<span style = \"color: green;\">" + text + "</span>"; emit newMsg(msg); break; } case DspType::ERROR: { QString msg = "<span style = \"color: red;\">ERROR: " + text + "</span>"; emit newMsg(msg); break; } default: break; } last_type = type; }
/** Constructor */ CreateGxsForumMsg::CreateGxsForumMsg(const RsGxsGroupId &fId, const RsGxsMessageId &pId) : QDialog(NULL, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint), mForumId(fId), mParentId(pId) { /* Invoke the Qt Designer generated object setup routine */ ui.setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); /* Setup Queue */ mForumQueue = new TokenQueue(rsGxsForums->getTokenService(), this); mCirclesQueue = new TokenQueue(rsGxsCircles->getTokenService(), this); /* Setup UI helper */ mStateHelper = new UIStateHelper(this); mStateHelper->addWidget(CREATEGXSFORUMMSG_FORUMINFO, ui.buttonBox->button(QDialogButtonBox::Ok)); mStateHelper->addWidget(CREATEGXSFORUMMSG_FORUMINFO, ui.innerFrame); mStateHelper->addLoadPlaceholder(CREATEGXSFORUMMSG_FORUMINFO, ui.forumName); mStateHelper->addLoadPlaceholder(CREATEGXSFORUMMSG_FORUMINFO, ui.forumSubject); mStateHelper->addClear(CREATEGXSFORUMMSG_FORUMINFO, ui.forumName); mStateHelper->addWidget(CREATEGXSFORUMMSG_PARENTMSG, ui.buttonBox->button(QDialogButtonBox::Ok)); mStateHelper->addWidget(CREATEGXSFORUMMSG_PARENTMSG, ui.innerFrame); mStateHelper->addLoadPlaceholder(CREATEGXSFORUMMSG_PARENTMSG, ui.forumName); mStateHelper->addLoadPlaceholder(CREATEGXSFORUMMSG_PARENTMSG, ui.forumSubject); mStateHelper->addClear(CREATEGXSFORUMMSG_PARENTMSG, ui.forumName); QString text = pId.isNull() ? tr("Start New Thread") : tr("Post Forum Message"); setWindowTitle(text); ui.headerFrame->setHeaderImage(QPixmap(":/images/konversation64.png")); ui.headerFrame->setHeaderText(text); ui.generateSpinBox->setEnabled(false); Settings->loadWidgetInformation(this); connect(ui.hashBox, SIGNAL(fileHashingFinished(QList<HashedFile>)), this, SLOT(fileHashingFinished(QList<HashedFile>))); /* Rename Ok button */ ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Send")); // connect up the buttons. connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(createMsg())); connect(ui.buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(ui.emoticonButton, SIGNAL(clicked()), this, SLOT(smileyWidgetForums())); connect(ui.attachFileButton, SIGNAL(clicked()), this, SLOT(addFile())); connect(ui.generateCheckBox, SIGNAL(toggled(bool)), ui.generateSpinBox, SLOT(setEnabled(bool))); setAcceptDrops(true); ui.hashBox->setDropWidget(this); ui.hashBox->setAutoHide(false); mParentMsgLoaded = false; mForumMetaLoaded = false; mForumCircleLoaded = false; newMsg(); #ifndef ENABLE_GENERATE ui.generateCheckBox->hide(); ui.generateSpinBox->hide(); #endif }
BeAccessibleWindow::BeAccessibleWindow(BRect frame, BList* recentFiles) : BWindow(frame, "BeAccessible", B_TITLED_WINDOW, 0) { //Create MenuBar BRect rect = Bounds(); rect.bottom = MENU_BAR_HEIGHT; fMenuBar = new BMenuBar(rect, "MenuBar"); AddChild(fMenuBar); //Create Menus fFileMenu = new BMenu("File"); fMenuBar->AddItem(fFileMenu); fOpenRecentMenu = new BMenu("Open Recent"); fToolsMenu = new BMenu("Tools"); fMenuBar->AddItem(fToolsMenu); //Create MenuItems fFileMenu->AddItem(new BMenuItem("New", new BMessage(MENU_FILE_NEW_MSG), 'N')); fFileMenu->AddItem(new BMenuItem("Open", new BMessage(MENU_FILE_OPEN_MSG), 'O')); fFileMenu->AddSeparatorItem(); BMenu* externalDataMenu = new BMenu("Get External Data"); fFileMenu->AddItem(externalDataMenu); fImportItem = new BMenuItem("Import Text File", new BMessage(IMPORT_FILE_REQUESTED_MSG)); externalDataMenu->AddItem(fImportItem); fFileMenu->AddSeparatorItem(); fCloseItem = new BMenuItem("Close", new BMessage(MENU_FILE_CLOSE_MSG), 'W'); fFileMenu->AddItem(fCloseItem); fFileMenu->AddSeparatorItem(); BMenuItem* about = new BMenuItem("About BeAccessible", new BMessage(B_ABOUT_REQUESTED)); fFileMenu->AddItem(about); about->SetTarget(be_app); fFileMenu->AddSeparatorItem(); BMenuItem* quitItem = new BMenuItem("Quit", new BMessage(B_QUIT_REQUESTED), 'Q'); quitItem->SetTarget(be_app); fFileMenu->AddItem(quitItem); fCompactItem = new BMenuItem("Compact", new BMessage(COMPACT_DATABASE_MSG)); fToolsMenu->AddItem(fCompactItem); // Create MenuItems for recent files for(int i = 0; i < recentFiles->CountItems(); i++) { BString* file = (BString*)recentFiles->ItemAt(i); BPath path(file->String()); BMessage* fileMsg = new BMessage(OPEN_DATABASE_MSG); fileMsg->AddString("path", file->String()); fOpenRecentMenu->AddItem(new BMenuItem(path.Leaf(), fileMsg)); } // Add the Open Recent menu between the Open and Close menu items fFileMenu->AddItem(fOpenRecentMenu, 2); fCloseItem->SetEnabled(false); fCompactItem->SetEnabled(false); fImportItem->SetEnabled(false); //Set up View frame.OffsetTo(B_ORIGIN); fMainView = new BView(frame, "BeAccessibleView", B_FOLLOW_ALL, B_WILL_DRAW); fMainView->SetViewColor(216,216,216,0); AddChild(fMainView); Show(); //Set up File->Open and File->Save panels BMessage newMsg(NEW_FILE_REQUESTED), importMsg(IMPORT_FILE_MSG); fOpenFile = new BFilePanel(B_OPEN_PANEL, NULL, NULL, 0, false); fNewFile = new BFilePanel(B_SAVE_PANEL, NULL, NULL, 0, false, &newMsg); fImportFile = new BFilePanel(B_OPEN_PANEL, NULL, NULL, 0, false, &importMsg); //Edit the look of the ImportFile panel fImportFile->Window()->SetTitle("BeAccessible: Import"); fImportFile->SetButtonLabel(B_DEFAULT_BUTTON, "Import"); //Initalize data members fTabView = NULL; fTableTab = NULL; fQueryTab = NULL; fNewGrid = NULL; fPath = new BString; }
/* Read commands from FIFO and process them. Start/stop drivers accordingly */ void newFIFO(void) { //char line[MAXRBUF], tDriver[MAXRBUF], tConfig[MAXRBUF], tDev[MAXRBUF], tSkel[MAXRBUF], envDev[MAXRBUF], envConfig[MAXRBUF], envSkel[MAXR]; char line[MAXRBUF]; DvrInfo *dp = NULL; int startCmd=0, i=0; while (i < MAXRBUF) { if (read(fifo.fd, line+i, 1) <= 0) { // Reset FIFO now, otherwise select will always return with no data from FIFO. indiFIFO(); return; } if (line[i] == '\n') { line[i] = '\0'; i=0; } else { i++; continue; } if (verbose) fprintf(stderr, "FIFO: %s\n", line); char cmd[MAXSBUF], arg[4][1], var[4][MAXSBUF], tDriver[MAXSBUF], tName[MAXSBUF], envDev[MAXSBUF], envConfig[MAXSBUF], envSkel[MAXSBUF], envPrefix[MAXSBUF]; memset(&tDriver[0], 0, sizeof(MAXSBUF)); memset(&tName[0], 0, sizeof(MAXSBUF)); memset(&envDev[0], 0, sizeof(MAXSBUF)); memset(&envConfig[0], 0, sizeof(MAXSBUF)); memset(&envSkel[0], 0, sizeof(MAXSBUF)); memset(&envPrefix[0], 0, sizeof(MAXSBUF)); int n = sscanf(line, "%s %s -%1c \"%512[^\"]\" -%1c \"%512[^\"]\" -%1c \"%512[^\"]\" -%1c \"%512[^\"]\"", cmd, tDriver, arg[0], var[0], arg[1], var[1] , arg[2], var[2], arg[3], var[3]); int n_args = (n - 2)/2; int j=0; for (j=0; j < n_args; j++) { //fprintf(stderr, "arg[%d]: %c\n", i, arg[j][0]); //fprintf(stderr, "var[%d]: %s\n", i, var[j]); if (arg[j][0] == 'n') { strncpy(tName, var[j], MAXSBUF-1); tName[MAXSBUF-1] = '\0'; if (verbose) fprintf(stderr, "With name: %s\n", envDev); } else if (arg[j][0] == 'c') { strncpy(envConfig, var[j], MAXSBUF-1); envConfig[MAXSBUF-1] = '\0'; if (verbose) fprintf(stderr, "With config: %s\n", envConfig); } else if (arg[j][0] == 's') { strncpy(envSkel, var[j], MAXSBUF-1); envSkel[MAXSBUF-1] = '\0'; if (verbose) fprintf(stderr, "With skeketon: %s\n", envSkel); } else if (arg[j][0] == 'p') { strncpy(envPrefix, var[j], MAXSBUF-1); envPrefix[MAXSBUF-1] = '\0'; if (verbose) fprintf(stderr, "With prefix: %s\n", envPrefix); } } if (!strcmp(cmd, "start")) startCmd = 1; else startCmd = 0; if (startCmd) { if (verbose) fprintf(stderr, "FIFO: Starting driver %s with name (%s)\n", tDriver, tName); dp = allocDvr(); strncpy(dp->name, tDriver, MAXINDIDEVICE); //strncpy(dp->dev, tName, MAXINDIDEVICE); strncpy(dp->envDev, tName, MAXSBUF); strncpy(dp->envConfig, envConfig, MAXSBUF); strncpy(dp->envSkel, envSkel, MAXSBUF); strncpy(dp->envPrefix, envPrefix, MAXSBUF); startDvr (dp); } else { for (dp = dvrinfo; dp < &dvrinfo[ndvrinfo]; dp++) { fprintf(stderr, "dp->name: %s - tDriver: %s\n", dp->name, tDriver); if (!strcmp(dp->name, tDriver) && dp->active==1) { fprintf(stderr, "name: %s - dp->dev[0]: %s\n", tName, dp->dev[0]); /* If device name is given, check against it before shutting down */ //if (tName[0] && strcmp(dp->dev[0], tName)) if (tName[0] && isDeviceInDriver(tName, dp) == 0) continue; if (verbose) fprintf(stderr, "FIFO: Shutting down driver: %s\n", tDriver); for (i=0; i < dp->ndev; i++) { /* Inform clients that this driver is dead */ XMLEle *root = addXMLEle (NULL, "delProperty"); addXMLAtt(root, "device", dp->dev[i]); prXMLEle(stderr, root, 0); Msg * mp = newMsg(); q2Clients(NULL, 0, dp->dev[i], NULL, mp, root); if (mp->count > 0) setMsgXMLEle (mp, root); else freeMsg (mp); delXMLEle (root); } shutdownDvr(dp, 0); break; } } } } }
void GetMsg::finished(QNetworkReply* reply) { QString replyStr = QString(reply->readAll()); #if QWX_DEBUG QFile file("getmsg.json"); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); out << replyStr; file.close(); } qDebug() << "DEBUG:" << __PRETTY_FUNCTION__; qDebug() << "DEBUG:" << replyStr; #endif QJsonDocument doc = QJsonDocument::fromJson(replyStr.toUtf8()); if (!doc.isObject()) { Q_EMIT error(); return; } QJsonObject obj = doc.object(); if (obj["AddMsgCount"].toInt() == 0) Q_EMIT noNewMsg(); Q_FOREACH (const QJsonValue & val, obj["AddMsgList"].toArray()) { QJsonObject msg = val.toObject(); QString fromUserNameStr = msg["FromUserName"].toString(); QString toUserNameStr = msg["ToUserName"].toString(); QString createTimeStr = QString::number(msg["CreateTime"].toInt()); QString content = msg["Content"] .toString(); if (content.contains("msg")) { if (content.contains("img")) { content = tr("Please view the photo on your phone"); } else if (content.contains("appmsg")) { content = tr("Please view the App message on your phone"); } else { continue; } } if (!m_map.contains(fromUserNameStr + toUserNameStr + createTimeStr)) { if (m_needSaveLog) m_saveLog(createTimeStr, fromUserNameStr, content); Q_EMIT newMsg(content, fromUserNameStr, toUserNameStr); } if ((fromUserNameStr == m_fromUserName && toUserNameStr == m_toUserName) || (fromUserNameStr == m_toUserName && toUserNameStr == m_fromUserName)) { if (!m_map.contains(fromUserNameStr + toUserNameStr + createTimeStr)) { Q_EMIT received(content, fromUserNameStr); } } if (m_map.size() > 64) { while (m_map.size() > 64 / 2) m_map.erase(m_map.begin()); } m_map.insert(fromUserNameStr + toUserNameStr + createTimeStr, msg["CreateTime"].toInt()); } m_syncKey.clear(); Q_FOREACH (const QJsonValue & val, obj["SyncKey"].toObject()["List"].toArray()) { m_syncKey.append(QString::number(val.toObject()["Key"].toInt()) + "|" + QString::number(val.toObject()["Val"].toInt())); } Q_EMIT syncKeyChanged(); }
/* read more from the given client, send to each appropriate driver when see * xml closure. also send all newXXX() to all other interested clients. * return -1 if had to shut down anything, else 0. */ int readFromClient (ClInfo *cp) { char buf[MAXRBUF]; int shutany = 0; ssize_t i, nr; /* read client */ nr = read (cp->s, buf, sizeof(buf)); if (nr <= 0) { if (nr < 0) fprintf (stderr, "%s: Client %d: read: %s\n", indi_tstamp(NULL), cp->s, strerror(errno)); else if (verbose > 0) fprintf (stderr, "%s: Client %d: read EOF\n", indi_tstamp(NULL), cp->s); shutdownClient (cp); return (-1); } /* process XML, sending when find closure */ for (i = 0; i < nr; i++) { char err[1024]; XMLEle *root = readXMLEle (cp->lp, buf[i], err); if (root) { char *roottag = tagXMLEle(root); const char *dev = findXMLAttValu (root, "device"); const char *name = findXMLAttValu (root, "name"); int isblob = !strcmp (tagXMLEle(root), "setBLOBVector"); Msg *mp; if (verbose > 2) { fprintf (stderr, "%s: Client %d: read ",indi_tstamp(NULL),cp->s); traceMsg (root); } else if (verbose > 1) { fprintf (stderr, "%s: Client %d: read <%s device='%s' name='%s'>\n", indi_tstamp(NULL), cp->s, tagXMLEle(root), findXMLAttValu (root, "device"), findXMLAttValu (root, "name")); } /* snag interested properties. * N.B. don't open to alldevs if seen specific dev already, else * remote client connections start returning too much. */ if (dev[0]) addClDevice (cp, dev, name, isblob); else if (!strcmp (roottag, "getProperties") && !cp->nprops) cp->allprops = 1; /* snag enableBLOB -- send to remote drivers too */ if (!strcmp (roottag, "enableBLOB")) // crackBLOB (pcdataXMLEle(root), &cp->blob); crackBLOBHandling (dev, name, pcdataXMLEle(root), cp); /* build a new message -- set content iff anyone cares */ mp = newMsg(); /* send message to driver(s) responsible for dev */ q2RDrivers (dev, mp, root); /* echo new* commands back to other clients */ if (!strncmp (roottag, "new", 3)) { if (q2Clients (cp, isblob, dev, name, mp, root) < 0) shutany++; } /* set message content if anyone cares else forget it */ if (mp->count > 0) setMsgXMLEle (mp, root); else freeMsg (mp); delXMLEle (root); } else if (err[0]) { char *ts = indi_tstamp(NULL); fprintf (stderr, "%s: Client %d: XML error: %s\n", ts, cp->s, err); fprintf (stderr, "%s: Client %d: XML read: %.*s\n", ts, cp->s, (int)nr, buf); shutdownClient (cp); return (-1); } } return (shutany ? -1 : 0); }
/* read more from the given driver, send to each interested client when see * xml closure. if driver dies, try restarting. * return 0 if ok else -1 if had to shut down anything. */ int readFromDriver (DvrInfo *dp) { char buf[MAXRBUF]; int shutany = 0; ssize_t i, nr; /* read driver */ nr = read (dp->rfd, buf, sizeof(buf)); if (nr <= 0) { if (nr < 0) fprintf (stderr, "%s: Driver %s: stdin %s\n", indi_tstamp(NULL), dp->name, strerror(errno)); else fprintf (stderr, "%s: Driver %s: stdin EOF\n", indi_tstamp(NULL), dp->name); shutdownDvr (dp, 1); return (-1); } /* process XML, sending when find closure */ for (i = 0; i < nr; i++) { char err[1024]; XMLEle *root = readXMLEle (dp->lp, buf[i], err); if (root) { char *roottag = tagXMLEle(root); const char *dev = findXMLAttValu (root, "device"); const char *name = findXMLAttValu (root, "name"); int isblob = !strcmp (tagXMLEle(root), "setBLOBVector"); Msg *mp; if (verbose > 2) { fprintf(stderr, "%s: Driver %s: read ", indi_tstamp(0),dp->name); traceMsg (root); } else if (verbose > 1) { fprintf (stderr, "%s: Driver %s: read <%s device='%s' name='%s'>\n", indi_tstamp(NULL), dp->name, tagXMLEle(root), findXMLAttValu (root, "device"), findXMLAttValu (root, "name")); } /* that's all if driver is just registering a snoop */ if (!strcmp (roottag, "getProperties")) { addSDevice (dp, dev, name); delXMLEle (root); continue; } /* that's all if driver is just registering a BLOB mode */ if (!strcmp (roottag, "enableBLOB")) { Property *sp = findSDevice (dp, dev, name); if (sp) crackBLOB (pcdataXMLEle (root), &sp->blob); delXMLEle (root); continue; } /* Found a new device? Let's add it to driver info */ if (dev[0] && isDeviceInDriver(dev, dp) == 0) { dp->dev = (char **) realloc(dp->dev, (dp->ndev+1) * sizeof(char *)); dp->dev[dp->ndev] = (char *) malloc(MAXINDIDEVICE * sizeof(char)); strncpy (dp->dev[dp->ndev], dev, MAXINDIDEVICE-1); dp->dev[dp->ndev][MAXINDIDEVICE-1] = '\0'; #ifdef OSX_EMBEDED_MODE if (!dp->ndev) fprintf(stderr, "STARTED \"%s\"\n", dp->name); fflush(stderr); #endif dp->ndev++; } /* log messages if any and wanted */ if (ldir) logDMsg (root, dev); /* build a new message -- set content iff anyone cares */ mp = newMsg(); /* send to interested clients */ if (q2Clients (NULL, isblob, dev, name, mp, root) < 0) shutany++; /* send to snooping drivers */ q2SDrivers (isblob, dev, name, mp, root); /* set message content if anyone cares else forget it */ if (mp->count > 0) setMsgXMLEle (mp, root); else freeMsg (mp); delXMLEle (root); } else if (err[0]) { char *ts = indi_tstamp(NULL); fprintf (stderr, "%s: Driver %s: XML error: %s\n", ts, dp->name, err); fprintf (stderr, "%s: Driver %s: XML read: %.*s\n", ts, dp->name, (int)nr, buf); shutdownDvr (dp, 1); return (-1); } } return (shutany ? -1 : 0); }