Beispiel #1
0
QSqlDatabase Application::sqlConnetion()
{
	QSqlDatabase db = QSqlDatabase::database(QSqlDatabase::defaultConnection, false);
	if(!db.isValid()) {
		Application *app = this;
		db = QSqlDatabase::addDatabase("QFMYSQL");
		db.setHostName(app->appConfigValue("connection/host").toString());
		db.setPort(app->appConfigValue("connection/port").toInt());
		db.setDatabaseName(app->appConfigValue("connection/database").toString());
		db.setUserName(app->appConfigValue("connection/user").toString());
		db.setPassword(app->appConfigValue("connection/password").toString());
		QString opts = "QF_CODEC_NAME=cp1250;QF_MYSQL_SET_NAMES=latin1";
		qDebug() << "connecting to:" << db.hostName() << db.port() << db.userName() << db.password();
		db.setConnectOptions(opts);
		//db.setPassword("toor");
		bool ok = db.open();
		if(!ok) qCritical() << "ERROR open database:" << db.lastError().text();
		else {
			//QSqlQuery q(db);
			//q.exec("SET NAMES latin1");
		}
	}
	return db;
}
Beispiel #2
0
bool ApplicationList::FindDefaultWindowsEditor()
{
    const QString appPath(getenv("ProgramFiles"));
    const QString notepadppPath = appPath + "\\Notepad++\\notepad++.exe";
    if (QFileInfo(notepadppPath).isExecutable()) {
        Application app;
        app.setName("Notepad++");
        app.setPath("\"" + notepadppPath + "\"");
        app.setParameters("-n(line) (file)");
        AddApplication(app);
        return true;
    }

    const QString notepadTwoPath = appPath + "\\Notepad2\\Notepad2.exe";
    if (QFileInfo(notepadTwoPath).isExecutable()) {
        Application app;
        app.setName("Notepad2");
        app.setPath("\"" + notepadTwoPath + "\"");
        app.setParameters("/g (line) (file)");
        AddApplication(app);
        return true;
    }

    const QString windowsPath(getenv("windir"));
    const QString notepadPath = windowsPath + "\\system32\\notepad.exe";
    if (QFileInfo(notepadPath).isExecutable()) {
        Application app;
        app.setName("Notepad");
        app.setPath(notepadPath);
        app.setParameters("(file)");
        AddApplication(app);
        return true;
    }
    return false;
}
Beispiel #3
0
int
main ()
{
  // This is a catch-all layer that should be in use only
  // if we are really in trouble.
  try
  {
    // This is a catch-system layer. Here we will catch exceptions like
    // bad_alloc, etc. If we get here it means that nobody wanted/managed
    // to recover from this kind of errors.
    try
    {
      // This is a catch-logic layer. If we get here it usually
      // indicates an application logic error.
      try
      {

        // Ok, here we go about our application logic.
        try
        {
          for (int i = 0; i < 10; i++)
          {
            try
            {
              Application app ("Hi dude!");
              app.run ();
              break;
            }
            catch (Application::FeelingDizzy const& )
            {
              if (i == 9)
              {
                cerr << "Given up!" << endl;
                return -1;
              }
              else
              {
                cerr << "Application is feeling dizzy. Trying again..."
                     << endl;
              }
            }
          }
        }
        catch (Application::InvalidArg const& )
        {
          cerr << "Cought Application::InvalidArg : ...hmm... strange!"
               << endl;
          return -1;
        }
      }
      catch (ExH::Logic::Exception const& e)
      {
        cerr << "Caught Logic::Exception : " << e.what () << endl;
        return -1;
      }
    }
    catch (const ExH::System::Exception& e)
    {
      cerr << "Caught System::Exception : " << e.what () << endl;
      return -1;
    }
    catch (...)
    {
      cerr << "Caught unknown exception using catch-all handler." << endl;
      return -1;
    }
  }
  catch (...)
  {
    // We get here in cases of some hard failure. For example when handling
    // exception, operator << throws another exception. Usually application
    // cannot handle such failures itself so we just propagate it futher.
    std::abort ();
  }
}
int main()
{
	// Our application initialization params
	Application::InitializationParams initParams = {};
	initParams.sApplicationName = "Chronicles of a Fallen Soul";
	initParams.sEngineName = "Wonderland";
	initParams.sApplicationVersion = VK_MAKE_VERSION(0, 0, 1);
	initParams.sEngineVersion = VK_MAKE_VERSION(0, 0, 1);
	initParams.sTotalNumberPeonThreads = 4;
	initParams.sThreadRingBufferSize = 65000;

	// Create and initialize the main application
	Application mainApplication = {};
	if (!mainApplication.Initialize(initParams))
	{
		return false;
	}

	// Run the main loop
	mainApplication.MainLoop();

	//

	bool result;

	//

	// Get all creator a register instances we need
	Flux::ClassCreator* classCreatorInstance = Flux::ClassCreator::GetInstance();
	Flux::ClassRegister* classRegisterInstance = Flux::ClassRegister::GetInstance();
	Flux::TypeCreator* typeCreatorInstance = Flux::TypeCreator::GetInstance();
	Flux::TypeRegister* typeRegisterInstance = Flux::TypeRegister::GetInstance();
	Flux::DynamicMemberFunctionCreator* memberFunctionCreatorInstance = Flux::DynamicMemberFunctionCreator::GetInstance();

	// Basic type registration //
	Flux::Type* intType = typeCreatorInstance->CreateType("int");
	Flux::Type* floatType = typeCreatorInstance->CreateType("float");
	Flux::Type* charType = typeCreatorInstance->CreateType("char");
	Flux::Type* stringType = typeCreatorInstance->CreateType("string");
	Flux::Type* booleanType = typeCreatorInstance->CreateType("bool");
	Flux::Type* vectorType = typeCreatorInstance->CreateType("vector");

	// Class creation //

	// Create a new class
	Flux::Class* newClass = classCreatorInstance->CreateClass("Car");
	if (newClass == nullptr)
	{
		return false;
	}

	// Create a variable from the created class
	Flux::MemberVariable speedVariable;
	result = speedVariable.Build(floatType, "m_Speed");
	if (!result)
	{
		return false;
	}

	// Add the member variable
	result = newClass->AddMemberVariable(speedVariable);
	if(!result)
	{
		return false;
	}

	// Create a variable from the created class
	Flux::MemberVariable distanceVariable;
	result = distanceVariable.Build(intType, "m_CurrentDistance");
	if (!result)
	{
		return false;
	}

	// Add the member variable
	result = newClass->AddMemberVariable(speedVariable);
	if (!result)
	{
		return false;
	}

	// Create a variable from the created class
	Flux::MemberVariable costVariable;
	result = costVariable.Build(floatType, "m_CostPerDistance");
	if (!result)
	{
		return false;
	}

	// Add the member variable
	result = newClass->AddMemberVariable(speedVariable);
	if (!result)
	{
		return false;
	}

	// Function creation //

	// Create the nem member function
	Flux::DynamicMemberFunction* newFunction = memberFunctionCreatorInstance->CreateDynamicMemberFunction("CalculateTime", *newClass);
	if (newFunction == nullptr)
	{
		return false;
	}

	/*

		- Handle precisa ter um id de versão
	*/

	/*
		
		=> Dynamic Function:

		- Head		-> Definições de uma função (qual o nome, se pertence à uma classe, quais entradas... etc)
		- Body		-> Como esta definido o seu corpo, quais funções (boxes) são utilizados, quais foram as ligações efetuadas, variáveis utilizadas... etc
		- Linker	-> Realização da compilação da DynamicFunction em realtime.
	*/

	/*
		- Vamos ter uma nova classe que vai ser tipo um box, ele vai contar o ponto inicial, final e vai possuir blocos que vão se ligar entre si, esses blocos fazem referência
		à um box conectado.
		- Começando no bloco inicial, vamos ir para o proximo, aqui podemos ter por exemplo uma função membro, nosso objetivo será pegar os dados da função membro, fazer a chamada
		com ela utilizando as variáveis linkadas (nota que não foi incluido a geração dos nomes das variáveis).
		- Após isso vamos para a proxima função, que pode ser um loop por exemplo, o loop deve criar uma variável que vai ser o contador e usar os parâmetros de entrada para realizar
		as chamadas seguintes.

		- Da pra perceber que o ideal é fechar cada bloco, por exemplo no primeiro, podemos passar as variáveis linkadas aos sockets de entrada para o "fechador" da função membro
		utilizada e ela fica responsável por usar essas entradas e gerar a chamada, podendo até mesmo retornar e assim seguimos para a proxima box ou continuar por conta propria.
		- No segundo exemplo nos iriamos para um loop, ele vai ter os valores de entrada (index inicial, final, etc) e provavelmente deveriamos continuar a execução por conta
		propria.

		- Temos que pensar em como vamos fazer os ifs, os sequences, sets, gets, for eachs, prints, etc... São todas funções standard, intrinsic.
		- Talvez devemos separar tipo, funções membro, funções normais, loop for, if, set, get e assim vai... Só que as funções (tanto membro quando normais) existiriam de várias
		formas precisando serem registradas enquanto os outros seriam classes especializadas que não precisariam serem registradas, afinal já teriamos uma de cada tipo.
		- O ideal seria que tivermos uma forma de criar essas funções intrinsics, talvez seja possível faze-las na parte de funções normais ou quem sabe fazer um criador para elas.
	*/

	/*
		- Uma box pode ter inputs e outputs, não importa qual o tipo de box.
		- Uma input/output pode ser de vários tipos.

		- Uma box pode ser uma função, uma caixa de debug, um start ou end dentro de uma função, etc.
		- Uma input/output pode ser uma variável, um valor absoluto, uma constante, etc.
		- Uma input/output pode ter um valor temporário para teste na engine.
		- Uma input/output pode ser uma array, nesse caso ele não pode possuir um valor absoluto e sim deve ser uma variável.

		- Uma box SEMPRE deve ter (se tiver) apenas UMA entrada.
		- Uma box pode ter várias saídas desde que mantenha em mente que as saídas serão executadas em sequência (depende da interpretação da box)

		
	
	
	
	
	*/

	////////////////
	// INITIALIZE //
	////////////////
	MainViewController viewController;
	viewController.Initialize();

	////////////////////////
	////////////////////////
	////////////////////////

    return 0;
}
Beispiel #5
0
void status_recstart(Recog *recog, void *app_)
{
  Application *app = (Application *)app_;
  app->tell("recstart");
}
Beispiel #6
0
void status_recready(Recog *recog, void *app_)
{
  Application *app = (Application *)app_;
  app->tell("recready");
}
int APIENTRY _tWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow) {
	System::OpenLog();
	System::Log("Logfile opening");

	if(!System::FileExists("../data/config.txt")) {
		System::Notify("Could not find a config-file!","Error!");
		return 1;
	};
	ConfigFile cfg("../data/config.txt");
	if(!cfg.HasKey("width")) {cfg.Set("width",ToString(1280));};
	if(!cfg.HasKey("height")) {cfg.Set("height",ToString(720));};
	if(!cfg.HasKey("m_yaw")) {cfg.Set("m_yaw",ToString(0.022f));};
	if(!cfg.HasKey("m_pitch")) {cfg.Set("m_pitch",ToString(-0.022f));};
	if(!cfg.HasKey("m_sensitivity")) {cfg.Set("m_sensitivity",ToString(50.0f));};
	if(!cfg.HasKey("c_speed")) {cfg.Set("c_speed",ToString(20.0f));};
	if(!cfg.HasKey("c_znear")) {cfg.Set("c_znear",ToString(0.5f));};
	if(!cfg.HasKey("c_zfar")) {cfg.Set("c_zfar",ToString(1000.0f));};

	const int width=cfg.AsInt("width"),height=cfg.AsInt("height");

	// create window class for registration
	WNDCLASSEX wc;
	wc.cbSize=sizeof(WNDCLASSEX);
	wc.style=CS_HREDRAW|CS_VREDRAW|CS_OWNDC;
	wc.lpfnWndProc=WndProc;
	wc.cbClsExtra=0;
	wc.cbWndExtra=0;
	wc.hInstance=hInstance;
	wc.hIcon=::LoadIcon(wc.hInstance,MAKEINTRESOURCE(IDI_GPIIBASE));
	wc.hIconSm=::LoadIcon(wc.hInstance,MAKEINTRESOURCE(IDI_GPIIBASE));
	wc.hCursor=::LoadCursor(NULL,IDC_ARROW);
	wc.hbrBackground=(HBRUSH)::GetStockObject(BLACK_BRUSH);
	wc.lpszMenuName=NULL;
	wc.lpszClassName=L"kWndCls";

	if(!::RegisterClassEx(&wc)) {
		System::Notify("Could not register window class","Error!");
		return 1;
	};

	unsigned int style=(WS_OVERLAPPEDWINDOW&~(WS_THICKFRAME|WS_MAXIMIZEBOX|WS_MINIMIZEBOX));
	RECT rc={0,0,width,height}; 
	::AdjustWindowRect(&rc,style,FALSE); 

	// create the main window
	HWND hWnd=::CreateWindow(
		L"kWndCls",
		L"RenderWindow",
		style,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		rc.right-rc.left,
		rc.bottom-rc.top,
		NULL,NULL,
		hInstance,
		NULL);
	if(hWnd==NULL) {
		System::Notify("Could not create a window","Error!");
		return 1;
	};

	::ShowWindow(hWnd,nCmdShow);
	::UpdateWindow(hWnd);

	// create application
	Application application;
	if(!application.Init(&message_system,hWnd,cfg)) {
		System::Notify("Could not initialize Application!\n"\
			"Read log.txt for more information.","Error!");
		return -1;
	};

	MSG msg={0};
	while(msg.message!=WM_QUIT) {
		if(::PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
			::TranslateMessage(&msg);
			::DispatchMessage(&msg);
		}
		else {
			application.Tick();
			::Sleep(2);
		};
	};

	application.Shut();

	::DestroyWindow(hWnd);

	System::Log("Logfile closing");
	System::CloseLog();

	return 0;
};
Beispiel #8
0
 void Application::termApplication()
 {
     Application* application = &System::getApplication();
     application->termInternal();
     LDELETE(application);
 }
