示例#1
0
void SlitherBot::newInstance() {
    BotInstance* instance = new BotInstance();
    ui->tabWidget->addTab(instance, "Bot (Loading)");
    BotController* controller = new BotController(instance, this);
    connect(&twitchChat, SIGNAL(comment(QString,QString)), controller, SIGNAL(twitchComment(QString,QString)));
    connect(&twitchChat, SIGNAL(parsedEmoticons(QVariantList)), controller, SIGNAL(parsedEmoticons(QVariantList)));
    connect(this, SIGNAL(updateMessages(QStringList)), controller, SIGNAL(updateMessages(QStringList)));
    instance->init(controller);
}
示例#2
0
void ofxObject::idleBase(float iTime)
{
	//timeElapsed = ofGetElapsedTimef() - timePrev; //ofGetSystemTime()/1000.0f - timePrev;
	//timePrev = ofGetElapsedTimef();	//ofGetSystemTime()/1000.0f;
  
	//timeElapsed = ofGetLastFrameTime();	//OF7
  //Calculate this locally so it's always based on the idle call times    //eg
  timeElapsed = iTime - timePrev;
  
	updateMessages();
	//call virtual
	idle(iTime);
  
	//call idle on all children
	for (unsigned int i = 0; i < children.size(); i++)
		children[i]->idleBase(iTime);
  
  // remove all marked children
  for( ofxObject *child : children_to_remove ){
    removeChild( child );
  }
  children_to_remove.clear();
  
  timePrev = iTime;   //eg
}
示例#3
0
/*----------------------------------------------------------------------------*/
void MainWindow::onDelLanguage()
{
  QString lang = m_langList[ui->langCombo->currentIndex()];
  m_messageFile->deleteLang(lang);
  updateMessages();
  m_messageFile->setModified(false);
}
示例#4
0
/*----------------------------------------------------------------------------*/
void MainWindow::onFileNew()
{
  if(!midifiedQuestion())
    return;
  delete m_messageFile;
  m_messageFile = new MessageFile;
  m_fileName.clear();
  updateMessages();
}
示例#5
0
/*----------------------------------------------------------------------------*/
void MainWindow::onNewLanguage()
{
  LanguageDialog dlg(this, m_messageFile);
  dlg.setPrompt(tr("Select locale for create new language"));
  if(dlg.exec() == QDialog::Accepted)
  {
    m_messageFile->addLang(dlg.lang());
    updateMessages();
    m_messageFile->setModified(true);
  }
}
示例#6
0
/*----------------------------------------------------------------------------*/
void MainWindow::onCopyLanguage()
{
  LanguageDialog dlg(this, m_messageFile);
  dlg.setPrompt(tr("Select locale for copy %1 locale").arg(ui->langCombo->currentText()));
  if(dlg.exec() == QDialog::Accepted)
  {
    QString srcLang = m_langList[ui->langCombo->currentIndex()];
    QString lang = dlg.lang();
    int size = m_sourceList.size();
    for(int i = 0; i < size; i++)
    {
      QString s = m_messageFile->message(m_sourceList[i], srcLang);
      m_messageFile->setMessage(m_sourceList[i], s, lang);
    }
    updateMessages();
  }
}
示例#7
0
文件: board.cpp 项目: akru/Netland-NG
void Board::connectAll()
{
  connect(_conn, SIGNAL(boardChannelsRecv(QMap<int, shared_ptr<BoardChannel> >)),
          this, SLOT(updateChannels(QMap<int,shared_ptr<BoardChannel> >)));
  connect(_conn, SIGNAL(boardMessagesRecv(QMap<int,shared_ptr<BoardMessage> >)),
          this, SLOT(updateMessages(QMap<int,shared_ptr<BoardMessage> >)));

  connect(this, SIGNAL(addMessageReady(int,QString, int)),
          _conn, SLOT(boardAddMessage(int,QString,int)));
  connect(this, SIGNAL(addReplyReady(int,QString)),
          _conn, SLOT(boardAddReply(int,QString)));
  connect(this, SIGNAL(editMessageReady(int,QString,int)),
          _conn, SLOT(boardEditMessage(int,QString,int)));
  connect(this, SIGNAL(deleteMessageReady(int)),
          _conn, SLOT(boardDeleteMessage(int)));
  connect(this, SIGNAL(upMessageReady(int)),
          _conn, SLOT(boardUpMessage(int)));
}
示例#8
0
void LLIMFloater::sendMsg()
{
    if (!gAgent.isGodlike()
            && (mDialog == IM_NOTHING_SPECIAL)
            && mOtherParticipantUUID.isNull())
    {
        llinfos << "Cannot send IM to everyone unless you're a god." << llendl;
        return;
    }

    if (mInputEditor)
    {
        LLWString text = mInputEditor->getConvertedText();
        if(!text.empty())
        {
            // Truncate and convert to UTF8 for transport
            std::string utf8_text = wstring_to_utf8str(text);
            utf8_text = utf8str_truncate(utf8_text, MAX_MSG_BUF_SIZE - 1);

            if (mSessionInitialized)
            {
                LLIMModel::sendMessage(utf8_text, mSessionID,
                                       mOtherParticipantUUID,mDialog);
            }
            else
            {
                //queue up the message to send once the session is initialized
                mQueuedMsgsForInit.append(utf8_text);
            }

            mInputEditor->setText(LLStringUtil::null);

            updateMessages();
        }
        else if (gSavedSettings.getBOOL("CloseIMOnEmptyReturn"))
        {
            // Close if we're the child of a floater
            closeFloater();
        }
    }
}
示例#9
0
/*----------------------------------------------------------------------------*/
void MainWindow::onFileOpen()
{
  if(!midifiedQuestion())
    return;
  QString fileName = QFileDialog::getOpenFileName(this,
       tr("Open File"), "", tr("XML Files (*.xml);;All files (*)"));
  if(fileName.isEmpty())
    return;

  delete m_messageFile;
  m_messageFile = new MessageFile;
  if(!m_messageFile->load(fileName))
  {
    QMessageBox::critical(this, tr("Error open file"), tr("Error open file '%1': %2").arg(fileName).arg(m_messageFile->errorString()));
    return;
  }
  m_fileName = fileName;
  updateMessages();
  if(ui->sourceList->count())
    ui->sourceList->setCurrentRow(0);
}
void LLIMFloater::setVisible(BOOL visible)
{
	LLNotificationsUI::LLScreenChannel* channel = static_cast<LLNotificationsUI::LLScreenChannel*>
		(LLNotificationsUI::LLChannelManager::getInstance()->
											findChannelByID(LLUUID(gSavedSettings.getString("NotificationChannelUUID"))));
	LLTransientDockableFloater::setVisible(visible);

	// update notification channel state
	if(channel)
	{
		channel->updateShowToastsState();
		channel->redrawToasts();
	}

	BOOL is_minimized = visible && isChatMultiTab()
		? LLIMFloaterContainer::getInstance()->isMinimized()
		: !visible;

	if (!is_minimized && mChatHistory && mInputEditor)
	{
		//only if floater was construced and initialized from xml
		updateMessages();
		//prevent stealing focus when opening a background IM tab (EXT-5387, checking focus for EXT-6781)
		if (!isChatMultiTab() || hasFocus())
		{
			mInputEditor->setFocus(TRUE);
		}
	}

	if(!visible)
	{
		LLIMChiclet* chiclet = LLChicletBar::getInstance()->getChicletPanel()->findChiclet<LLIMChiclet>(mSessionID);
		if(chiclet)
		{
			chiclet->setToggleState(false);
		}
	}
}
示例#11
0
SlitherBot::SlitherBot() :
    ui(new Ui::SlitherBot)
{
    ui->setupUi(this);
    connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
    //connect(ui->actionCreate, SIGNAL(triggered(bool)), this, SLOT(newInstance()));

    QToolBar *toolBar = new QToolBar;
    QLabel* nowPlaying = new QLabel();
    connect(&player, SIGNAL(nowPlaying(QString)), nowPlaying, SLOT(setText(QString)));
    toolBar->addWidget(nowPlaying);
    nowPlaying->setText("Now Playing: ...");

    QWidget* spacer = new QWidget();
    spacer->setMinimumWidth(12);
    toolBar->addWidget(spacer);

    QPushButton* button = new QPushButton();
    button->setText("New Tab");
    connect(button, SIGNAL(clicked(bool)), this, SLOT(newInstance()));
    toolBar->addWidget(button);

    button = new QPushButton();
    button->setText("Next Song");
    connect(button, SIGNAL(clicked(bool)), &player, SLOT(next()));
    toolBar->addWidget(button);

    button = new QPushButton();
    button->setText("Menu");
    connect(button, &QPushButton::clicked, [=]() {
        Menu menu(this);
        menu.setMessages(messages);
        menu.setXMPath(settings.value("xmpath", "").toString());
        menu.setTwitchChannel(settings.value("twitchchannel", "").toString());
        menu.setTwitchOAuth(settings.value("twitchoauth", "").toString());
        if(menu.exec() == QDialog::Accepted) {
            QString xmPath = menu.xmPath();
            QString twitchOAuth = menu.twitchOAuth();
            QString twitchChannel = menu.twitchChannel();
            QStringList messages = menu.messages();

            settings.setValue("xmpath", xmPath);
            settings.setValue("twitchoauth", twitchOAuth);
            settings.setValue("twitchchannel", twitchChannel);
            settings.setValue("messages", messages);

            emit updateMessages(messages);
            this->messages = messages;

            player.play(xmPath);
        }
    });
    toolBar->addWidget(button);

    ui->tabWidget->setCornerWidget(toolBar);

    QString xmPath = settings.value("xmpath").toString();
    if(!xmPath.isEmpty())
        player.play(xmPath);

    QString oauth = settings.value("twitchoauth").toString();
    QString channel = settings.value("twitchchannel").toString();
    if(!oauth.isEmpty() && !channel.isEmpty())
        twitchChat.connect(channel, oauth);

    messages = settings.value("messages").toStringList();

    QMetaObject::invokeMethod(&player, "next", Qt::QueuedConnection);
    QMetaObject::invokeMethod(this, "newInstance", Qt::QueuedConnection);
}
示例#12
0
int main(int argc, char *argv[])
{ 
#ifdef WINDOWS_SYS
	{
		/* Set the current directory to the application dir,
		   because the start dir with autostart from the registry run key is not the exe dir */
		QApplication app(argc, argv);
		QDir::setCurrent(QCoreApplication::applicationDirPath());
	}
#endif

  QStringList args = char_array_to_stringlist(argv+1, argc-1);
  
  Q_INIT_RESOURCE(images);

	rsiface = NULL;

	NotifyQt *notify = NotifyQt::Create();
	createRsIface(*notify);
	createRsControl(*rsiface, *notify);

        /* RetroShare Core Objects */
	RsInit::InitRsConfig();
	int initResult = RsInit::InitRetroShare(argc, argv);

	if (initResult < 0) {
		/* Error occured */
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		QMessageBox mb(QMessageBox::Critical, QObject::tr("RetroShare"), "", QMessageBox::Ok);
		mb.setWindowIcon(QIcon(":/images/rstray3.png"));

		switch (initResult) {
		case RS_INIT_AUTH_FAILED:
			std::cerr << "RsInit::InitRetroShare AuthGPG::InitAuth failed" << std::endl;
			mb.setText(QObject::tr("Inititialize failed. Wrong or missing installation of gpg."));
			break;
		default:
			/* Unexpected return code */
			std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
			mb.setText(QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
			break;
		}
		mb.exec();
		return 1;
	}

	/* create global settings object
	   path maybe wrong, when no profile exist
	   in this case it can be use only for default values */
	RshareSettings::Create ();

	/* Setup The GUI Stuff */
	Rshare rshare(args, argc, argv, 
		QString::fromStdString(RsInit::RsConfigDirectory()));

	std::string url = RsInit::getRetroShareLink();
	if (!url.empty()) {
		/* start with RetroShare link */
		EventReceiver eventReceiver;
		if (eventReceiver.sendRetroShareLink(QString::fromStdString(url))) {
			return 0;
		}

		/* Start RetroShare */
	}

	QSplashScreen splashScreen(QPixmap(":/images/splash.png")/* , Qt::WindowStaysOnTopHint*/);

	switch (initResult) {
	case RS_INIT_OK:
		{
			/* Login Dialog */
			/* check for existing Certificate */
			std::string userName;

			StartDialog *sd = NULL;
			bool genCert = false;
			std::list<std::string> accountIds;
			if (RsInit::getAccountIds(accountIds) && (accountIds.size() > 0))
			{
				sd = new StartDialog();
				sd->show();

				while(sd -> isVisible())
				{
					rshare.processEvents();
#ifdef WIN32
					Sleep(10);
#else // __LINUX__
					usleep(10000);
#endif
				}

				/* if we're logged in */
				genCert = sd->requestedNewCert();
				delete (sd);
			}
			else
			{
				genCert = true;
			}

			if (genCert)
			{
				GenCertDialog gd;
				gd.exec ();
			}

			splashScreen.show();
		}
		break;
	case RS_INIT_HAVE_ACCOUNT:
		{
			splashScreen.show();
			splashScreen.showMessage(rshare.translate("SplashScreen", "Load profile"), Qt::AlignHCenter | Qt::AlignBottom);

			std::string preferredId, gpgId, gpgName, gpgEmail, sslName;
			RsInit::getPreferedAccountId(preferredId);

			if (RsInit::getAccountDetails(preferredId, gpgId, gpgName, gpgEmail, sslName))
			{
				RsInit::SelectGPGAccount(gpgId);
			}

			// true: note auto-login is active
                        std::string lockFile;
                        int retVal = RsInit::LockAndLoadCertificates(true, lockFile);
			switch(retVal)
			{
				case 0:	break;
				case 1:	QMessageBox::warning(	0,
												QObject::tr("Multiple instances"),
												QObject::tr("Another RetroShare using the same profile is "
                                                                                                                "already running on your system. Please close "
                                                                                                                "that instance first\n Lock file:\n") +
                                                                                                                QString::fromStdString(lockFile));
						return 1;
				case 2:	QMessageBox::critical(	0,
												QObject::tr("Multiple instances"),
												QObject::tr("An unexpected error occurred when Retroshare"
                                                                                                                     "tried to acquire the single instance lock\n Lock file:\n") +
                                                                                                                     QString::fromStdString(lockFile));
						return 1;
				case 3: QMessageBox::critical(	0,
												QObject::tr("Login Failure"),
												QObject::tr("Maybe password is wrong") );
						return 1;
				default: std::cerr << "StartDialog::loadCertificates() unexpected switch value " << retVal << std::endl;
			}
		}
		break;
	default:
		/* Unexpected return code */
		std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
		QMessageBox::warning(0, QObject::tr("RetroShare"), QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
		return 1;
	}

	splashScreen.showMessage(rshare.translate("SplashScreen", "Load configuration"), Qt::AlignHCenter | Qt::AlignBottom);

	rsicontrol->StartupRetroShare();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Create interface"), Qt::AlignHCenter | Qt::AlignBottom);

	/* recreate global settings object, now with correct path */
	RshareSettings::Create ();
	RsharePeerSettings::Create();

#ifdef MINIMAL_RSGUI
	MessengerWindow::showYourself();

	rshare.setQuitOnLastWindowClosed(true);

	splashScreen.hide();
#else
	Emoticons::load();

	if (Settings->value(QString::fromUtf8("FirstRun"), true).toBool()) {
		splashScreen.hide();

		Settings->setValue(QString::fromUtf8("FirstRun"), false);
		QuickStartWizard qstartWizard;
		qstartWizard.exec();
	}

	MainWindow *w = MainWindow::Create ();
	splashScreen.finish(w);

	EventReceiver *eventReceiver = NULL;
	if (Settings->getRetroShareProtocol()) {
		/* Create event receiver */
		eventReceiver = new EventReceiver;
		if (eventReceiver->start()) {
			QObject::connect(eventReceiver, SIGNAL(linkReceived(const QUrl&)), w, SLOT(linkActivated(const QUrl&)));
		}
	}

	if (!url.empty()) {
		/* Now use link from the command line, because no RetroShare was running */
		RetroShareLink link(QString::fromStdString(url));
		if (link.valid()) {
			w->linkActivated(link.toUrl());
		}
	}

	// I'm using a signal to transfer the hashing info to the mainwindow, because Qt schedules signals properly to
	// avoid clashes between infos from threads.
	//

	qRegisterMetaType<FileDetail>("FileDetail") ;

	std::cerr << "connecting signals and slots" << std::endl ;
	QObject::connect(notify,SIGNAL(gotTurtleSearchResult(qulonglong,FileDetail)),w->searchDialog	,SLOT(updateFiles(qulonglong,FileDetail))) ;
	QObject::connect(notify,SIGNAL(diskFull(int,int))						,w                   		,SLOT(displayDiskSpaceWarning(int,int))) ;
	QObject::connect(notify,SIGNAL(filesPreModChanged(bool))          ,w->sharedfilesDialog		,SLOT(preModDirectories(bool)          )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w->sharedfilesDialog		,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w                            ,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(transfersChanged())                ,w->transfersDialog  		,SLOT(insertTransfers()                )) ;
	QObject::connect(notify,SIGNAL(friendsChanged())                  ,w->friendsDialog      		,SLOT(insertPeers()                    )) ;
	QObject::connect(notify,SIGNAL(publicChatChanged(int))            ,w->friendsDialog      		,SLOT(publicChatChanged(int)           ));
	QObject::connect(notify,SIGNAL(groupsChanged(int))                ,w->friendsDialog      		,SLOT(groupsChanged(int)               ));
	QObject::connect(notify,SIGNAL(privateChatChanged(int, int))      ,w                   		,SLOT(privateChatChanged(int, int)     ));
	QObject::connect(notify,SIGNAL(neighboursChanged())               ,w->networkDialog    		,SLOT(insertConnect()                  )) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w->messagesDialog   		,SLOT(insertMessages()                 )) ;
	QObject::connect(notify,SIGNAL(messagesTagsChanged())             ,w->messagesDialog   		,SLOT(messagesTagsChanged()            )) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w                   		,SLOT(updateMessages()                 )) ;
	QObject::connect(notify,SIGNAL(forumsChanged())                   ,w                   		,SLOT(updateForums()                   ), Qt::QueuedConnection);
	QObject::connect(notify,SIGNAL(channelsChanged(int))              ,w                   		,SLOT(updateChannels(int)              ), Qt::QueuedConnection);
	QObject::connect(notify,SIGNAL(downloadCompleteCountChanged(int)) ,w                   		,SLOT(updateTransfers(int)             ));

	QObject::connect(notify,SIGNAL(chatStatusChanged(const QString&,const QString&,bool)),w->friendsDialog,SLOT(updatePeerStatusString(const QString&,const QString&,bool)));
	QObject::connect(notify,SIGNAL(ownStatusMessageChanged()),w->friendsDialog,SLOT(loadmypersonalstatus()));

	QObject::connect(notify,SIGNAL(logInfoChanged(const QString&))		,w->networkDialog,SLOT(setLogInfo(QString))) ;
	QObject::connect(notify,SIGNAL(discInfoChanged())						,w->networkDialog,SLOT(updateNewDiscoveryInfo()),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(errorOccurred(int,int,const QString&)),w,SLOT(displayErrorMessage(int,int,const QString&))) ;

	QObject::connect(w->friendsDialog,SIGNAL(friendsUpdated()),w->networkDialog,SLOT(insertConnect())) ;

	w->installGroupChatNotifier();

	/* only show window, if not startMinimized */
	if (RsInit::getStartMinimised() || Settings->getStartMinimized())
	{
		splashScreen.close();
	} else {
		w->show();
	}

	/* Startup a Timer to keep the gui's updated */
	QTimer *timer = new QTimer(w);
	timer -> connect(timer, SIGNAL(timeout()), notify, SLOT(UpdateGUI()));
	timer->start(1000);
#endif // MINIMAL_RSGUI

	/* dive into the endless loop */
	int ti = rshare.exec();
#ifndef MINIMAL_RSGUI
	delete w ;

	if (eventReceiver) {
		/* Destroy event receiver */
		delete eventReceiver;
		eventReceiver = NULL;
	}

	/* cleanup */
	PopupChatDialog::cleanupChat();
#endif // MINIMAL_RSGUI

	rsicontrol->rsGlobalShutDown();

	Settings->sync();
	delete Settings;

	return ti ;
}
示例#13
0
void CMessageBox::warningClicked()
{
	updateMessages();
}
示例#14
0
void CMessageBox::errorClicked()
{
	updateMessages();
}
示例#15
0
/*!
    Updates the meta data of the existing message on the message store, to match \a metaData.
    Returns \c true if the operation completed successfully, or \c false otherwise. 
*/
bool QMailStore::updateMessage(QMailMessageMetaData* metaData)
{
    return updateMessages(QList<QMailMessageMetaData*>() << metaData);
}
示例#16
0
void CMessageBox::informationClicked()
{
	updateMessages();
}
示例#17
0
/*!
    Updates the existing QMailMessage \a msg on the message store.
    Returns \c true if the operation completed successfully, or \c false otherwise. 
*/
bool QMailStore::updateMessage(QMailMessage* msg)
{
    return updateMessages(QList<QMailMessage*>() << msg);
}
void LLIMFloater::updateChatHistoryStyle()
{
	mChatHistory->clear();
	mLastMessageIndex = -1;
	updateMessages();
}
示例#19
0
void LocalRulesManager::update(const double& timeStep)
{	
	ENetEvent event;

	while(enet_host_service(m_server, &event, 0) > 0)
	{
		switch (event.type)
		{
		case ENET_EVENT_TYPE_CONNECT:
			std::cout<<"Client connected: "<< event.peer->address.host << " : " << event.peer->address.port<<std::endl;
			break;

		case ENET_EVENT_TYPE_RECEIVE:
			updateMessages(event.packet->data, event.packet->dataLength);

			for(auto msg : m_messageQueue)
			{
				switch(msg->getType())
				{
				case C_HELLO:
					{
						sendMessage(MessagePtr(new Welcome("Server")), ENET_PACKET_FLAG_RELIABLE);
						m_isWaiting = false;
					}
					break;
				case G_UPDATE_POS:
					m_pongScene->updateOpponentPos(((UpdatePos*)msg.get())->getPosition());
					break;
				case G_BALLEVENT:
					{
						//std::cout<<"Ball event: " << (int)((BallEvent*)msg.get())->getEventType() << "  "<< (int)((BallEvent*)msg.get())->getPlayerId() << std::endl;
						BallEvent* evt = (BallEvent*)msg.get();
						switch(evt->getEventType())
						{
						case BallEvent::BALLEVENT_TABLE:	
							m_gameRules->onBallHitTable(evt->getPlayerId());
							break;
						case BallEvent::BALLEVENT_RACKET:	
							m_gameRules->onBallHitRacket(evt->getPlayerId());
							break;
						case BallEvent::BALLEVENT_OUTSIDE:	
							m_gameRules->onBallOut();
							break;
						}

						checkGameRules();
					}
					break;
				case G_BALLSTATE:
					{
						BallState* ballState = (BallState*)msg.get();
						m_pongScene->updateBallState(
							ballState->getPosition(), 
							ballState->getVelocity(), 
							ballState->getAngularVelocity(), 
							ballState->getServe(),
							ballState->getHitMagnitude());
						if(ballState->getServe() != 0)
							m_gameRules->onNewRound();
					}
					break;
				}
			}
			m_messageQueue.clear();

			//std::cout<<"Got data: "<< event.packet->dataLength << std::endl;
			break;

		case ENET_EVENT_TYPE_DISCONNECT:
			std::cout<<"Client disconnected: "<< event.peer->address.host << " : " << event.peer->address.port<<std::endl;
			break;
		}
	}
}
示例#20
0
void RemoteRulesManager::update(const double& timeStep)
{	
	ENetEvent event;

	while(enet_host_service(m_client, &event, 0) > 0)
	{
		switch (event.type)
		{
		case ENET_EVENT_TYPE_CONNECT:
			{
				sendMessage(MessagePtr(new Hello("Client")), ENET_PACKET_FLAG_RELIABLE);
			}
			break;

		case ENET_EVENT_TYPE_RECEIVE:
			updateMessages(event.packet->data, event.packet->dataLength);

			for(auto msg : m_messageQueue)
			{
				switch(msg->getType())
				{
				case S_WELCOME:
					std::cout<<"GOT WELCOME "<<msg->getData()<<std::endl;
					m_isWaiting = false;
					break;
				case G_UPDATE_POS:
					m_pongScene->updateOpponentPos(((UpdatePos*)msg.get())->getPosition());
					break;
				case G_BALLSTATE:
					{
						BallState* ballState = (BallState*)msg.get();
						m_pongScene->updateBallState(
							ballState->getPosition(), 
							ballState->getVelocity(), 
							ballState->getAngularVelocity(), 
							ballState->getServe(),
							ballState->getHitMagnitude());
					}
					break;
				case G_META:
					{
						MetaGameInfo* meta = (MetaGameInfo*)msg.get();
						switch(meta->getEventType())
						{
						case MetaGameInfo::META_ROUND_START:
							m_pongScene->onNewRound(
								meta->getLocalScore(),
								meta->getRemoteScore(),
								meta->getServe(),
								meta->getWinner());
							break;
						case MetaGameInfo::META_GAME_OVER:
							m_pongScene->onGameOver(
								meta->getLocalScore(),
								meta->getRemoteScore(),
								meta->getWinner());
							break;
						}
					}
					break;
				}
			}
			m_messageQueue.clear();

			//std::cout<<"Got data: "<< event.packet->dataLength << std::endl;
			break;

		case ENET_EVENT_TYPE_DISCONNECT:
			std::cout<<"Client disconnected: "<< event.peer->address.host << " : " << event.peer->address.port<<std::endl;
			break;
		}
	}
}
示例#21
0
int main(int argc, char *argv[])
{ 
#ifdef WINDOWS_SYS
	{
		/* Set the current directory to the application dir,
		   because the start dir with autostart from the registry run key is not the exe dir */
		QApplication app(argc, argv);
		QDir::setCurrent(QCoreApplication::applicationDirPath());
	}
#endif

	QStringList args = char_array_to_stringlist(argv+1, argc-1);

	Q_INIT_RESOURCE(images);

	rsiface = NULL;

	NotifyQt *notify = NotifyQt::Create();
	createRsIface(*notify);
	createRsControl(*rsiface, *notify);

	/* RetroShare Core Objects */
	RsInit::InitRsConfig();
	int initResult = RsInit::InitRetroShare(argc, argv);

	if(initResult == RS_INIT_NO_KEYRING)	// happens when we already have accounts, but no pgp key. This is when switching to the openpgp-sdk version.
	{
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		/* Translate into the desired language */
		LanguageSupport::translate(LanguageSupport::defaultLanguageCode());

		QMessageBox msgBox;
		msgBox.setText(QObject::tr("This version of RetroShare is using OpenPGP-SDK. As a side effect, it's not using the system shared PGP keyring, but has it's own keyring shared by all RetroShare instances. <br><br>You do not appear to have such a keyring, although GPG keys are mentionned by existing RetroShare accounts, probably because you just changed to this new version of the software."));
		msgBox.setInformativeText(QObject::tr("Choose between:<br><ul><li><b>Ok</b> to copy the existing keyring from gnupg (safest bet), or </li><li><b>Close without saving</b> to start fresh with an empty keyring (you will be asked to create a new PGP key to work with RetroShare, or import a previously saved pgp keypair). </li><li><b>Cancel</b> to quit and forge a keyring by yourself (needs some PGP skills)</li></ul>"));
		msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Discard | QMessageBox::Cancel);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.setWindowIcon(QIcon(":/images/rstray3.png"));

		int ret = msgBox.exec();

		if(ret == QMessageBox::Cancel)
			return 0 ;
		if(ret == QMessageBox::Ok)
		{
			if(!RsInit::copyGnuPGKeyrings())
				return 0 ; 

			initResult = RsInit::InitRetroShare(argc, argv);

			displayWarningAboutDSAKeys() ;

		}
		else
			initResult = RS_INIT_OK ;
	}

	if (initResult < 0) {
		/* Error occured */
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		/* Translate into the desired language */
		LanguageSupport::translate(LanguageSupport::defaultLanguageCode());

		displayWarningAboutDSAKeys();

		QMessageBox mb(QMessageBox::Critical, QObject::tr("RetroShare"), "", QMessageBox::Ok);
		mb.setWindowIcon(QIcon(":/images/rstray3.png"));

		switch (initResult) 
		{
			case RS_INIT_AUTH_FAILED:
				std::cerr << "RsInit::InitRetroShare AuthGPG::InitAuth failed" << std::endl;
				mb.setText(QObject::tr("Inititialize failed. Wrong or missing installation of gpg."));
				break;
			default:
				/* Unexpected return code */
				std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
				mb.setText(QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
				break;
		}
		mb.exec();
		return 1;
	}

	/* create global settings object
	   path maybe wrong, when no profile exist
	   in this case it can be use only for default values */
	RshareSettings::Create ();

	/* Setup The GUI Stuff */
	Rshare rshare(args, argc, argv, 
		QString::fromUtf8(RsInit::RsConfigDirectory().c_str()));

	std::string url = RsInit::getRetroShareLink();
	if (!url.empty()) {
		/* start with RetroShare link */
		EventReceiver eventReceiver;
		if (eventReceiver.sendRetroShareLink(QString::fromStdString(url))) {
			return 0;
		}

		/* Start RetroShare */
	}

	QSplashScreen splashScreen(QPixmap(":/images/splash.png")/* , Qt::WindowStaysOnTopHint*/);

	switch (initResult) {
	case RS_INIT_OK:
		{
			/* Login Dialog */
			/* check for existing Certificate */
			StartDialog *sd = NULL;
			bool genCert = false;
			std::list<std::string> accountIds;
			if (RsInit::getAccountIds(accountIds) && (accountIds.size() > 0))
			{
				sd = new StartDialog();
				sd->show();

				while(sd -> isVisible())
				{
					rshare.processEvents();
#ifdef WIN32
					Sleep(10);
#else // __LINUX__
					usleep(10000);
#endif
				}

				/* if we're logged in */
				genCert = sd->requestedNewCert();
				delete (sd);
			}
			else
			{
				genCert = true;
			}

			if (genCert)
			{
				GenCertDialog gd;
				gd.exec ();
			}

			splashScreen.show();
		}
		break;
	case RS_INIT_HAVE_ACCOUNT:
		{
			splashScreen.show();
			splashScreen.showMessage(rshare.translate("SplashScreen", "Load profile"), Qt::AlignHCenter | Qt::AlignBottom);

			std::string preferredId, gpgId, gpgName, gpgEmail, sslName;
			RsInit::getPreferedAccountId(preferredId);

			if (RsInit::getAccountDetails(preferredId, gpgId, gpgName, gpgEmail, sslName))
			{
				RsInit::SelectGPGAccount(gpgId);
			}

			// true: note auto-login is active
			std::string lockFile;
			int retVal = RsInit::LockAndLoadCertificates(true, lockFile);
			switch(retVal)
			{
				case 0:	break;
				case 1:	QMessageBox::warning(	0,
												QObject::tr("Multiple instances"),
												QObject::tr("Another RetroShare using the same profile is "
												"already running on your system. Please close "
												"that instance first\n Lock file:\n") +
												QString::fromStdString(lockFile));
						return 1;
				case 2:	QMessageBox::critical(	0,
												QObject::tr("Multiple instances"),
												QObject::tr("An unexpected error occurred when Retroshare"
												"tried to acquire the single instance lock\n Lock file:\n") +
												QString::fromStdString(lockFile));
						return 1;
				case 3: QMessageBox::critical(	0,
												QObject::tr("Login Failure"),
												QObject::tr("Maybe password is wrong") );
						return 1;
				default: std::cerr << "StartDialog::loadCertificates() unexpected switch value " << retVal << std::endl;
			}
		}
		break;
	default:
		/* Unexpected return code */
		std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
		QMessageBox::warning(0, QObject::tr("RetroShare"), QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
		return 1;
	}

	/* recreate global settings object, now with correct path */
	RshareSettings::Create(true);
	Rshare::resetLanguageAndStyle();

	SoundManager::create();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Load configuration"), Qt::AlignHCenter | Qt::AlignBottom);

	/* stop Retroshare if startup fails */
	if (!rsicontrol->StartupRetroShare())
	{
		std::cerr << "libretroshare failed to startup!" << std::endl;
		return 1;
	}


	Rshare::initPlugins();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Create interface"), Qt::AlignHCenter | Qt::AlignBottom);

	RsharePeerSettings::Create();

	Emoticons::load();

	if (Settings->value(QString::fromUtf8("FirstRun"), true).toBool()) {
		splashScreen.hide();

		Settings->setValue(QString::fromUtf8("FirstRun"), false);

#ifdef __APPLE__
		/* For OSX, we set the default to "cleanlooks", as the AQUA style hides some input boxes 
		 * only on the first run - as the user might want to change it ;)
		 */
		QString osx_style("cleanlooks");
		Rshare::setStyle(osx_style);
		Settings->setInterfaceStyle(osx_style);
#endif

// This is now disabled - as it doesn't add very much.
// Need to make sure that defaults are sensible!
#ifdef ENABLE_QUICKSTART_WIZARD
		QuickStartWizard qstartWizard;
		qstartWizard.exec();
#endif

	}

	MainWindow *w = MainWindow::Create ();
	splashScreen.finish(w);

	EventReceiver *eventReceiver = NULL;
	if (Settings->getRetroShareProtocol()) {
		/* Create event receiver */
		eventReceiver = new EventReceiver;
		if (eventReceiver->start()) {
			QObject::connect(eventReceiver, SIGNAL(linkReceived(const QUrl&)), w, SLOT(linkActivated(const QUrl&)));
		}
	}

	if (!url.empty()) {
		/* Now use link from the command line, because no RetroShare was running */
		RetroShareLink link(QString::fromStdString(url));
		if (link.valid()) {
			w->linkActivated(link.toUrl());
		}
	}

	// I'm using a signal to transfer the hashing info to the mainwindow, because Qt schedules signals properly to
	// avoid clashes between infos from threads.
	//

	qRegisterMetaType<FileDetail>("FileDetail") ;

	std::cerr << "connecting signals and slots" << std::endl ;
	QObject::connect(notify,SIGNAL(gotTurtleSearchResult(qulonglong,FileDetail)),w->searchDialog	,SLOT(updateFiles(qulonglong,FileDetail))) ;
	QObject::connect(notify,SIGNAL(diskFull(int,int))						,w                   		,SLOT(displayDiskSpaceWarning(int,int))) ;
	QObject::connect(notify,SIGNAL(filesPreModChanged(bool))          ,w->sharedfilesDialog		,SLOT(preModDirectories(bool)          )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w->sharedfilesDialog		,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w                            ,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(transfersChanged())                ,w->transfersDialog  		,SLOT(insertTransfers()                )) ;
	QObject::connect(notify,SIGNAL(publicChatChanged(int))            ,w->friendsDialog      		,SLOT(publicChatChanged(int)           ));
	QObject::connect(notify,SIGNAL(privateChatChanged(int, int))      ,w                   		,SLOT(privateChatChanged(int, int)     ));
	QObject::connect(notify,SIGNAL(neighboursChanged())               ,w->networkDialog    		,SLOT(insertConnect()                  )) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w->messagesDialog   		,SLOT(insertMessages()                 )) ;
	QObject::connect(notify,SIGNAL(messagesTagsChanged())             ,w->messagesDialog   		,SLOT(messagesTagsChanged()            )) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w                   		,SLOT(updateMessages()                 )) ;
	QObject::connect(notify,SIGNAL(forumsChanged())                   ,w                   		,SLOT(updateForums()                   ), Qt::QueuedConnection);
	QObject::connect(notify,SIGNAL(channelsChanged(int))              ,w                   		,SLOT(updateChannels(int)              ), Qt::QueuedConnection);
	QObject::connect(notify,SIGNAL(downloadCompleteCountChanged(int)) ,w                   		,SLOT(updateTransfers(int)             ));

	QObject::connect(notify,SIGNAL(chatStatusChanged(const QString&,const QString&,bool)),w->friendsDialog,SLOT(updatePeerStatusString(const QString&,const QString&,bool)));
	QObject::connect(notify,SIGNAL(ownStatusMessageChanged()),w->friendsDialog,SLOT(loadmypersonalstatus()));

	QObject::connect(notify,SIGNAL(logInfoChanged(const QString&))		,w->networkDialog,SLOT(setLogInfo(QString))) ;
	QObject::connect(notify,SIGNAL(discInfoChanged())						,w->networkDialog,SLOT(updateNewDiscoveryInfo()),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(errorOccurred(int,int,const QString&)),w,SLOT(displayErrorMessage(int,int,const QString&))) ;

	w->installGroupChatNotifier();

	/* only show window, if not startMinimized */
	if (RsInit::getStartMinimised() || Settings->getStartMinimized())
	{
		splashScreen.close();
	} else {
		w->show();
	}

	/* Startup a Timer to keep the gui's updated */
	QTimer *timer = new QTimer(w);
	timer -> connect(timer, SIGNAL(timeout()), notify, SLOT(UpdateGUI()));
	timer->start(1000);

	notify->enable() ;	// enable notification system after GUI creation, to avoid data races in Qt.

	/* dive into the endless loop */
	int ti = rshare.exec();
	delete w ;

	if (eventReceiver) {
		/* Destroy event receiver */
		delete eventReceiver;
		eventReceiver = NULL;
	}

	/* cleanup */
	ChatDialog::cleanupChat();

	rsicontrol->rsGlobalShutDown();

	delete(soundManager);
	soundManager = NULL;

	Settings->sync();
	delete(Settings);

	return ti ;
}
void LLIMFloater::reloadMessages()
{
	mChatHistory->clear();
	mLastMessageIndex = -1;
	updateMessages();
}
void LLIMFloater::sendMsg()
{
	if (!gAgent.isGodlike() 
		&& (mDialog == IM_NOTHING_SPECIAL)
		&& mOtherParticipantUUID.isNull())
	{
		llinfos << "Cannot send IM to everyone unless you're a god." << llendl;
		return;
	}

	if (mInputEditor)
	{
		LLWString text = mInputEditor->getConvertedText();
		if(!text.empty())
		{
			// Truncate and convert to UTF8 for transport
			std::string utf8_text = wstring_to_utf8str(text);
			utf8_text = utf8str_truncate(utf8_text, MAX_MSG_BUF_SIZE - 1);
			
// [RLVa:KB] - Checked: 2010-11-30 (RLVa-1.3.0c) | Modified: RLVa-1.3.0c
			if ( (gRlvHandler.hasBehaviour(RLV_BHVR_SENDIM)) || (gRlvHandler.hasBehaviour(RLV_BHVR_SENDIMTO)) )
			{
				LLIMModel::LLIMSession* pIMSession = LLIMModel::instance().findIMSession(mSessionID);
				RLV_ASSERT(pIMSession);

				bool fRlvFilter = !pIMSession;
				if (pIMSession)
				{
					switch (pIMSession->mSessionType)
					{
						case LLIMModel::LLIMSession::P2P_SESSION:	// One-on-one IM
							fRlvFilter = !gRlvHandler.canSendIM(mOtherParticipantUUID);
							break;
						case LLIMModel::LLIMSession::GROUP_SESSION:	// Group chat
							fRlvFilter = !gRlvHandler.canSendIM(mSessionID);
							break;
						case LLIMModel::LLIMSession::ADHOC_SESSION:	// Conference chat: allow if all participants can be sent an IM
							{
								if (!pIMSession->mSpeakers)
								{
									fRlvFilter = true;
									break;
								}

								LLSpeakerMgr::speaker_list_t speakers;
								pIMSession->mSpeakers->getSpeakerList(&speakers, TRUE);
								for (LLSpeakerMgr::speaker_list_t::const_iterator itSpeaker = speakers.begin(); 
										itSpeaker != speakers.end(); ++itSpeaker)
								{
									const LLSpeaker* pSpeaker = *itSpeaker;
									if ( (gAgent.getID() != pSpeaker->mID) && (!gRlvHandler.canSendIM(pSpeaker->mID)) )
									{
										fRlvFilter = true;
										break;
									}
								}
							}
							break;
						default:
							fRlvFilter = true;
							break;
					}
				}

				if (fRlvFilter)
					utf8_text = RlvStrings::getString(RLV_STRING_BLOCKED_SENDIM);
			}
// [/RLVa:KB]

			if (mSessionInitialized)
			{
				LLIMModel::sendMessage(utf8_text, mSessionID,
					mOtherParticipantUUID,mDialog);
			}
			else
			{
				//queue up the message to send once the session is initialized
				mQueuedMsgsForInit.append(utf8_text);
			}

			mInputEditor->setText(LLStringUtil::null);

			updateMessages();
		}
	}
}