Beispiel #9
0
 EVENT(on_discuss_msg, const cq::DiscussMessageEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_message_event(e, data);
     app.on_after_event(e, data);
 }
Beispiel #10
0
 EVENT(on_group_msg, const cq::GroupMessageEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_message_event(e, data);
     app.on_after_event(e, data);
 }
Beispiel #11
0
 EVENT(on_private_msg, const cq::PrivateMessageEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_message_event(e, data);
     app.on_after_event(e, data);
 }
Beispiel #12
0
namespace cqhttp {
    Application app;

    static vector<function<void()>> callback_initializers;

    static bool add_callback_initializer(const function<void()> initializer) {
        callback_initializers.push_back(initializer);
        return true;
    }

    void init() {
        for (const auto &initializer : callback_initializers) {
            initializer();
        }
    }

/**
 * Generate lifecycle callbacks.
 */
#define LIFECYCLE(Name)                            \
    static void __on_##Name() { app.on_##Name(); } \
    static bool __dummy_on_##Name = add_callback_initializer([]() { cq::app::on_##Name = __on_##Name; })

    LIFECYCLE(initialize);
    LIFECYCLE(enable);
    LIFECYCLE(disable);
    LIFECYCLE(coolq_start);
    LIFECYCLE(coolq_exit);

/**
 * Generate event callbacks.
 */
#define EVENT(Name, ...)                                                                                         \
    static void __##Name##_event(__VA_ARGS__);                                                                   \
    static bool __dummy_##Name##_event = add_callback_initializer([]() { cq::event::Name = __##Name##_event; }); \
    static void __##Name##_event(__VA_ARGS__)

    EVENT(on_private_msg, const cq::PrivateMessageEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_message_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_group_msg, const cq::GroupMessageEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_message_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_discuss_msg, const cq::DiscussMessageEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_message_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_group_upload, const cq::GroupUploadEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_notice_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_group_admin, const cq::GroupAdminEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_notice_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_group_member_decrease, const cq::GroupMemberDecreaseEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_notice_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_group_member_increase, const cq::GroupMemberIncreaseEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_notice_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_friend_add, const cq::FriendAddEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_notice_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_friend_request, const cq::FriendRequestEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_request_event(e, data);
        app.on_after_event(e, data);
    }

    EVENT(on_group_request, const cq::GroupRequestEvent &e) {
        json data = e;
        app.on_before_event(e, data);
        app.on_request_event(e, data);
        app.on_after_event(e, data);
    }
} // namespace cqhttp
Beispiel #13
0
 EVENT(on_group_request, const cq::GroupRequestEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_request_event(e, data);
     app.on_after_event(e, data);
 }
int main(int argc, const char *arg[]) {
	
	std::string modelname = "../../media/models/primitive/cube.obj";

	if (argc > 1) {
		std::string model(arg[1]);
		if (model == "corsair") {
			modelname = "../../media/models/aircraft/f4u-corsair/f4u-no-propeller.obj";
		}
		else if (model == "p47") {
			modelname = "../../media/models/aircraft/p47-thunderbolt/p47.obj";
		}
		else if (model == "ki-84" || model == "kate") {
			modelname = "../../media/models/aircraft/ki-84/ki84-no-propeller.obj";
		}
		else if (model == "p40" || model == "warhawk") {
			modelname = "../../media/models/aircraft/p40-warkhawk/P40.obj";
		}
		else if (model == "p38" || model == "lightning") {
			modelname = "../../media/models/aircraft/p38-lightning/P38.obj";
		}
		else if (model == "uboat" || model == "U99") {
			modelname = "../../media/models/marine/uboat-u99/U99.obj";
		}
		else if (model == "cube") {
			modelname = "../../media/models/primitive/cube.obj";
		}
		else if (model == "trex" || model == "t-rex") {
			modelname = "../../media/models/objects/absurd/t-rex/t-rex.obj";
		}
		else if (model == "path" && argc > 2) {
			modelname = arg[2];
		}
	}

	Log::initialize("RenderRigidModel.log", Log::All);
	LogReport() << "GLFW version: " << glfwGetVersionString();
	LogReport() << "Rendering model '" << modelname << "'.";

	std::cout << "Rendering model '" << modelname << "'." << std::endl;

  GLFWwindow* window;
  glfwSetErrorCallback(error_callback);

  if (!glfwInit()) {
		exit(EXIT_FAILURE);
	}
  window = glfwCreateWindow(800, 800, "Render Rigid Body", NULL, NULL);
  if (!window) {
		glfwTerminate();
		exit(EXIT_FAILURE);
  }

  glfwMakeContextCurrent(window);
  glfwSetKeyCallback(window, key_callback);
		
	int width, height;
	glfwGetFramebufferSize(window, &width, &height);
	glViewport(0, 0, width, height);

	try {
		if (!application.initialize(modelname)) {
			return 0;
		}
	}
	catch (std::runtime_error &e) {
		LogError() << e.what();
		std::cerr << e.what() << std::endl;
		return -1;
	}

	try {
		while (!glfwWindowShouldClose(window)) {
			application.update();
			application.render();
			glfwSwapBuffers(window);
			glfwPollEvents();
		}
		glfwDestroyWindow(window);
		glfwTerminate();
		exit(EXIT_SUCCESS);
	}
	catch (std::runtime_error &e) {
		LogError() << e.what();
		std::cerr << e.what() << std::endl;
	}

	return 0;
}
Beispiel #15
0
bool ApplicationList::LoadSettings()
{
    QSettings settings;
    QStringList names = settings.value(SETTINGS_APPLICATION_NAMES, QStringList()).toStringList();
    QStringList paths = settings.value(SETTINGS_APPLICATION_PATHS, QStringList()).toStringList();
    QStringList params = settings.value(SETTINGS_APPLICATION_PARAMS, QStringList()).toStringList();
    int defapp = settings.value(SETTINGS_APPLICATION_DEFAULT, -1).toInt();

    // Params will be empty first time starting with the new setting.
    // Return false and inform user about problem with application settings.
    bool succeeded = true;
    if (!names.empty() && !paths.empty() && params.empty()) {
        for (int i = 0; i < paths.length(); i++)
            params << "";
        succeeded = false;
    }

    if (names.empty() && paths.empty() && params.empty()) {
        do {
            // use as default for gnome environments
            if (QFileInfo("/usr/bin/gedit").isExecutable()) {
                Application app;
                app.setName("gedit");
                app.setPath("/usr/bin/gedit");
                app.setParameters("+(line) (file)");
                AddApplication(app);
                defapp = 0;
                break;
            }
            // use as default for kde environments
            if (QFileInfo("/usr/bin/kate").isExecutable()) {
                Application app;
                app.setName("kate");
                app.setPath("/usr/bin/kate");
                app.setParameters("-l(line) (file)");
                AddApplication(app);
                defapp = 0;
                break;
            }
            if (FindDefaultWindowsEditor()) {
                defapp = 0;
                break;
            }
        } while (0);
    }

    if (names.size() > 0 && (names.size() == paths.size())) {
        for (int i = 0; i < names.size(); i++) {
            const Application app(names[i], paths[i], params[i]);
            AddApplication(app);
        }

        if (defapp == -1)
            mDefaultApplicationIndex = 0;
        else if (defapp < names.size())
            mDefaultApplicationIndex = defapp;
        else
            mDefaultApplicationIndex = 0;
    }
    return succeeded;
}
CommandHandler::CommandHandler(Application& app) : mApp(app)
{
    if (mApp.getConfig().HTTP_PORT)
    {
        std::string ipStr;
        if (mApp.getConfig().PUBLIC_HTTP_PORT)
        {
            ipStr = "0.0.0.0";
        }
        else
        {
            ipStr = "127.0.0.1";
        }
        LOG(INFO) << "Listening on " << ipStr << ":"
                  << mApp.getConfig().HTTP_PORT << " for HTTP requests";

        int httpMaxClient = mApp.getConfig().HTTP_MAX_CLIENT;

        mServer = stellar::make_unique<http::server::server>(
            app.getClock().getIOService(), ipStr, mApp.getConfig().HTTP_PORT, httpMaxClient);
    }
    else
    {
        mServer = stellar::make_unique<http::server::server>(
            app.getClock().getIOService());
    }

    mServer->add404(std::bind(&CommandHandler::fileNotFound, this, _1, _2));

    mServer->addRoute("catchup",
                      std::bind(&CommandHandler::catchup, this, _1, _2));
    mServer->addRoute("checkdb",
                      std::bind(&CommandHandler::checkdb, this, _1, _2));
    mServer->addRoute("checkpoint",
                      std::bind(&CommandHandler::checkpoint, this, _1, _2));
    mServer->addRoute("connect",
                      std::bind(&CommandHandler::connect, this, _1, _2));
    mServer->addRoute("dropcursor",
                      std::bind(&CommandHandler::dropcursor, this, _1, _2));
    mServer->addRoute("generateload",
                      std::bind(&CommandHandler::generateLoad, this, _1, _2));
    mServer->addRoute("info", std::bind(&CommandHandler::info, this, _1, _2));
    mServer->addRoute("ll", std::bind(&CommandHandler::ll, this, _1, _2));
    mServer->addRoute("logrotate",
                      std::bind(&CommandHandler::logRotate, this, _1, _2));
    mServer->addRoute("maintenance",
                      std::bind(&CommandHandler::maintenance, this, _1, _2));
    mServer->addRoute("manualclose",
                      std::bind(&CommandHandler::manualClose, this, _1, _2));
    mServer->addRoute("metrics",
                      std::bind(&CommandHandler::metrics, this, _1, _2));
    mServer->addRoute("peers", std::bind(&CommandHandler::peers, this, _1, _2));
    mServer->addRoute("quorum",
                      std::bind(&CommandHandler::quorum, this, _1, _2));
    mServer->addRoute("setcursor",
                      std::bind(&CommandHandler::setcursor, this, _1, _2));
    mServer->addRoute("scp", std::bind(&CommandHandler::scpInfo, this, _1, _2));
    mServer->addRoute("testacc",
                      std::bind(&CommandHandler::testAcc, this, _1, _2));
    mServer->addRoute("testtx",
                      std::bind(&CommandHandler::testTx, this, _1, _2));
    mServer->addRoute("tx", std::bind(&CommandHandler::tx, this, _1, _2));
}
Beispiel #17
0
int main()
{
	Application theApp;
	return theApp.Run();
}
Beispiel #18
0
 EVENT(on_group_upload, const cq::GroupUploadEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_notice_event(e, data);
     app.on_after_event(e, data);
 }
Beispiel #19
0
inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* outputRight) {

    NodeList* nodeList = NodeList::getInstance();
    Application* interface = Application::getInstance();
    Avatar* interfaceAvatar = interface->getAvatar();

    memset(outputLeft, 0, PACKET_LENGTH_BYTES_PER_CHANNEL);
    memset(outputRight, 0, PACKET_LENGTH_BYTES_PER_CHANNEL);

    // Add Procedural effects to input samples
    addProceduralSounds(inputLeft, outputLeft, outputRight, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);
    
    if (nodeList && inputLeft) {
        
        //  Measure the loudness of the signal from the microphone and store in audio object
        float loudness = 0;
        for (int i = 0; i < BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) {
            loudness += abs(inputLeft[i]);
        }
        
        loudness /= BUFFER_LENGTH_SAMPLES_PER_CHANNEL;
        _lastInputLoudness = loudness;
        
        // add input (@microphone) data to the scope
        _scope->addSamples(0, inputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);

        Node* audioMixer = nodeList->soloNodeOfType(NODE_TYPE_AUDIO_MIXER);
        
        if (audioMixer) {
            audioMixer->lock();
            sockaddr_in audioSocket = *(sockaddr_in*) audioMixer->getActiveSocket();
            audioMixer->unlock();
            
            glm::vec3 headPosition = interfaceAvatar->getHeadJointPosition();
            glm::quat headOrientation = interfaceAvatar->getHead().getOrientation();
            
            int numBytesPacketHeader = numBytesForPacketHeader((unsigned char*) &PACKET_TYPE_MICROPHONE_AUDIO_NO_ECHO);
            int leadingBytes = numBytesPacketHeader + sizeof(headPosition) + sizeof(headOrientation);
            
            // we need the amount of bytes in the buffer + 1 for type
            // + 12 for 3 floats for position + float for bearing + 1 attenuation byte
            unsigned char dataPacket[MAX_PACKET_SIZE];
            
            PACKET_TYPE packetType = Menu::getInstance()->isOptionChecked(MenuOption::EchoAudio)
                ? PACKET_TYPE_MICROPHONE_AUDIO_WITH_ECHO
                : PACKET_TYPE_MICROPHONE_AUDIO_NO_ECHO;
            
            unsigned char* currentPacketPtr = dataPacket + populateTypeAndVersion(dataPacket, packetType);
            
            // pack Source Data
            uint16_t ownerID = NodeList::getInstance()->getOwnerID();
            memcpy(currentPacketPtr, &ownerID, sizeof(ownerID));
            currentPacketPtr += (sizeof(ownerID));
            leadingBytes += (sizeof(ownerID));
            
            // pack Listen Mode Data
            memcpy(currentPacketPtr, &_listenMode, sizeof(_listenMode));
            currentPacketPtr += (sizeof(_listenMode));
            leadingBytes += (sizeof(_listenMode));
    
            if (_listenMode == AudioRingBuffer::OMNI_DIRECTIONAL_POINT) {
                memcpy(currentPacketPtr, &_listenRadius, sizeof(_listenRadius));
                currentPacketPtr += (sizeof(_listenRadius));
                leadingBytes += (sizeof(_listenRadius));
            } else if (_listenMode == AudioRingBuffer::SELECTED_SOURCES) {
                int listenSourceCount = _listenSources.size();
                memcpy(currentPacketPtr, &listenSourceCount, sizeof(listenSourceCount));
                currentPacketPtr += (sizeof(listenSourceCount));
                leadingBytes += (sizeof(listenSourceCount));
                for (int i = 0; i < listenSourceCount; i++) {
                    memcpy(currentPacketPtr, &_listenSources[i], sizeof(_listenSources[i]));
                    currentPacketPtr += sizeof(_listenSources[i]);
                    leadingBytes += sizeof(_listenSources[i]);
                }
            }
            
            // memcpy the three float positions
            memcpy(currentPacketPtr, &headPosition, sizeof(headPosition));
            currentPacketPtr += (sizeof(headPosition));
            
            // memcpy our orientation
            memcpy(currentPacketPtr, &headOrientation, sizeof(headOrientation));
            currentPacketPtr += sizeof(headOrientation);
            
            // copy the audio data to the last BUFFER_LENGTH_BYTES bytes of the data packet
            memcpy(currentPacketPtr, inputLeft, BUFFER_LENGTH_BYTES_PER_CHANNEL);
            
            nodeList->getNodeSocket()->send((sockaddr*) &audioSocket,
                                            dataPacket,
                                            BUFFER_LENGTH_BYTES_PER_CHANNEL + leadingBytes);

            interface->getBandwidthMeter()->outputStream(BandwidthMeter::AUDIO).updateValue(BUFFER_LENGTH_BYTES_PER_CHANNEL
                                                                                            + leadingBytes);
            
        }
    }
        
    AudioRingBuffer* ringBuffer = &_ringBuffer;
    
    // if there is anything in the ring buffer, decide what to do:
    
    if (ringBuffer->getEndOfLastWrite()) {
        if (!ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() <
            (PACKET_LENGTH_SAMPLES + _jitterBufferSamples * (ringBuffer->isStereo() ? 2 : 1))) {
            //
            //  If not enough audio has arrived to start playback, keep waiting
            //
#ifdef SHOW_AUDIO_DEBUG
            qDebug("%i,%i,%i,%i\n",
                     _packetsReceivedThisPlayback,
                     ringBuffer->diffLastWriteNextOutput(),
                     PACKET_LENGTH_SAMPLES,
                     _jitterBufferSamples);
#endif
        } else if (ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() == 0) {
            //
            //  If we have started and now have run out of audio to send to the audio device, 
            //  this means we've starved and should restart.  
            //  
            ringBuffer->setStarted(false);
            
            _numStarves++;
            _packetsReceivedThisPlayback = 0;
            _wasStarved = 10;          //   Frames for which to render the indication that the system was starved.
#ifdef SHOW_AUDIO_DEBUG
            qDebug("Starved, remaining samples = %d\n",
                     ringBuffer->diffLastWriteNextOutput());
#endif

        } else {
            //
            //  We are either already playing back, or we have enough audio to start playing back.
            // 
            if (!ringBuffer->isStarted()) {
                ringBuffer->setStarted(true);
#ifdef SHOW_AUDIO_DEBUG
                qDebug("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d \n",
                         (usecTimestampNow() - usecTimestamp(&_firstPacketReceivedTime))/1000.0,
                         _jitterBufferSamples,
                         _packetsReceivedThisPlayback);
#endif
            }

            //
            // play whatever we have in the audio buffer
            //
            // if we haven't fired off the flange effect, check if we should
            // TODO: lastMeasuredHeadYaw is now relative to body - check if this still works.
            
            int lastYawMeasured = fabsf(interfaceAvatar->getHeadYawRate());
            
            if (!_samplesLeftForFlange && lastYawMeasured > MIN_FLANGE_EFFECT_THRESHOLD) {
                // we should flange for one second
                if ((_lastYawMeasuredMaximum = std::max(_lastYawMeasuredMaximum, lastYawMeasured)) != lastYawMeasured) {
                    _lastYawMeasuredMaximum = std::min(_lastYawMeasuredMaximum, MIN_FLANGE_EFFECT_THRESHOLD);
                    
                    _samplesLeftForFlange = SAMPLE_RATE;
                    
                    _flangeIntensity = MIN_FLANGE_INTENSITY +
                        ((_lastYawMeasuredMaximum - MIN_FLANGE_EFFECT_THRESHOLD) /
                         (float)(MAX_FLANGE_EFFECT_THRESHOLD - MIN_FLANGE_EFFECT_THRESHOLD)) *
                        (1 - MIN_FLANGE_INTENSITY);
                    
                    _flangeRate = FLANGE_BASE_RATE * _flangeIntensity;
                    _flangeWeight = MAX_FLANGE_SAMPLE_WEIGHT * _flangeIntensity;
                }
            }
            
            for (int s = 0; s < PACKET_LENGTH_SAMPLES_PER_CHANNEL; s++) {
                
                int leftSample = ringBuffer->getNextOutput()[s];
                int rightSample = ringBuffer->getNextOutput()[s + PACKET_LENGTH_SAMPLES_PER_CHANNEL];
                
                if (_samplesLeftForFlange > 0) {
                    float exponent = (SAMPLE_RATE - _samplesLeftForFlange - (SAMPLE_RATE / _flangeRate)) /
                        (SAMPLE_RATE / _flangeRate);
                    int sampleFlangeDelay = (SAMPLE_RATE / (1000 * _flangeIntensity)) * powf(2, exponent);
                    
                    if (_samplesLeftForFlange != SAMPLE_RATE || s >= (SAMPLE_RATE / 2000)) {
                        // we have a delayed sample to add to this sample
                        
                        int16_t *flangeFrame = ringBuffer->getNextOutput();
                        int flangeIndex = s - sampleFlangeDelay;
                        
                        if (flangeIndex < 0) {
                            // we need to grab the flange sample from earlier in the buffer
                            flangeFrame = ringBuffer->getNextOutput() != ringBuffer->getBuffer()
                            ? ringBuffer->getNextOutput() - PACKET_LENGTH_SAMPLES
                            : ringBuffer->getNextOutput() + RING_BUFFER_LENGTH_SAMPLES - PACKET_LENGTH_SAMPLES;
                            
                            flangeIndex = PACKET_LENGTH_SAMPLES_PER_CHANNEL + (s - sampleFlangeDelay);
                        }
                        
                        int16_t leftFlangeSample = flangeFrame[flangeIndex];
                        int16_t rightFlangeSample = flangeFrame[flangeIndex + PACKET_LENGTH_SAMPLES_PER_CHANNEL];
                        
                        leftSample = (1 - _flangeWeight) * leftSample + (_flangeWeight * leftFlangeSample);
                        rightSample = (1 - _flangeWeight) * rightSample + (_flangeWeight * rightFlangeSample);
                        
                        _samplesLeftForFlange--;
                        
                        if (_samplesLeftForFlange == 0) {
                            _lastYawMeasuredMaximum = 0;
                        }
                    }
                }
#ifndef TEST_AUDIO_LOOPBACK
                outputLeft[s] += leftSample;
                outputRight[s] += rightSample;
#else 
                outputLeft[s] += inputLeft[s];
                outputRight[s] += inputLeft[s];
#endif
            }
            ringBuffer->setNextOutput(ringBuffer->getNextOutput() + PACKET_LENGTH_SAMPLES);
            
            if (ringBuffer->getNextOutput() == ringBuffer->getBuffer() + RING_BUFFER_LENGTH_SAMPLES) {
                ringBuffer->setNextOutput(ringBuffer->getBuffer());
            }
        }
    }

    eventuallySendRecvPing(inputLeft, outputLeft, outputRight);


    // add output (@speakers) data just written to the scope
    _scope->addSamples(1, outputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);
    _scope->addSamples(2, outputRight, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);

    gettimeofday(&_lastCallbackTime, NULL);
}
Beispiel #20
0
 EVENT(on_group_admin, const cq::GroupAdminEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_notice_event(e, data);
     app.on_after_event(e, data);
 }
void OctreePacketProcessor::processPacket(const SharedNodePointer& sendingNode, const QByteArray& packet) {
    PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings),
                            "OctreePacketProcessor::processPacket()");
    
    QByteArray mutablePacket = packet;

    const int WAY_BEHIND = 300;

    if (packetsToProcessCount() > WAY_BEHIND && Application::getInstance()->getLogger()->extraDebugging()) {
        qDebug("OctreePacketProcessor::processPacket() packets to process=%d", packetsToProcessCount());
    }
    int messageLength = mutablePacket.size();

    Application* app = Application::getInstance();
    bool wasStatsPacket = false;


    PacketType voxelPacketType = packetTypeForPacket(mutablePacket);
    
    // note: PacketType_OCTREE_STATS can have PacketType_VOXEL_DATA
    // immediately following them inside the same packet. So, we process the PacketType_OCTREE_STATS first
    // then process any remaining bytes as if it was another packet
    if (voxelPacketType == PacketTypeOctreeStats) {
        int statsMessageLength = app->parseOctreeStats(mutablePacket, sendingNode);
        wasStatsPacket = true;
        if (messageLength > statsMessageLength) {
            mutablePacket = mutablePacket.mid(statsMessageLength);
            
            // TODO: this does not look correct, the goal is to test the packet version for the piggyback, but
            //       this is testing the version and hash of the original packet
            if (!DependencyManager::get<NodeList>()->packetVersionAndHashMatch(packet)) {
                return; // bail since piggyback data doesn't match our versioning
            }
        } else {
            // Note... stats packets don't have sequence numbers, so we don't want to send those to trackIncomingVoxelPacket()
            return; // bail since no piggyback data
        }
    } // fall through to piggyback message
    
    voxelPacketType = packetTypeForPacket(mutablePacket);
    PacketVersion packetVersion = mutablePacket[1];
    PacketVersion expectedVersion = versionForPacketType(voxelPacketType);
    
    // check version of piggyback packet against expected version
    if (packetVersion != expectedVersion) {
        static QMultiMap<QUuid, PacketType> versionDebugSuppressMap;
        
        QUuid senderUUID = uuidFromPacketHeader(packet);
        if (!versionDebugSuppressMap.contains(senderUUID, voxelPacketType)) {
            qDebug() << "Packet version mismatch on" << voxelPacketType << "- Sender"
            << senderUUID << "sent" << (int)packetVersion << "but"
            << (int)expectedVersion << "expected.";
            
            emit packetVersionMismatch();

            versionDebugSuppressMap.insert(senderUUID, voxelPacketType);
        }
        return; // bail since piggyback version doesn't match
    }
    
    app->trackIncomingOctreePacket(mutablePacket, sendingNode, wasStatsPacket);

    if (sendingNode) {

        switch(voxelPacketType) {
            case PacketTypeEntityErase: {
                if (DependencyManager::get<SceneScriptingInterface>()->shouldRenderEntities()) {
                    app->_entities.processEraseMessage(mutablePacket, sendingNode);
                }
            } break;

            case PacketTypeEntityData: {
                if (DependencyManager::get<SceneScriptingInterface>()->shouldRenderEntities()) {
                    app->_entities.processDatagram(mutablePacket, sendingNode);
                }
            } break;

            case PacketTypeEnvironmentData: {
                app->_environment.parseData(*sendingNode->getActiveSocket(), mutablePacket);
            } break;

            default: {
                // nothing to do
            } break;
        }
    }
}
Beispiel #22
0
 EVENT(on_group_member_increase, const cq::GroupMemberIncreaseEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_notice_event(e, data);
     app.on_after_event(e, data);
 }
Beispiel #23
0
void output_result(Recog *recog, void *app_)
{
  Application *app = (Application *)app_;
  int i, j;
  int len;
  WORD_INFO *winfo;
  WORD_ID *seq;
  int seqnum;
  int n;
  Sentence *s;
  RecogProcess *r;
  HMM_Logical *p;
  SentenceAlign *align;
  boolean multi;

  if (recog->process_list->next != NULL) 
    multi = TRUE;
  else 
    multi = FALSE;

  /* all recognition results are stored at each recognition process
     instance */
  for(r=recog->process_list;r;r=r->next) {

    /* skip the process if the process is not alive */
    if (! r->live) continue;

    /* result are in r->result.  See recog.h for details */
    
    /* check result status */
    if (r->result.status < 0) {      /* no results obtained */
#if 0
      /* outout message according to the status code */
      switch(r->result.status) {
      case J_RESULT_STATUS_REJECT_POWER:
	fprintf(stderr, "<input rejected by power>\n");
	break;
      case J_RESULT_STATUS_TERMINATE:
	fprintf(stderr, "<input teminated by request>\n");
	break;
      case J_RESULT_STATUS_ONLY_SILENCE:
	fprintf(stderr, "<input rejected by decoder (silence input result)>\n");
	break;
      case J_RESULT_STATUS_REJECT_GMM:
	fprintf(stderr, "<input rejected by GMM>\n");
	break;
      case J_RESULT_STATUS_REJECT_SHORT:
	fprintf(stderr, "<input rejected by short input>\n");
	break;
      case J_RESULT_STATUS_FAIL:
	fprintf(stderr, "<search failed>\n");
	break;
      }
      /* continue to next process instance */
#endif
      continue;
    }
#if 0
    fprintf(stderr, "\n");
    fprintf(stderr, "search id:%d name:%s\n", r->config->id, r->config->name);
#endif
    /* output results for all the obtained sentences */
    winfo = r->lm->winfo;

    for(n = 0; n < r->result.sentnum; n++) { /* for all sentences */

      s = &(r->result.sent[n]);
      seq = s->word;
      seqnum = s->word_num;

#if 0
      /* output word sequence like Julius */
      fprintf(stderr, "sentence%d:", n+1);
      for(i=0;i<seqnum;i++) 
	fprintf(stderr, " %s", to_utf(winfo->woutput[seq[i]]));
      fprintf(stderr, "\n");
#endif
      if (n == 0 and seqnum == 3) {
	app->onSpeechRecognized(to_utf(winfo->woutput[seq[1]]));
      }
#if 0
      /* LM entry sequence */
      fprintf(stderr, "wseq%d:", n+1);
      for(i=0;i<seqnum;i++) 
	fprintf(stderr, " %s", to_utf(winfo->wname[seq[i]]));
      fprintf(stderr, "\n");
      /* phoneme sequence */
      fprintf(stderr, "phseq%d:", n+1);
      put_hypo_phoneme(seq, seqnum, winfo);
      //fprintf(stderr, "\n");
      /* confidence scores */
      fprintf(stderr, "cmscore%d:", n+1);
      for (i=0;i<seqnum; i++) 
	fprintf(stderr, " %5.3f", s->confidence[i]);
      fprintf(stderr, "\n");
      /* AM and LM scores */
      fprintf(stderr, "score%d: %f", n+1, s->score);
      if (r->lmtype == LM_PROB) { /* if this process uses N-gram */
	fprintf(stderr, " (AM: %f  LM: %f)", s->score_am, s->score_lm);
      }
      fprintf(stderr, "\n");
      if (r->lmtype == LM_DFA) { /* if this process uses DFA grammar */
	/* output which grammar the hypothesis belongs to
	   when using multiple grammars */
	if (multigram_get_all_num(r->lm) > 1) {
	  fprintf(stderr, "grammar%d: %d\n", n+1, s->gram_id);
	}
      }
#endif
    }
  }
#if 0
  fflush(stderr);
#endif
}
Beispiel #24
0
 EVENT(on_friend_add, const cq::FriendAddEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_notice_event(e, data);
     app.on_after_event(e, data);
 }
Beispiel #25
0
void RunTest( Application& application )
{
  HelloWorldController test( application );

  application.MainLoop();
}
Beispiel #26
0
 EVENT(on_friend_request, const cq::FriendRequestEvent &e) {
     json data = e;
     app.on_before_event(e, data);
     app.on_request_event(e, data);
     app.on_after_event(e, data);
 }
Beispiel #27
0
int main()
{
    Application app;
    return app.Execute();
}
bool
CreateAccountOpFrame::doApply(Application& app, LedgerDelta& delta,
                              LedgerManager& ledgerManager)
{
    AccountFrame::pointer destAccount;

    Database& db = ledgerManager.getDatabase();

    destAccount =
        AccountFrame::loadAccount(delta, mCreateAccount.destination, db);
    if (!destAccount)
    {
        if (mCreateAccount.startingBalance < ledgerManager.getMinBalance(0))
        { // not over the minBalance to make an account
            app.getMetrics()
                .NewMeter({"op-create-account", "failure", "low-reserve"},
                          "operation")
                .Mark();
            innerResult().code(CREATE_ACCOUNT_LOW_RESERVE);
            return false;
        }
        else
        {
            int64_t minBalance =
                mSourceAccount->getMinimumBalance(ledgerManager);

            if ((mSourceAccount->getAccount().balance - minBalance) <
                mCreateAccount.startingBalance)
            { // they don't have enough to send
                app.getMetrics()
                    .NewMeter({"op-create-account", "failure", "underfunded"},
                              "operation")
                    .Mark();
                innerResult().code(CREATE_ACCOUNT_UNDERFUNDED);
                return false;
            }

            auto ok =
                mSourceAccount->addBalance(-mCreateAccount.startingBalance);
            assert(ok);

            mSourceAccount->storeChange(delta, db);

            destAccount = make_shared<AccountFrame>(mCreateAccount.destination);
            destAccount->getAccount().seqNum =
                delta.getHeaderFrame().getStartingSequenceNumber();
            destAccount->getAccount().balance = mCreateAccount.startingBalance;

            destAccount->storeAdd(delta, db);

            app.getMetrics()
                .NewMeter({"op-create-account", "success", "apply"},
                          "operation")
                .Mark();
            innerResult().code(CREATE_ACCOUNT_SUCCESS);
            return true;
        }
    }
    else
    {
        app.getMetrics()
            .NewMeter({"op-create-account", "failure", "already-exist"},
                      "operation")
            .Mark();
        innerResult().code(CREATE_ACCOUNT_ALREADY_EXIST);
        return false;
    }
}
Beispiel #29
0
DBTimeExcluder::DBTimeExcluder(Application& app)
    : mApp(app)
    , mStartQueryTime(app.getDatabase().totalQueryTime())
    , mStartTotalTime(app.getClock().now())
{
}
Beispiel #30
0
bool ConnectionManager::reuseExistingConnection(ConnectionSettings& settings, bool interactive)
{
    Server* dupe = 0;
    ConnectionDupe dupeType;
    bool doReuse = true;

    Application* konvApp = static_cast<Application *>(kapp);
    MainWindow* mainWindow = konvApp->getMainWindow();

    QMap<int, Server*>::ConstIterator it;

    for (it = m_connectionList.constBegin(); it != m_connectionList.constEnd(); ++it)
    {
        if (it.value()->getServerGroup() && settings.serverGroup()
            && it.value()->getServerGroup() == settings.serverGroup())
        {
            dupe = it.value();
            dupeType = SameServerGroup;

            break;
        }
    }

    if (!dupe)
    {
        for (it = m_connectionList.constBegin(); it != m_connectionList.constEnd(); ++it)
        {
            if (it.value()->getConnectionSettings().server() == settings.server())
            {
                dupe = it.value();
                dupeType = SameServer;

                break;
            }
        }
    }

    if (dupe && interactive)
    {
        int result = KMessageBox::warningContinueCancel(
            mainWindow,
            i18n("You are already connected to %1. Do you want to open another connection?", dupe->getDisplayName()),
            i18n("Already connected to %1", dupe->getDisplayName()),
            KGuiItem(i18n("Create connection")),
            KStandardGuiItem::cancel(),
            QString("ReuseExistingConnection"));

        if (result == KMessageBox::Continue) doReuse = false;
    }

    if (dupe && doReuse)
    {
        if (interactive && dupeType == SameServerGroup
            && !(dupe->getConnectionSettings().server() == settings.server()))
        {
            int result = KMessageBox::warningContinueCancel(
                mainWindow,
                i18n("You are presently connected to %1 via '%2' (port <numid>%3</numid>). Do you want to switch to '%4' (port <numid>%5</numid>) instead?",
                    dupe->getDisplayName(),
                    dupe->getServerName(),
                    dupe->getPort(),
                    settings.server().host(),
                    settings.server().port()),
                i18n("Already connected to %1", dupe->getDisplayName()),
                KGuiItem(i18n("Switch Server")),
                KStandardGuiItem::cancel(),
                "ReconnectWithDifferentServer");

            if (result == KMessageBox::Continue)
            {
                dupe->disconnectServer();

                dupe->setConnectionSettings(settings);
            }
        }

        if (!dupe->isConnected())
        {
            if (!settings.oneShotChannelList().isEmpty())
                dupe->updateAutoJoin(settings.oneShotChannelList());

            if (!dupe->isConnecting())
                dupe->reconnectServer();
        }
        else
        {
            if (!settings.oneShotChannelList().isEmpty())
            {
                Konversation::ChannelList::ConstIterator it = settings.oneShotChannelList().constBegin();
                Konversation::ChannelList::ConstIterator itend = settings.oneShotChannelList().constEnd();

                for ( ; it != itend; ++it )
                {
                    dupe->sendJoinCommand((*it).name(), (*it).password());
                }
                settings.clearOneShotChannelList();
            }
        }
    }

    return (dupe && doReuse);
}