Example #1
0
int main(int argc, char **argv)
{
	//See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions
	/** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory
		on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to
		ensure that resource sharing between contexts stays functional as all internal contexts are created
		using the correct version and profile.
	**/
	{
		QSurfaceFormat format = QSurfaceFormat::defaultFormat();
		format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
		format.setStencilBufferSize(0);
#ifdef CC_GL_WINDOW_USE_QWINDOW
		format.setStereo(true);
#endif
#ifdef Q_OS_MAC
		format.setStereo(false);
		format.setVersion( 2, 1 );
		format.setProfile( QSurfaceFormat::CoreProfile );
#endif
#ifdef QT_DEBUG
		format.setOption(QSurfaceFormat::DebugContext, true);
#endif
		QSurfaceFormat::setDefaultFormat(format);
	}

	//The 'AA_ShareOpenGLContexts' attribute must be defined BEFORE the creation of the Q(Gui)Application
	//DGM: this is mandatory to enable exclusive full screen for ccGLWidget (at least on Windows)
	QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);

	//QT initialiation
	qccApplication app(argc, argv);

	//Locale management
	{
		//Force 'english' locale so as to get a consistent behavior everywhere
		QLocale locale = QLocale(QLocale::English);
		locale.setNumberOptions(QLocale::c().numberOptions());
		QLocale::setDefault(locale);

#ifdef Q_OS_UNIX
		//We reset the numeric locale for POSIX functions
		//See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings
		setlocale(LC_NUMERIC, "C");
#endif
	}

#ifdef USE_VLD
	VLDEnable();
#endif

	QDir  workingDir = QCoreApplication::applicationDirPath();
	
#ifdef Q_OS_MAC
	// This makes sure that our "working directory" is not within the application bundle	
	if ( workingDir.dirName() == "MacOS" )
	{
		workingDir.cdUp();
		workingDir.cdUp();
		workingDir.cdUp();
	}
#endif

	//store the log message until a valid logging instance is registered
	ccLog::EnableMessageBackup(true);
	
	//restore some global parameters
	{
		QSettings settings;
		settings.beginGroup(ccPS::GlobalShift());
		double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble();
		double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble();
		settings.endGroup();

		ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0));
		
		ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord);
		ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag);
	}

	//Command line mode?
	bool commandLine = (argc > 1 && argv[1][0] == '-');
	
	//specific commands
	int lastArgumentIndex = 1;
	QTranslator translator;
	if (commandLine)
	{
		//translation file selection
		if (QString(argv[lastArgumentIndex]).toUpper() == "-LANG")
		{
			QString langFilename = QString(argv[2]);

			//Load translation file
			if (translator.load(langFilename, QCoreApplication::applicationDirPath()))
			{
				qApp->installTranslator(&translator);
			}
			else
			{
				QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename));
			}
			commandLine = false;
			lastArgumentIndex += 2;
		}
	}

	//splash screen
	QScopedPointer<QSplashScreen> splash(0);
	QTimer splashTimer;

	//standard mode
	if (!commandLine)
	{
		if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0)
		{
			QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!");
			return EXIT_FAILURE;
		}

		//splash screen
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash.reset(new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint));
		splash->show();
		QApplication::processEvents();
	}

	//global structures initialization
	FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!)
	ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization
	ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization

	//load the plugins
	tPluginInfoList plugins;
	QStringList dirFilters;
	QStringList pluginPaths;
	{
		QString appPath = QCoreApplication::applicationDirPath();

#if defined(Q_OS_MAC)
		dirFilters << "*.dylib";

		// plugins are in the bundle
		appPath.remove("MacOS");

		pluginPaths += (appPath + "PlugIns/ccPlugins");
#if defined(CC_MAC_DEV_PATHS)
		// used for development only - this is the path where the plugins are built
		// this avoids having to install into the application bundle when developing
		pluginPaths += (appPath + "../../../ccPlugins");
#endif
#elif defined(Q_OS_WIN)
		dirFilters << "*.dll";

		//plugins are in bin/plugins
		pluginPaths << (appPath + "/plugins");
#elif defined(Q_OS_LINUX)
		dirFilters << "*.so";

		// Plugins are relative to the bin directory where the executable is found
		QDir  binDir(appPath);

		if (binDir.dirName() == "bin")
		{
			binDir.cdUp();

			pluginPaths << (binDir.absolutePath() + "/lib/cloudcompare/plugins");
		}
		else
		{
			// Choose a reasonable default to look in
			pluginPaths << "/usr/lib/cloudcompare/plugins";
		}
#else
		#warning Need to specify the plugin path for this OS.
#endif

#ifdef Q_OS_MAC
		// Add any app data paths
		// Plugins in these directories take precendence over the included ones
		QStringList appDataPaths = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);

		for (const QString &appDataPath : appDataPaths)
		{
			pluginPaths << (appDataPath + "/plugins");
		}
#endif
	}

	ccPlugins::LoadPlugins(plugins, pluginPaths, dirFilters);
	
	int result = 0;

	//command line mode
	if (commandLine)
	{
		//command line processing (no GUI)
		result = ccCommandLineParser::Parse(argc, argv, &plugins);
	}
	else
	{
		//main window init.
		MainWindow* mainWindow = MainWindow::TheInstance();
		if (!mainWindow)
		{
			QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!");
			return EXIT_FAILURE;
		}
		mainWindow->dispatchPlugins(plugins, pluginPaths);
		mainWindow->show();
		QApplication::processEvents();

		//show current Global Shift parameters in Console
		{
			ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2")
				.arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0)
				.arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0));
		}

		if (argc > lastArgumentIndex)
		{
			if (splash)
			{
				splash->close();
			}

			//any additional argument is assumed to be a filename --> we try to load it/them
			QStringList filenames;
			for (int i = lastArgumentIndex; i < argc; ++i)
			{
				QString arg(argv[i]);
				//special command: auto start a plugin
				if (arg.startsWith(":start-plugin:"))
				{
					QString pluginName = arg.mid(14);
					QString pluginNameUpper = pluginName.toUpper();
					//look for this plugin
					bool found = false;
					for (const tPluginInfo &plugin : plugins)
					{
						if (plugin.object->getName().replace(' ', '_').toUpper() == pluginNameUpper)
						{
							found = true;
							bool success = plugin.object->start();
							if (!success)
							{
								ccLog::Error(QString("Failed to start the plugin '%1'").arg(plugin.object->getName()));
							}
							break;
						}
					}

					if (!found)
					{
						ccLog::Error(QString("Couldn't find the plugin '%1'").arg(pluginName.replace('_', ' ')));
					}
				}
				else
				{
					filenames << arg;
				}
			}

			mainWindow->addToDB(filenames);
		}
		else if (splash)
		{
			//count-down to hide the timer (only effective once the application will have actually started!)
			QObject::connect(&splashTimer, &QTimer::timeout, [&]() { if (splash) splash->close(); QCoreApplication::processEvents(); splash.reset(); });
			splashTimer.setInterval(1000);
			splashTimer.start();
		}

		//change the default path to the application one (do this AFTER processing the command line)
		QDir::setCurrent(workingDir.absolutePath());

		//let's rock!
		try
		{
			result = app.exec();
		}
		catch (...)
		{
			QMessageBox::warning(0, "CC crashed!", "Hum, it seems that CC has crashed... Sorry about that :)");
		}

		//release the plugins
		for (tPluginInfo &plugin : plugins)
		{
			plugin.object->stop(); //just in case
			if (!plugin.qObject->parent())
			{
				delete plugin.object;
				plugin.object = 0;
				plugin.qObject = 0;
			}
		}
	}

	//release global structures
	MainWindow::DestroyInstance();
	FileIOFilter::UnregisterAll();

#ifdef CC_TRACK_ALIVE_SHARED_OBJECTS
	//for debug purposes
	unsigned alive = CCShareable::GetAliveCount();
	if (alive > 1)
	{
		printf("Error: some shared objects (%u) have not been released on program end!",alive);
		system("PAUSE");
	}
#endif

	return result;
}
Example #2
0
SerialConsole::SerialConsole(QWidget *parent) :
    QDockWidget(tr("Serial console"), parent)
{
	setObjectName("SerialConsole");

    extruder_temperature = 0.0;
    bed_temperature = 0.0;
    nb_processed_commands = 0;
    start_time.start();

    QWidget *widget = new QWidget;
    setWidget(widget);
    QVBoxLayout *layout = new QVBoxLayout;
    widget->setLayout(layout);

    QComboBox *serial_ports = new QComboBox;

	const QList<QSerialPortInfo> &available_ports = QSerialPortInfo::availablePorts();
	for(const QSerialPortInfo &port : available_ports)
    {
        serial_ports->addItem(QIcon::fromTheme("printer"), port.portName(), port.portName());
    }
    connect(serial_ports,SIGNAL(activated(QString)),this,SLOT(connectTo(QString)));

    QHBoxLayout *history_layout = new QHBoxLayout;
    scroll_bar = new QScrollBar(Qt::Vertical);
    scroll_bar->setMinimum(0);
    scroll_bar->setValue(0);
    history_layout->addWidget(history = new SimpleTextEdit);
	history->setMaxSize(10000);
    history_layout->addWidget(scroll_bar);
    connect(history,SIGNAL(scrollPositionChanged(int)),scroll_bar,SLOT(setValue(int)));
    connect(scroll_bar,SIGNAL(valueChanged(int)),history,SLOT(setScrollPosition(int)));
    connect(history,SIGNAL(maxScrollChanged(int)),this,SLOT(updateScrollBar(int)));

    layout->addWidget(serial_ports);
    layout->addLayout(history_layout);
    layout->addWidget(cmd = new QLineEdit);

    history->setFocusPolicy(Qt::NoFocus);
    cmd->setFocusPolicy(Qt::StrongFocus);

	rs232 = new QSerialPort(this);
	rs232->setBaudRate(115200);

    connect(rs232,SIGNAL(readyRead()),this,SLOT(readMessage()));
    connect(cmd,SIGNAL(returnPressed()),this,SLOT(sendMessage()));

    ack_timer = new QTimer(this);
    ack_timer->setSingleShot(true);
    ack_timer->setInterval(2000);
    connect(ack_timer,SIGNAL(timeout()),this,SLOT(kickAfterTimeout()));

    QTimer *timer = new QTimer(this);
    timer->setInterval(10000);
    timer->setSingleShot(false);
    connect(timer,SIGNAL(timeout()),this,SLOT(requestTemperature()));
    timer->start();

    ack_expected_before_sending_a_command = 0;
    b_paused = false;

    QSettings settings;
    settings.beginGroup("SerialConsole");
    const QString &serial_port = settings.value("serial_port", QString()).toString();
    settings.endGroup();

    int idx = 0;
	for(const QSerialPortInfo &port : available_ports)
        if (port.portName() == serial_port)
        {
            serial_ports->setCurrentIndex(idx);
            connectTo(serial_port);
            break;
        }
        else
            ++idx;
}
/*
 * This function works pretty much like routTcpMessage only that this one interpretes message from RFIDMonitor and don't verify packages size.
 * it only tries to interpret data just arrived.
 */
void RFIDMonitorDaemon::routeIpcMessage()
{
    QByteArray message = ipcConnection->readAll();
    json::NodeJSMessage nodeMessage;

    nodeMessage.read(QJsonDocument::fromJson(message).object());
    QString messageType(nodeMessage.type());

    if(messageType == "SYN"){

        m_restoreTimer.stop();
        ipcSendMessage(buildMessage(QJsonObject(), "ACK-SYN").toJson());
        qApp->processEvents();

        /* When the deskApp change some configuration the RFIDMonitor is restarted.
         * But, the RFIDMonitor starts with flag connection=false. And if the server is connected the RFIDMonitor don't know that yet.
         * To solve this, after 1 seconds a SYNC message is sent to RFIDMonitor to set true to connection flag.
         */
        if(isConnected)
        {
            QTimer *timer = new QTimer();
            timer->setSingleShot(true);
            timer->setInterval(1000);
            connect(timer, &QTimer::timeout, [=](){
                ipcSendMessage(buildMessage(QJsonObject(), "SYNC").toJson());
                timer->deleteLater();
            });
            timer->start();
        }

        m_configManager->restartNetwork();

    }else if (messageType == "READER-RESPONSE") {
        QJsonObject command(nodeMessage.jsonData());
        /*
         * When a 'reader response' message is received is because someone sent a 'reader command' message. So it needs to know who did it.
         * To perform this it uses a field called 'sender' that carry the name of who sent the 'command message'.
         * And based on that, it will respond to the server connection or to the deskApp connection.
         *
         * see reoutTcpMessage (messageType == "READER-COMMAND")
         */
        if(command.value("sender").toString() == "server")
            tcpSendMessage(m_tcpSocket, message);
        else
            tcpSendMessage(m_tcpAppSocket, message);

    }else if (messageType == "DATA"){
        /*
         * A Data message means that the RFIDMonitor is trying to sync some data into the server. So, it just send this message to the server.
         */
//        qDebug() <<  "DATA Message Received from Monitor\n";
//        qDebug() <<  QString(QJsonDocument(nodeMessage.jsonData()).toJson());
        // Only a node.js server receives DATA messages.
        tcpSendMessage(m_tcpSocket, message);

    }else if (messageType == "STOPPED"){
        qDebug() << "STOPPED";
        m_process.kill();
//        qDebug() << "Process Killed, PID: " << m_process.pid();
    }
    else if (messageType == "ACK-UNKNOWN") {
        QJsonDocument unknown(nodeMessage.jsonData());
        QJsonObject dataObj(unknown.object().value("unknownmessage").toObject());
        qDebug() <<  "The Monitor don't understand the message type: "
                        << dataObj.value("type").toString();
    }
    else{
        /* When receives a message that can't be interpreted like any type is an unknown message.
         * In this case an ACK-UNKNOWN message is built and sent to the connection that received this message
         */
        qDebug() <<  "UNKNOWN MESSAGE";

        QJsonObject unknownObj;
        unknownObj.insert("unknownmessage", QJsonDocument::fromJson(message).object());
        unknownObj.insert("errorinfo", QString("Unknown message received"));

        ipcSendMessage(buildMessage(unknownObj, "ACK-UNKNOWN").toJson());
    }
}
Example #4
0
void OpenRouteServiceRunner::retrieveRoute( const RouteRequest *route )
{
    if ( route->size() < 2 ) {
        return;
    }

    GeoDataCoordinates source = route->source();
    GeoDataCoordinates destination = route->destination();
    QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()["openrouteservice"];

    QUrlQuery queries;
    queries.addQueryItem("api_key", "ee0b8233adff52ce9fd6afc2a2859a28");

    QString unit = "KM";
    QString preference = "Fastest";
    if (settings.contains(QStringLiteral("preference"))) {
        preference = settings[QStringLiteral("preference")].toString();
    }
    if (preference == QLatin1String("Pedestrian")) {
        unit = QStringLiteral("M");
    }

    queries.addQueryItem("start", formatCoordinates(source));
    QStringList via;
    for (int i = 1; i < route->size()-1; ++i) {
        via << formatCoordinates(route->at(i));
    }
    queries.addQueryItem("via", via.join(' '));
    queries.addQueryItem("end", formatCoordinates(destination));

    queries.addQueryItem("distunit", unit);
    if (preference == "Fastest" || preference == "Shortest" || preference == "Recommended") {
        queries.addQueryItem("routepref", "Car");
        queries.addQueryItem("weighting", preference);
    } else {
        queries.addQueryItem("routepref", preference);
        queries.addQueryItem("weighting", "Recommended");
    }

    QString const motorways = settings.value("noMotorways").toInt() == 0 ? "false" : "true";
    queries.addQueryItem("noMotorways", motorways);
    QString const tollways = settings.value("noTollways").toInt() == 0 ? "false" : "true";
    queries.addQueryItem("noTollways", tollways);
    queries.addQueryItem("noUnpavedroads", "false");
    queries.addQueryItem("noSteps", "false");
    QString const ferries = settings.value("noFerries").toInt() == 0 ? "false" : "true";
    queries.addQueryItem("noFerries", ferries);
    queries.addQueryItem("instructions", "true");
    queries.addQueryItem("lang", "en");

    QUrl url = QUrl( "http://openls.geog.uni-heidelberg.de/route" );
    // QUrlQuery strips empty value pairs, but OpenRouteService does not work without
    QString const trailer = route->size() == 2 ? "&via=" : QString();
    url.setQuery(queries.toString() + trailer);

    m_request = QNetworkRequest( url );

    QEventLoop eventLoop;
    QTimer timer;
    timer.setSingleShot( true );
    timer.setInterval( 15000 );

    connect( &timer, SIGNAL(timeout()),
             &eventLoop, SLOT(quit()));
    connect( this, SIGNAL(routeCalculated(GeoDataDocument*)),
             &eventLoop, SLOT(quit()));

    // @todo FIXME Must currently be done in the main thread, see bug 257376
    QTimer::singleShot( 0, this, SLOT(get()));
    timer.start();

    eventLoop.exec();
}
Example #5
0
void TestQGeoPositionInfoSource::lastKnownPosition()
{
    CHECK_SOURCE_VALID;
    QFETCH(int, positioningMethod);
    QFETCH(bool, lastKnownPositionArgument);
    QFETCH(bool, positionValid);

#if defined(Q_OS_SYMBIAN)
    QSKIP("Real GPS not suitable for autotesting, skipping the test.", SkipAll);
#endif
    QGeoPositionInfoSource::PositioningMethods method
            = static_cast<QGeoPositionInfoSource::PositioningMethods>(positioningMethod);

    if ((m_source->supportedPositioningMethods() & method) == 0)
        QSKIP("Not a supported positioning method for this position source", SkipSingle);

    m_source->setPreferredPositioningMethods(method);

    QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)));
    QSignalSpy timeout(m_source, SIGNAL(updateTimeout()));
    int time_out = 7000;
    m_source->setUpdateInterval(time_out);
    m_source->startUpdates();

    // Use QEventLoop instead of qWait() to ensure we stop as soon as a
    // position is emitted (otherwise the lastKnownPosition() may have
    // changed by the time it is checked)
    QEventLoop loop;
    QTimer timer;
    timer.setInterval(9500);
    connect(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)),
            &loop, SLOT(quit()));
    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    timer.start();
    loop.exec();

    EXPECT_FAIL_WINCE_SEE_MOBILITY_337_ABORT;

    QVERIFY((spy.count() > 0) && (timeout.count() == 0));

    QList<QVariant> list = spy.takeFirst();
    QGeoPositionInfo info;
    info = list.at(0).value<QGeoPositionInfo>();
    QGeoPositionInfo lastPositioninfo;
    lastPositioninfo = m_source->lastKnownPosition(lastKnownPositionArgument);
 
    QCOMPARE(lastPositioninfo.isValid(), positionValid);

    if (positionValid) {
        QCOMPARE(info.coordinate(), lastPositioninfo.coordinate());
        QCOMPARE(info.timestamp(), lastPositioninfo.timestamp());

        QCOMPARE(info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy),
                 lastPositioninfo.hasAttribute(QGeoPositionInfo::HorizontalAccuracy));

        if (info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy)) {
            bool isNaN1 =  qIsNaN(info.attribute(QGeoPositionInfo::HorizontalAccuracy));
            bool isNaN2 =  qIsNaN(lastPositioninfo.attribute(QGeoPositionInfo::HorizontalAccuracy));
            QCOMPARE(isNaN1, isNaN2);
            if (!isNaN1) {
                QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::HorizontalAccuracy),
                                       lastPositioninfo.attribute(QGeoPositionInfo::HorizontalAccuracy)), TRUE);
            }
        }

        QCOMPARE(info.hasAttribute(QGeoPositionInfo::VerticalAccuracy),
                 lastPositioninfo.hasAttribute(QGeoPositionInfo::VerticalAccuracy));

        if (info.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) {
            bool isNaN1 =  qIsNaN(info.attribute(QGeoPositionInfo::VerticalAccuracy));
            bool isNaN2 =  qIsNaN(lastPositioninfo.attribute(QGeoPositionInfo::VerticalAccuracy));
            QCOMPARE(isNaN1, isNaN2);
            if (!isNaN1) {
                QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::VerticalAccuracy),
                                       lastPositioninfo.attribute(QGeoPositionInfo::VerticalAccuracy)), TRUE);
            }
        }
    }

    m_source->stopUpdates();
}
Example #6
0
int main(int argc, char **argv)
{
	ccApplication::init();
	
	ccApplication app(argc, argv);

	//store the log message until a valid logging instance is registered
	ccLog::EnableMessageBackup(true);
	
	//restore some global parameters
	{
		QSettings settings;
		settings.beginGroup(ccPS::GlobalShift());
		double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble();
		double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble();
		settings.endGroup();

		ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0));
		
		ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord);
		ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag);
	}

	//Command line mode?
	bool commandLine = (argc > 1 && argv[1][0] == '-');
	
	//specific commands
	int lastArgumentIndex = 1;
	QTranslator translator;
	if (commandLine)
	{
		//translation file selection
		if (QString(argv[lastArgumentIndex]).toUpper() == "-LANG")
		{
			QString langFilename = QString(argv[2]);

			//Load translation file
			if (translator.load(langFilename, QCoreApplication::applicationDirPath()))
			{
				qApp->installTranslator(&translator);
			}
			else
			{
				QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename));
			}
			commandLine = false;
			lastArgumentIndex += 2;
		}
	}

	//splash screen
	QScopedPointer<QSplashScreen> splash(nullptr);
	QTimer splashTimer;

	//standard mode
	if (!commandLine)
	{
		if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0)
		{
			QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!");
			return EXIT_FAILURE;
		}

		//splash screen
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash.reset(new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint));
		splash->show();
		QApplication::processEvents();
	}

	//global structures initialization
	FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!)
	ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization
	ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization

	//load the plugins
	ccPluginManager::loadPlugins();
	
	int result = 0;

	//command line mode
	if (commandLine)
	{
		//command line processing (no GUI)
		result = ccCommandLineParser::Parse(argc, argv, ccPluginManager::pluginList());
	}
	else
	{
		//main window init.
		MainWindow* mainWindow = MainWindow::TheInstance();
		if (!mainWindow)
		{
			QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!");
			return EXIT_FAILURE;
		}
		mainWindow->initPlugins();
		mainWindow->show();
		QApplication::processEvents();

		//show current Global Shift parameters in Console
		{
			ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2")
				.arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0)
				.arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0));
		}

		if (argc > lastArgumentIndex)
		{
			if (splash)
			{
				splash->close();
			}

			//any additional argument is assumed to be a filename --> we try to load it/them
			QStringList filenames;
			for (int i = lastArgumentIndex; i < argc; ++i)
			{
				QString arg(argv[i]);
				//special command: auto start a plugin
				if (arg.startsWith(":start-plugin:"))
				{
					QString pluginName = arg.mid(14);
					QString pluginNameUpper = pluginName.toUpper();
					//look for this plugin
					bool found = false;
					for ( ccPluginInterface *plugin : ccPluginManager::pluginList() )
					{
						if (plugin->getName().replace(' ', '_').toUpper() == pluginNameUpper)
						{
							found = true;
							bool success = plugin->start();
							if (!success)
							{
								ccLog::Error(QString("Failed to start the plugin '%1'").arg(plugin->getName()));
							}
							break;
						}
					}

					if (!found)
					{
						ccLog::Error(QString("Couldn't find the plugin '%1'").arg(pluginName.replace('_', ' ')));
					}
				}
				else
				{
					filenames << QString::fromLocal8Bit(argv[i]);
				}
			}

			mainWindow->addToDB(filenames);
		}
		else if (splash)
		{
			//count-down to hide the timer (only effective once the application will have actually started!)
			QObject::connect(&splashTimer, &QTimer::timeout, [&]() { if (splash) splash->close(); QCoreApplication::processEvents(); splash.reset(); });
			splashTimer.setInterval(1000);
			splashTimer.start();
		}

		//change the default path to the application one (do this AFTER processing the command line)
		QDir  workingDir = QCoreApplication::applicationDirPath();
		
	#ifdef Q_OS_MAC
		// This makes sure that our "working directory" is not within the application bundle	
		if ( workingDir.dirName() == "MacOS" )
		{
			workingDir.cdUp();
			workingDir.cdUp();
			workingDir.cdUp();
		}
	#endif

		QDir::setCurrent(workingDir.absolutePath());

		//let's rock!
		try
		{
			result = app.exec();
		}
		catch (const std::exception& e)
		{
			QMessageBox::warning(0, "CC crashed!", QString("Hum, it seems that CC has crashed... Sorry about that :)\n") + e.what());
		}
		catch (...)
		{
			QMessageBox::warning(0, "CC crashed!", "Hum, it seems that CC has crashed... Sorry about that :)");
		}

		//release the plugins
		for ( ccPluginInterface *plugin : ccPluginManager::pluginList() )
		{
			plugin->stop(); //just in case
		}
	}

	//release global structures
	MainWindow::DestroyInstance();
	FileIOFilter::UnregisterAll();

#ifdef CC_TRACK_ALIVE_SHARED_OBJECTS
	//for debug purposes
	unsigned alive = CCShareable::GetAliveCount();
	if (alive > 1)
	{
		printf("Error: some shared objects (%u) have not been released on program end!",alive);
		system("PAUSE");
	}
#endif

	return result;
}
Example #7
0
void ChatWindow::startTimerForTimeStamps() {
    QTimer* timer = new QTimer(this);
    timer->setInterval(10 * 60 * 1000);
    connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
    timer->start();
}
Example #8
0
void Reader_RFM008B::readData()
{
    if(m_serial->canReadLine()){
        if(!allLines){

//            Logger::instance()->writeRecord(Logger::severity_level::debug, m_module, Q_FUNC_INFO, QString("Reading Data..."));

            QByteArray buffer = m_serial->readAll();
            QRegExp regex;
            regex.setPattern("(L(\\d{2})?W)\\s([0-9a-fA-F]{4})\\s([0-9a-fA-F]{16})");

            QString data(buffer);
            data.remove(QRegExp("[\\n\\t\\r]"));

            //        if(m_outReceived.device()){
            //            m_outReceived << data;
            //            m_outReceived.flush();
            //        }


            int pos = regex.indexIn(data);
            if(pos != -1){
                // The first string in the list is the entire matched string.
                // Each subsequent list element contains a string that matched a
                // (capturing) subexpression of the regexp.
                QStringList matches = regex.capturedTexts();

                // crear RFIDData
                QRegularExpression regexCode;
                regexCode.setPattern("([0-9a-fA-F]{4})(\\s)([0-9a-fA-F]{16})");
                QRegularExpressionMatch match = regexCode.match(matches.at(0));

                if(m_outCaptured.device()){
                    m_outCaptured << matches.at(0);
                    m_outCaptured.flush();
                }

                if(match.hasMatch()) {
                    Rfiddata *data = new Rfiddata(this);

                    // Id collector from configuration file
                    data->setIdpontocoleta(idCollector);

                    // This module can read from only one antena, so the idAntena is static.
                    int idAntena = 1;
                    data->setIdantena(idAntena);

                    qlonglong applicationcode = match.captured(1).toLongLong();
                    qlonglong identificationcode = match.captured(3).toLongLong();

                    /*
                 * Filter by time. If more than one transponder was read in a time interval only one of them will be persisted.
                 * A QMap is used to verify if each new data that had arrived was already read in this interval.
                 */
                    if(!m_map.contains(identificationcode)){

                        QTimer *timer = new QTimer;
                        timer->setSingleShot(true);
                        timer->setInterval(1000);
                        connect(timer, &QTimer::timeout,
                                [=, this]()
                        {
                            this->m_map.remove(identificationcode);
                            timer->deleteLater();
                        });
                        m_map.insert(identificationcode, timer);
                        timer->start();

                        data->setApplicationcode(applicationcode);
                        data->setIdentificationcode(identificationcode);
                        data->setDatetime(QDateTime::currentDateTime());
                        data->setSync(Rfiddata::KNotSynced);

                        QList<Rfiddata*> list;
                        list.append(data);
                        try {
                            PersistenceInterface *persister = qobject_cast<PersistenceInterface *>(RFIDMonitor::instance()->defaultService(ServiceType::KPersister));
                            Q_ASSERT(persister);
                            SynchronizationInterface *synchronizer = qobject_cast<SynchronizationInterface*>(RFIDMonitor::instance()->defaultService(ServiceType::KSynchronizer));
                            Q_ASSERT(synchronizer);

#ifdef CPP_11_ASYNC
                            /*C++11 std::async Version*/
                            std::function<void(const QList<Rfiddata *>&)> persistence = std::bind(&PersistenceInterface::insertObjectList, persister, std::placeholders::_1);
                            std::async(std::launch::async, persistence, list);
                            std::function<void()> synchronize = std::bind(&SynchronizationInterface::readyRead, synchronizer);
                            std::async(std::launch::async, synchronize);
#else
                            /*Qt Concurrent Version*/
                            QtConcurrent::run(persister, &PersistenceInterface::insertObjectList, list);
                            QtConcurrent::run(synchronizer, &SynchronizationInterface::readyRead);
#endif
                        } catch (std::exception &e) {
                            Logger::instance()->writeRecord(Logger::severity_level::fatal, m_module, Q_FUNC_INFO, e.what());
                        }
                    }
                }
            }
        }else{

            //            Logger::instance()->writeRecord(Logger::severity_level::debug, m_module, Q_FUNC_INFO, QString("FULL READ..."));

            QByteArray buffer = m_serial->readLine();
            QString data(buffer);
            data.remove(QRegExp("[\\n\\t\\r]"));

            // Remove lines only with LI. Not used anywhere.
            if(data == "LI")
                return;

            json::NodeJSMessage answer;
            answer.setType("READER-RESPONSE");

            QJsonObject dataObj;
            dataObj.insert("sender", QString("app"));
            dataObj.insert("response", data);
            dataObj.insert("reader", QString("1"));

            answer.setDateTime(QDateTime::currentDateTime());
            answer.setJsonData(dataObj);
            QJsonObject jsonAnswer;
            answer.write(jsonAnswer);


            static CommunicationInterface *communitacion = 0;
            communitacion = qobject_cast<CommunicationInterface *>(RFIDMonitor::instance()->defaultService(ServiceType::KCommunicator));

#ifdef CPP_11_ASYNC
            /*C++11 std::async Version*/
            std::function<void (QByteArray)> sendMessage = std::bind(&CommunicationInterface::sendMessage, communitacion, std::placeholders::_1);
            std::async(std::launch::async, sendMessage, QJsonDocument(jsonAnswer).toJson());
#else
            /*Qt Concurrent Version*/
            QtConcurrent::run(communitacion, &CommunicationInterface::sendMessage, QJsonDocument(jsonAnswer).toJson());
#endif
        }
    }
}
CWinMainControler::CWinMainControler(CListStream* argAnalyseur,CCarteIO* argCarteIO,CCarteMesure* argCarteMesure, CSocketIHM* argInterfaceIHM)
    :m_CurrentGraphPage(0)
{
	qDebug() << "#### CWinMainControler::CWinMainControler" << endl;
	
	m_pSupervision = new CSupervision();
	m_pSupervision->setAnalyseur((CAnalyseur*)argAnalyseur);
	m_pSupervision->setCarteMesure(argCarteMesure);
	m_pSupervision->setCarteIO(argCarteIO);
	m_pSupervision->setInterfaceIHM(argInterfaceIHM);

	//Fenêtre alarme
	m_pDialogAlarm = new CDialogAlarm(m_pSupervision);
   
    //Fenêtre principale
	m_pView  = new CWinMainView(this);
	m_pModel = new CWinMainModel(m_pSupervision, m_pView);
	m_pView->setModel(m_pModel);

    //Construction des objets avant pour plus de fluidité  
	CWinElecTestControler::getInstance(this);
    CWinMaintenanceControler::getInstance(this);
    CWinSchedulerControler::getInstance(this);
    CWinStreamControler::getInstance(this);  

    //Construction de toutes les boites de dialog
    CDialogStopCycle::getInstance();
    CDialogCopyFiles::getInstance();
    CDialogInfo::getInstance();
    CDialogMessage::getInstance();
    CDialogPassword::getInstance();
    CDialogPaveNum::getInstance();
    CDialogRestauration::getInstance();
    CDialogResultatEtalon::getInstance();
    CDialogValEtalon::getInstance();
    
	CUserSession::getInstance()->objectRegister(this);

	
	//Controles de la fenêtre principale
	m_bEnStop = false;
	m_bEnPause = false;
	
	QPixmapCache::setCacheLimit(128);
	qDebug() << "#### FIN CWinMainControler::CWinMainControler" << endl;

	//récupération des erreurs
	QTimer* timerGetError = new QTimer(this);
	timerGetError->setInterval(1000);
	connect(timerGetError, SIGNAL(timeout()), this, SLOT(getErrorIOAndJBus()));
	timerGetError->start();
	
#ifdef SCREENSHOTS
	m_nbScreenshot = 0;
	QTimer* timerScreenShot = new QTimer(this);
	timerScreenShot->setInterval(3000);
	connect(timerScreenShot, SIGNAL(timeout()), this, SLOT(takeScreenshot()));
	timerScreenShot->start();
	//Fin screenshot
#endif

}
Example #10
0
RemoteOM::RemoteOM(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::RemoteOM)
{

    mapResponse[48] = "No fault";
    mapResponse[49] = "IP. Plate current too high.";
    mapResponse[50] = "HV. Plate/anode voltage too low.";
    mapResponse[51] = "SWR. Excessive reflected power.";
    mapResponse[52] = "Ig2. Screen limit exceeded.";
    mapResponse[53] = "Overdrive. Too much drive from exciter.";
    mapResponse[54] = "FWD=0, Power output is zero with drive power higher than zero.";
    mapResponse[55] = "Igmax. 1st grid current limit exceeded.";
    mapResponse[56] = "Tune. Insufficient tuning - retune PA";
    mapResponse[62] = "PA turned on.";
    mapResponse[60] = "PA turned off.";
    mapResponse[83] = "PA turned to stand by mode.";
    mapResponse[79] = "PA turned to operating mode.";
    mapResponse[76] = "List 20 last fault codes.";
    mapResponse[71] = "Reset PA succeeded.";
    mapResponse[87] = "PA is heating up. Please wait.";
    mapResponse[90] = "Operating is not possible.";
    mapResponse[84] = "Fatal fault.";

    dialog = new SettingsDialog();

    ui->setupUi(this);
    createActions();

    //Init settings if startprofile is empty
    if (startProfile.isEmpty())
    {
        dialog->FirstChoice(startProfile.remove("\""));
        startProfile = "";
    }

    QTimer *timer = new QTimer(this);
    timer->setInterval(1000);
    timer->start();
    connect(timer, SIGNAL(timeout()), this, SLOT(TimeOut()));


    ui->menu->addAction(configureAct);
    ui->menu->addAction(exitAct);
    ui->ledDrive->hide();
    ui->ledGrid->hide();
    ui->ledOperate->hide();
    ui->ledPA->hide();
    ui->ledPower->hide();
    ui->ledStdby->hide();
    ui->ledSwr->hide();
    ui->ledTune->hide();
    ui->ledFault->hide();

    connect(ui->buttonConnect, SIGNAL(clicked()), this, SLOT(connectSocket()));
    socket = new QTcpSocket(this);
    ui->buttonPower->setStatusTip(tr("Turn PA ON/OFF."));
    ui->buttonOperate->setStatusTip(tr("Turn Operate ON/OFF."));
    ui->buttonConnect->setStatusTip(tr("Connect/Disconnect to Remote OM"));

    setInfoText("Connecting to Remote OM. Please wait.");

    receiveFaults = false;

    faultTimer = new QTimer(this);
    waitTimer = new QTimer(this);
    connect(faultTimer, SIGNAL(timeout()), this, SLOT(blinkFault()));
    connect(waitTimer, SIGNAL(timeout()), this, SLOT(blinkWait()));

    //Get settings
    if (!startProfile.isEmpty())
    {
       /* dialog->SetInitialSettings();
        QString show_ip = dialog->set_ipaddress;
        QString show_port = dialog->set_port;
        ui->txtCurrentSettings->setText("Current settings: "+show_ip+":"+show_port);*/
    }

}
Example #11
0
void QTimerProto::setInterval(int msec)
{
  QTimer *item = qscriptvalue_cast<QTimer*>(thisObject());
  if (item)
    item->setInterval(msec);
}
Example #12
0
ProofPage::ProofPage(ResizableStackedWidget *pageStack, Model *model, QWidget *parent)
    : QWidget(parent)
{
    this->model = model;
    this->pageStack = pageStack;



    proofEditForm = new ProofForm();
    proofEditDialog = new Dialog(this, proofEditForm, "Edit the proof...", "Change", "Cancel");

    proofDeleteDialog = new Dialog(this, nullptr, "Are you sure you want to delete this proof?", "Delete", "Cancel");



    QVBoxLayout *outerLayout = new QVBoxLayout(this);



    //  ##   ## #######   ###   #####   ####### #####
    //  ##   ## ##       ## ##  ##  ##  ##      ##  ##
    //  ##   ## ##      ##   ## ##   ## ##      ##   ##
    //  ####### #####   ##   ## ##   ## #####   ##  ##
    //  ##   ## ##      ####### ##   ## ##      #####
    //  ##   ## ##      ##   ## ##  ##  ##      ##  ##
    //  ##   ## ####### ##   ## #####   ####### ##   ##

    // The breadcrumbs show the current course and provide
    // a way to go back to the courses screen.
    // It is presented like a filepath.

    QHBoxLayout *crumbBorderLayout = new QHBoxLayout();

    breadCrumbs = new BreadCrumbs(3, model, pageStack);
    breadCrumbs->setFixedWidth(700);

    crumbBorderLayout->addStretch(1);
    crumbBorderLayout->addWidget(breadCrumbs);
    crumbBorderLayout->addStretch(1);

    outerLayout->addLayout(crumbBorderLayout);



    // Now show the name of the current proof and some buttons to
    // edit it, delete it or add a new dependency.

    QHBoxLayout *topBorderLayout = new QHBoxLayout();

    QWidget *topWidget = new QWidget();
    topWidget->setFixedWidth(700);
    QHBoxLayout *topLayout = new QHBoxLayout(topWidget);
    topLayout->setContentsMargins(0, 0, 0, 0);

    proofLabel = new QLabel();
    proofLabel->setWordWrap(true);
    proofLabel->setScaledContents(true);

    QFont proofFont = proofLabel->font();
    proofFont.setPointSize(24);
    proofLabel->setFont(proofFont);

    trafficLight = new TrafficLight(TrafficLight::AMBER);
    trafficLight->setFixedSize(QSize(32, 32));
    QVBoxLayout *trafficLightVLayout = new QVBoxLayout();
    trafficLightVLayout->addSpacing(16);
    trafficLightVLayout->addWidget(trafficLight);

    editProofButton = new ImageButton(QPixmap(":/images/pencil_black.png"), QSize(32, 32));
    QVBoxLayout *editProofVLayout = new QVBoxLayout();
    editProofVLayout->addSpacing(16);
    editProofVLayout->addWidget(editProofButton);

    deleteProofButton = new ImageButton(QPixmap(":/images/trash_black.png"), QSize(32, 32));
    QVBoxLayout *deleteProofVLayout = new QVBoxLayout();
    deleteProofVLayout->addSpacing(16);
    deleteProofVLayout->addWidget(deleteProofButton);

    topLayout->addWidget(proofLabel);
    topLayout->addLayout(trafficLightVLayout);
    topLayout->addSpacing(10);
    topLayout->addLayout(editProofVLayout);
    topLayout->addSpacing(10);
    topLayout->addLayout(deleteProofVLayout);

    topBorderLayout->addStretch(1);
    topBorderLayout->addWidget(topWidget);
    topBorderLayout->addStretch(1);
    outerLayout->addLayout(topBorderLayout);



    outerLayout->addSpacing(20);
    outerLayout->addWidget(new HorizontalSeperator(QColor(66, 139, 202), 2));
    outerLayout->addSpacing(20);



    //  ######   #####  #####   ##    ##
    //  ##   ## ##   ## ##  ###  ##  ##
    //  ##   ## ##   ## ##   ##   ####
    //  ######  ##   ## ##   ##    ##
    //  ##   ## ##   ## ##   ##    ##
    //  ##   ## ##   ## ##  ###    ##
    //  ######   #####  #####      ##

    // Use a vertical splitter to divide the areas.

    splitter = new Splitter(Qt::Vertical);
    outerLayout->addWidget(splitter);
    splitter->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);



    // The first area is a large text editing widget, this is
    // used to edit the proof's body.
    // The QTextEdit does its own scrolling.

    bodyTextEdit = new QTextEdit();

    QFont font = bodyTextEdit->font();
    font.setFamily("Courier");
    font.setPointSize(12);
    bodyTextEdit->setFont(font);

    bodyHighlighter = new LatexHighlighter(bodyTextEdit->document());

    splitter->addWidget(bodyTextEdit);

    QTimer *bodySaveTimer = new QTimer(this);
    bodySaveTimer->setSingleShot(true);
    bodySaveTimer->setInterval(200);

    connect(bodyTextEdit, SIGNAL(textChanged()), bodySaveTimer, SLOT(start()));
    connect(bodySaveTimer, SIGNAL(timeout()), this, SLOT(saveBody()));



    // The second area contains the rendered body.

    QScrollArea *bodyScrollArea = new QScrollArea();
    bodyScrollArea->setWidgetResizable(true);
    bodyScrollArea->setFrameShape(QFrame::NoFrame);

    QWidget *bodyWidget = new QWidget();

    QPalette palette = bodyWidget->palette();
    palette.setColor(QPalette::Background, Qt::white);
    bodyWidget->setPalette(palette);
    bodyWidget->setAutoFillBackground(true);

    bodyImage = new ResizableImage("");

    QHBoxLayout *bodyHLayout = new QHBoxLayout();
    bodyHLayout->addStretch(1);
    bodyHLayout->addWidget(bodyImage);
    bodyHLayout->addStretch(1);

    QVBoxLayout *bodyVLayout = new QVBoxLayout();
    bodyVLayout->addLayout(bodyHLayout);
    bodyVLayout->addStretch(1);

    bodyWidget->setLayout(bodyVLayout);
    bodyScrollArea->setWidget(bodyWidget);
    splitter->addWidget(bodyScrollArea);



    //  #####  ####  #####  ##   ##   ###   ##       #####
    // ##   ##  ##  ##   ## ###  ##  ## ##  ##      ##   ##
    //  ##      ##  ##      ###  ## ##   ## ##       ##
    //   ###    ##  ##      ####### ##   ## ##        ###
    //     ##   ##  ##  ### ##  ### ####### ##          ##
    // ##   ##  ##  ##   ## ##  ### ##   ## ##      ##   ##
    //  #####  ####  #####  ##   ## ##   ## #######  #####

    connect(editProofButton, SIGNAL(clicked()), this, SLOT(proofEditButtonClicked()));

    connect(proofEditDialog, SIGNAL(accepted()), this, SLOT(proofEditDialogCompleted()));
    connect(proofEditDialog, SIGNAL(rejected()), proofEditDialog, SLOT(close()));

    connect(deleteProofButton, SIGNAL(clicked()), proofDeleteDialog, SLOT(show()));

    connect(proofDeleteDialog, SIGNAL(accepted()), this, SLOT(proofDeleteDialogAccepted()));
    connect(proofDeleteDialog, SIGNAL(rejected()), proofDeleteDialog, SLOT(close()));

    connect(model, SIGNAL(proofSelectedChanged(Proof)), this, SLOT(proofSelectedChangedSlot(Proof)));
    connect(model, SIGNAL(proofEdited(Proof)), this, SLOT(proofEditedSlot(Proof)));
    connect(model, SIGNAL(proofDeleted(int)), this, SLOT(proofDeletedSlot(int)));
}
void ShutDownFrame::initUI() {
    m_btnsList = new QList<RoundItemButton *>;
    m_shutdownButton = new RoundItemButton(tr("Shut down"));
    m_shutdownButton->setAutoExclusive(true);
    m_shutdownButton->setObjectName("ShutDownButton");
    m_restartButton = new RoundItemButton(tr("Restart"));
    m_restartButton->setAutoExclusive(true);
    m_restartButton->setObjectName("RestartButton");
    m_suspendButton = new RoundItemButton(tr("Suspend"));
    m_suspendButton->setAutoExclusive(true);
    m_suspendButton->setObjectName("SuspendButton");
    m_lockButton = new RoundItemButton(tr("Lock"));
    m_lockButton->setAutoExclusive(true);
    m_lockButton->setObjectName("LockButton");
    m_logoutButton = new RoundItemButton(tr("Log out"));
    m_logoutButton->setAutoExclusive(true);
    m_logoutButton->setObjectName("LogoutButton");

    m_switchUserBtn = new RoundItemButton(tr("Switch user"));
    m_switchUserBtn->setAutoExclusive(true);
    m_switchUserBtn->setObjectName("SwitchUserButton");

    QLabel *tipsIcon = new QLabel;
    tipsIcon->setPixmap(QPixmap(":/img/waring.png"));
    m_tipsLabel = new QLabel;
    m_tipsLabel->setAlignment(Qt::AlignCenter);
    m_tipsLabel->setStyleSheet("color:white;"
                               "font-size:14px;");
    QHBoxLayout *tipsLayout = new QHBoxLayout;
    tipsLayout->addStretch();
    tipsLayout->addWidget(tipsIcon);
    tipsLayout->addWidget(m_tipsLabel);
    tipsLayout->addStretch();

    m_tipsWidget = new QWidget;
    m_tipsWidget->hide();
    m_tipsWidget->setLayout(tipsLayout);

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->setMargin(0);
    buttonLayout->setSpacing(10);
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_shutdownButton);
    buttonLayout->addWidget(m_restartButton);
    buttonLayout->addWidget(m_suspendButton);
    buttonLayout->addWidget(m_lockButton);
    buttonLayout->addWidget(m_switchUserBtn);
    buttonLayout->addWidget(m_logoutButton);
    buttonLayout->addStretch(0);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setMargin(0);
    mainLayout->setSpacing(0);
    mainLayout->addStretch();
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(m_tipsWidget);
    mainLayout->addStretch();
    setFocusPolicy(Qt::StrongFocus);
    setLayout(mainLayout);

    updateStyle(":/skin/shutdown.qss", this);


    m_btnsList->append(m_shutdownButton);
    m_btnsList->append(m_restartButton);
    m_btnsList->append(m_suspendButton);
    m_btnsList->append(m_lockButton);
    m_btnsList->append(m_switchUserBtn);
    m_btnsList->append(m_logoutButton);

    m_currentSelectedBtn = m_shutdownButton;
    m_currentSelectedBtn->updateState(RoundItemButton::Default);

    //// Inhibit to shutdown
    inhibitShutdown();

    QTimer* checkTooltip = new QTimer(this);
    checkTooltip->setInterval(5*60*1000);
    checkTooltip->start();
    connect(checkTooltip,  &QTimer::timeout, this, &ShutDownFrame::inhibitShutdown);
}
Example #14
0
FacebookWidget::FacebookWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FacebookWidget)
{
    systemTrayIcon = new QSystemTrayIcon(QIcon(":/res/logo/Facebook-icon.png"));
    systemTrayMenu = new QMenu();
    notificationAction = new QAction(tr("Notifications"),this);
    friendRequestAction = new QAction(tr("Friend requests"),this);
    messagesAction = new QAction(tr("Messages"),this);
    quitAction = new QAction(tr("Quit"),this);
    windowVisibilityToggleAction = new QAction(tr("Hide"),this);
    aboutWindow = new AboutWindow();
    windowVisible = true;
    systemTrayMenu->addAction(windowVisibilityToggleAction);
    systemTrayMenu->addSeparator();
    systemTrayMenu->addAction(friendRequestAction);
    systemTrayMenu->addAction(messagesAction);
    systemTrayMenu->addAction(notificationAction);
    systemTrayMenu->addSeparator();
    systemTrayMenu->addAction(quitAction);
    systemTrayIcon->setContextMenu(systemTrayMenu);
    systemTrayIcon->show();
    themeSelectorWidget = new ThemeSelectorWidget();
    pressed = false;
    ui->setupUi(this);
    webView = new QWebView();
    ui->mainLayout->addWidget(webView);
    webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    this->setLayout(ui->mainLayout);
    connect(webView->page()->networkAccessManager(),SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),this,SLOT(sslErrorHandler(QNetworkReply*,QList<QSslError>)));
    connect(webView,SIGNAL(loadProgress(int)),ui->progressBar,SLOT(setValue(int)));
    connect(webView,SIGNAL(loadFinished(bool)),ui->progressBar,SLOT(reset()));
    connect(ui->backButton,SIGNAL(clicked()),webView,SLOT(back()));
    connect(ui->forwardButton,SIGNAL(clicked()),webView,SLOT(forward()));
    connect(ui->closeButton,SIGNAL(clicked()),this,SLOT(toggleWindowVisibility()));
    connect(quitAction,SIGNAL(triggered()),this,SLOT(quitActionTriggered()));
#ifndef Q_OS_MAC
    connect(systemTrayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(onSystemTrayClicked(QSystemTrayIcon::ActivationReason)));
#endif
    connect(friendRequestAction,SIGNAL(triggered()),this,SLOT(friendRequestActionTriggered()));
    connect(messagesAction,SIGNAL(triggered()),this,SLOT(messagesActionTriggered()));
    connect(notificationAction,SIGNAL(triggered()),this,SLOT(notificationActionTriggered()));
    connect(windowVisibilityToggleAction,SIGNAL(triggered()),this,SLOT(toggleWindowVisibility()));
    connect(webView->page(),SIGNAL(linkClicked(QUrl)),this,SLOT(delegateLink(QUrl)));
    connect(ui->aboutButton,SIGNAL(clicked()),aboutWindow,SLOT(show()));
    connect(ui->maximizeButton,SIGNAL(clicked()),this,SLOT(fullscreenToggle()));
    connect(ui->themeButton,SIGNAL(clicked()),themeSelectorWidget,SLOT(show()));
    connect(themeSelectorWidget,SIGNAL(applyTheme(QStringList)),this,SLOT(setTheme(QStringList)));
    connect(themeSelectorWidget,SIGNAL(useDefaultTheme()),this,SLOT(useDefaultTheme()));
    windowSizes << QRect(10,10,640,480);
    windowSizes << QRect(10,10,800,480);
    windowSizes << QRect(10,10,1030,600);
    windowSizes << desktopDetails.availableGeometry();
    windowSizeIndex = 2;
    setGeometry(windowSizes.at(2));
    setWindowFlags(Qt::FramelessWindowHint);
    themeRefreshTimer = new QTimer();
    QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled,true);
    QDir configDir = QDir::home();
    configDir.mkpath(".config/Socializer");
    configDir.mkpath(".config/Socializer/LocalStorage/");
    configDir.mkpath(".config/Socializer/OfflineStorage/");
    configDir.mkpath(".config/Socializer/IconDatabase/");
    configDir.mkpath(".config/Socializer/OfflineWebApplicationCache/");
    configDir.cd(".config/Socializer");
    configDir.cd("OfflineStorage");
    QWebSettings::setOfflineStoragePath(configDir.absolutePath());
    configDir.cdUp();
    configDir.cd("IconDatabase");
    QWebSettings::setIconDatabasePath(configDir.absolutePath());
    configDir.cdUp();
    configDir.cd("OfflineWebApplicationCache");
    QWebSettings::setOfflineWebApplicationCachePath(configDir.absolutePath());
    configDir.cdUp();
    QWebSettings::setMaximumPagesInCache(100);
    QWebSettings::globalSettings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled,true);
    QWebSettings::globalSettings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled,true);
    QWebSettings::globalSettings()->setAttribute(QWebSettings::LocalStorageEnabled,true);
    cookieJar = new CookieJar;
    webView->page()->networkAccessManager()->setCookieJar(cookieJar);
    cookieJar->load();
    configDir.cd("LocalStorage");
    webView->page()->settings()->setLocalStoragePath(configDir.absolutePath());
    webView->page()->settings()->setAttribute(QWebSettings::LocalStorageEnabled,true);
    configDir.cdUp();

    QTimer *refreshTimer = new QTimer();
    refreshTimer->setInterval(5000);
    connect(refreshTimer,SIGNAL(timeout()),this,SLOT(getNewStatus()));
    refreshTimer->start();
    fullscreen = false;
    loadApplicationState();
}
Example #15
0
void addlens::change()
{
    if(dPrevAConst_1!=ui->AVal_1->text().toDouble())
    {
        if(ui->AVal_1->text().toDouble()>=115 && ui->AVal_1->text().toDouble()<=128)
        {
            double temp=ui->AVal_1->text().toDouble();

            ui->AVal_1->setText(QString::number(temp,'f',2));

           /* ui->A0val->setText(QString::number( (0.62467 *(ui->AVal_1->text().toDouble()) - 72.434),'f',2));

            ui->Acdval->setText(QString::number(((ui->AVal_1->text().toDouble())*0.5663-62.005)/0.9704,'f',2));

            ui->Sfval->setText(QString::number(0.9704 *ui->Acdval->text().toDouble() - 3.595,'f',2));*/


        }
        else
        {
            ui->AVal_1->setText(QString::number(dPrevAConst_1,'f',2));

            p=new prompta("AConst should be between 115 and 128",this);

            p->move(200,200);

            p->show();

            QTimer *msgBoxCloseTimer = new QTimer(this);

            msgBoxCloseTimer->setInterval(3000);

            msgBoxCloseTimer->setSingleShot(true);

            connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

            msgBoxCloseTimer->start();

            p->exec();

        }

    }
    else if(dPrevAConst_2!=ui->AVal_2->text().toDouble())
    {
        if(ui->AVal_2->text().toDouble()>=115 && ui->AVal_2->text().toDouble()<=128)
        {
            double temp=ui->AVal_2->text().toDouble();

            ui->AVal_2->setText(QString::number(temp,'f',2));

            ui->A0val->setText(QString::number( (0.62467 *(ui->AVal_2->text().toDouble()) - 72.434),'f',2));

            ui->Acdval->setText(QString::number(((ui->AVal_2->text().toDouble())*0.5663-62.005)/0.9704,'f',2));

            ui->Sfval->setText(QString::number(0.9704 *ui->Acdval->text().toDouble() - 3.595,'f',2));


        }
        else
        {
            ui->AVal_2->setText(QString::number(dPrevAConst_2,'f',2));

            p=new prompta("AConst out of range",this);

            p->move(200,200);

            p->show();

            QTimer *msgBoxCloseTimer = new QTimer(this);

            msgBoxCloseTimer->setInterval(3000);

            msgBoxCloseTimer->setSingleShot(true);

            connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

            msgBoxCloseTimer->start();

            p->exec();

        }

    }
    else if(dPrevAcd!=ui->Acdval->text().toDouble())
    {
        if(ui->Acdval->text().toDouble()>=3 && ui->Acdval->text().toDouble()<=11)
         {
             double temp=ui->Acdval->text().toDouble();

             ui->Acdval->setText(QString::number(temp,'f',2));

             ui->AVal_2->setText(QString::number((ui->Acdval->text().toDouble()*0.9704+62.005)/0.5663,'f',2));

             ui->Sfval->setText(QString::number(0.9704 *ui->Acdval->text().toDouble() - 3.595,'f',2));

             ui->A0val->setText(QString::number( (0.62467 *(ui->AVal_2->text().toDouble()) - 72.434),'f',2));


         }
         else
         {
             ui->Acdval->setText(QString::number(dPrevAcd,'f',2));

             p=new prompta("ACD out of range",this);

             p->move(200,200);

             p->show();

             QTimer *msgBoxCloseTimer = new QTimer(this);

             msgBoxCloseTimer->setInterval(3000);

             msgBoxCloseTimer->setSingleShot(true);

             connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

             msgBoxCloseTimer->start();

             p->exec();

         }

    }
    else if(dPrevSF!=ui->Sfval->text().toDouble())
    {
        if(ui->Sfval->text().toDouble()>=-0.5 && ui->Sfval->text().toDouble()<=11)
         {
            //()<<"batman";
             double temp=ui->Sfval->text().toDouble();

             ui->Sfval->setText(QString::number(temp,'f',2));

             ui->Acdval->setText(QString::number((ui->Sfval->text().toDouble()+3.595)/0.9704,'f',2));

             ui->AVal_2->setText(QString::number((ui->Acdval->text().toDouble()*0.9704+62.005)/0.5663,'f',2));

             ui->A0val->setText(QString::number( (0.62467 *(ui->AVal_2->text().toDouble()) - 72.434),'f',2));


         }
         else
         {
             ui->Sfval->setText(QString::number(dPrevSF,'f',2));

             p=new prompta("SF out of range",this);

             p->move(200,200);

             p->show();

             QTimer *msgBoxCloseTimer = new QTimer(this);

             msgBoxCloseTimer->setInterval(3000);

             msgBoxCloseTimer->setSingleShot(true);

             connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

             msgBoxCloseTimer->start();

             p->exec();

         }
    }
    else if(dPrevA1!=ui->A1val->text().toDouble())
    {
        if(ui->A1val->text().toDouble()>=0.3 && ui->A1val->text().toDouble()<=0.5)
         {
             double temp=ui->A1val->text().toDouble();

             ui->A1val->setText(QString::number(temp,'f',2));


         }
         else
         {
             ui->A1val->setText(QString::number(dPrevA1,'f',2));

             p=new prompta("A1 out of range",this);

             p->move(200,200);

             p->show();

             QTimer *msgBoxCloseTimer = new QTimer(this);

             msgBoxCloseTimer->setInterval(3000);

             msgBoxCloseTimer->setSingleShot(true);

             connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

             msgBoxCloseTimer->start();

             p->exec();

         }
    }
    else if(dPrevA2!=ui->A2val->text().toDouble())
    {
        if(ui->A2val->text().toDouble()>=0 && ui->A2val->text().toDouble()<=0.2)
         {
             double temp=ui->A2val->text().toDouble();

             ui->A2val->setText(QString::number(temp,'f',2));



         }
         else
         {
             ui->A2val->setText(QString::number(dPrevA2,'f',2));

             p=new prompta("A2 out of range",this);

             p->move(200,200);

             p->show();

             QTimer *msgBoxCloseTimer = new QTimer(this);

             msgBoxCloseTimer->setInterval(3000);

             msgBoxCloseTimer->setSingleShot(true);

             connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

             msgBoxCloseTimer->start();

             p->exec();

         }
    }
}
Example #16
0
void BoatAnalysisDlg::StartAnalysis()
{
	//
	// Method applied from v6.00 onwards
	// 
	// First case :
	// If the analysis is for a wing and not a plane, the full 3D panel method is applied
	// and the wing is modelled as a thick surface
	// The method is strictly the one described in NASA TN 4023
	// The boundary condition is of the Dirichlet type, which has proved more convincing 
	// than the Neumann BC for full 3D panel methods
	//
	// Second case :
	// If the analysis is for a plane, the full 3D method is not applicable since the 
	// junctions between wing and body, or between fin and elevator, cannot be adequately 
	// represented as closed surfaces. This would require a 3D CAD programe. 
	// Therefore, in this case, the wings are modelled as thin surfaces.
	// Trial tests using the method of NASA TN 4023 have not been conclusive. With a uniform doublet
	// distribution and a boundary condition applied at the panel's centroid, the results 
	// are less convincing than with VLM.
	// Therefore in this case, the VLM1 method is applied to the thin surfaces, and the 3D-panel method 
	// is applied to the body.
	// Last consideration : since the potential of a straight vortex line requires a lot of computations, 
	// the Neumann type BC is applied to the body panels, rather than the Dirichlet type BC
	//
//	MainFrame *pMainFrame = (MainFrame*)s_pMainFrame;
	qApp->processEvents();

	if(!m_pBoatPolar) return;

	QString strong;
	m_pctrlCancel->setText(tr("Cancel"));
	m_bIsFinished = false;


	if(m_pBoatPolar->m_bVLM1) strong = tr("Launching VLM1 Analysis....")+"\n";
	else                      strong = tr("Launching VLM2 Analysis....")+"\n";

	AddString(strong);


	if(m_pBoat->m_poaHull.size())
	{
		if(m_pBoatPolar->m_bDirichlet) strong = tr("Using Dirichlet boundary conditions for thick bodies")+"\n";
		else                           strong = tr("Using Neumann boundary conditions for thick bodies")+"\n";
		AddString(strong);
		AddString("\n");
	}


	strong = tr("Type 1 - Fixed speed polar");
	AddString(strong);
	m_bCancel = false;

	QTimer *pTimer = new QTimer;
	connect(pTimer, SIGNAL(timeout()), this, SLOT(OnProgress()));
	pTimer->setInterval(100);
	pTimer->start();

	qApp->processEvents();

	UnitLoop();


	if (!m_bCancel && !m_bWarning) strong = "\n"+tr("Panel Analysis completed successfully")+"\n";
	else if (m_bWarning)           strong = "\n"+tr("Panel Analysis completed ... Errors encountered")+"\n";
	AddString(strong);
	pTimer->stop();

//	if(m_pBoatPolar && (m_pBoatPolar->m_Type==STABILITYPOLAR || m_pBoatPolar->m_bTiltedGeom || m_pBoatPolar->m_bWakeRollUp))
	{
		//restore the panels and nodes;
		memcpy(s_pPanel, s_pMemPanel, m_MatSize * sizeof(CPanel));
		memcpy(s_pNode,  s_pMemNode,  m_nNodes  * sizeof(CVector));
		memcpy(s_pWakePanel, s_pRefWakePanel, m_WakeSize * sizeof(CPanel));
		memcpy(s_pWakeNode,  s_pRefWakeNode,  m_nWakeNodes * sizeof(CVector));
	}

	m_bIsFinished = true;
	m_pctrlCancel->setText(tr("Close"));
}
Example #17
0
Window::Window()
{
    QCommandLineParser parser;
    QCommandLineOption pathToAgentOption("p", "Path to sync agent", "agentPath");
    parser.addOption(pathToAgentOption);
    QCommandLineOption skipAgentStartOption("s", "Do not try to start agent on start up", "skipAgentStart");
    parser.addOption(skipAgentStartOption);
    QCommandLineOption dumbTestOption("test", "Super simple start/stop test.");
    parser.addOption(dumbTestOption);
    parser.process(*qApp);
    bool startAgent = true;
    if(parser.isSet(skipAgentStartOption) && parser.value(skipAgentStartOption) == "true"){
        startAgent = false;
    }
    cmdHelper = new CmdHelper(this, (parser.isSet(pathToAgentOption))?parser.value(pathToAgentOption):"");
    if(parser.isSet(dumbTestOption)){
        QTimer *t = new QTimer(this);
        connect(t, SIGNAL(timeout()), qApp, SLOT(quit()));
        t->setInterval(5000);
        t->setSingleShot(true);
        t->start();
        qDebug()<<"Dumb test, will exit in 5 seconds...";
    }
    else{
        if(startAgent){
#if defined(Q_OS_WIN) || defined(Q_OS_LINUX)
            cmdHelper->launchAgentProcess();
#elif defined(Q_OS_MAC)
            qDebug()<<"Starting agent via launchctl command.";
            cmdHelper->launchAgentMac();
#endif

        }

        if(CHECK_FOR_UPDATE){
            updateDialog = new UpdateDialog(this);
            updatePinger = new PydioUpdatePinger(this);
            connect(updatePinger, SIGNAL(updateFound(QString,QString,QString,QString)),
                    updateDialog, SLOT(proposeDownload(QString,QString,QString,QString)));
            updatePinger->lookForUpdate();
        }

        QString dataDir = CmdHelper::getAppDataDir() +'/'+ PORT_CONFIG_FILE_NAME;
        portConfigurer = new PortConfigurer(dataDir);
        pollTimer = new QTimer(this);
        pollTimer->setInterval(POLL_INTERVAL);
        pollTimer->setSingleShot(true);

        httpManager = new HTTPManager(this);
        this->createTrayIcon();
        tray->show();

        aboutDialog = new AboutDialog(this);

        connect(pollTimer, SIGNAL(timeout()), httpManager, SLOT(poll()));
        connect(httpManager, SIGNAL(requestFinished()), pollTimer, SLOT(start()));
        connect(httpManager, SIGNAL(newJob(Job*)), tray, SLOT(onNewJob(Job*)));
        connect(httpManager, SIGNAL(jobUpdated(QString)), tray, SLOT(onJobUpdate(QString)));
        connect(httpManager, SIGNAL(jobDeleted(QString)), tray, SLOT(onJobDeleted(QString)));
        connect(httpManager, SIGNAL(connectionProblem()), tray, SLOT(connectionLost()));
        connect(httpManager, SIGNAL(agentReached()), this, SLOT(agentReached()));
        connect(httpManager, SIGNAL(noActiveJobsAtLaunch()), this, SLOT(show()));
        connect(httpManager, SIGNAL(jobsCleared()), tray, SLOT(jobsCleared()));
        connect(httpManager, SIGNAL(webUI404()), this, SLOT(notFoundFromPython()));
        connect(httpManager, SIGNAL(noInternetConnection()), tray, SLOT(noInternetConnection()));
        connect(httpManager, SIGNAL(internetConnectionOk()), tray, SLOT(internetConnectionOk()));
        connect(httpManager, SIGNAL(connectionProblem()), this, SLOT(connectionLost()));
        connect(httpManager, SIGNAL(jobNotifyMessage(QString,QString,QString)), tray, SLOT(notificationReceived(QString,QString,QString)));

        connect(tray, SIGNAL(about()), this, SLOT(about()));
        connect(tray, SIGNAL(pauseSync()), httpManager, SLOT(pauseSync()));
        connect(tray, SIGNAL(resumeSync()), httpManager, SLOT(resumeSync()));
        connect(tray, SIGNAL(quit()), this, SLOT(cleanQuit()));
        connect(tray, SIGNAL(launchAgentSignal()), cmdHelper, SLOT(launchAgentProcess()));
//        connect(cmdHelper, SIGNAL(winAgentLaunched()), this, SLOT(show()));

        settingsWebView = new QWebView();

        jsDialog = new JSEventHandler(this);

        portConfigurer->updatePorts();
        httpManager->setUrl(AGENT_SERVER_URL + portConfigurer->port(), portConfigurer->username(), portConfigurer->password());
        httpManager->poll();

        //this->setWindowFlags(Qt::Tool);
        setWindowTitle(PYDIO_DATA_DIR);
        setWindowIcon(QIcon(":/images/PydioSync-Systray-Mac.png"));
    }
}
Example #18
0
void viewlens::on_deleteButton_clicked()
{
    int flag=0;

    ifstream lensin;

    lensin.open("lens.dat",ios::binary);

    ofstream temp;

    temp.open("temp.dat",ios::binary);

    while(lensin.read((char*)&lensVariable,sizeof(lensVariable)))

    {

        if(strcmp(lensVariable.cIol,ui->tableWidget->item(ui->tableWidget->currentRow(),0)->text().toStdString().c_str())==0)

        {
            flag++;

        }

        else

            temp.write((char*)&lensVariable,sizeof(lensVariable));

    }

    lensin.close();

    temp.close();

    if(flag==0)
    {
        pa=new prompta("Record not found!",this);

        pa->move(300,200);

        QTimer *msgBoxCloseTimer = new QTimer(this);

        msgBoxCloseTimer->setInterval(3000);

        msgBoxCloseTimer->setSingleShot(true);

        connect(msgBoxCloseTimer, SIGNAL(timeout()), pa, SLOT(reject())); // or accept()

        msgBoxCloseTimer->start();

        pa->exec();

    }
    else
    {
        QFile file("lens.dat");

        QFile file1("temp.dat");

        file.remove();

        file1.rename("lens.dat");

        pa=new prompta("Record deleted succesfully!",this);

        pa->move(300,200);

        pa->show();

        QTimer *msgBoxCloseTimer = new QTimer(this);

        msgBoxCloseTimer->setInterval(3000);

        msgBoxCloseTimer->setSingleShot(true);

        connect(msgBoxCloseTimer, SIGNAL(timeout()), pa, SLOT(reject())); // or accept()

        msgBoxCloseTimer->start();

        pa->exec();

        this->done(QDialog::Accepted);


    }



}
ChineseCalendar::ChineseCalendar(QWidget *parent)
    : QWidget(parent)
{
    setupUi(this); m_strFileList.clear();
//    bg = new QPixmap(":/img/chinesecalendarBGyellow.png");
    icon = QIcon(":/img/icon.png");
    icon64 = QIcon(":/img/chinesecalendar-64.png");

    mycalendat=new CCBO;
    mycalendat->InitConnection(QDir::currentPath ());
    selectedDate = QDate::currentDate();
	monthCombo->setCurrentIndex(selectedDate.month() - 1);
    YearSelect->setCurrentIndex(selectedDate.year()-1900);

    connect(monthCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setMonth(int)));
    connect(monthCombo, SIGNAL(activated(int)), this, SLOT(setMonth(int)));
    connect(YearSelect, SIGNAL(currentIndexChanged(int)), this, SLOT(setYear(int)));
    connect(this->backtotoday, SIGNAL(clicked()), this, SLOT(backtoday()));

//    this->TbnextMonth->setStyleSheet("QPushButton{background-color:transparent;color:rgb(200,200,150);}QPushButton:hover{color:rgb(255,255,255);}");
//    this->TbnextYear->setStyleSheet("QPushButton{background-color:transparent;color:rgb(200,200,150);}QPushButton:hover{color:rgb(255,255,255);}");
//    this->TbpreviousMonth->setStyleSheet("QPushButton{background-color:transparent;color:rgb(200,200,150);}QPushButton:hover{color:rgb(255,255,255);}");
//    this->TbpreviousYear->setStyleSheet("QPushButton{background-color:transparent;color:rgb(200,200,150);}QPushButton:hover{color:rgb(255,255,255);}");
//    this->backtotoday->setStyleSheet("QPushButton{background-color:transparent;color:rgb(200,200,150);}QPushButton:hover{color:rgb(255,255,255);}");
//    this->YearSelect->setStyleSheet("QComboBox{border: 2px solid lightgray;border-radius: 5px;font:12pt;}");
//    this->monthCombo->setStyleSheet("QComboBox{border: 2px solid lightgray;border-radius: 5px;font:12pt;}");
//    this->label->setStyleSheet("QLabel{font:12pt;}");
//    this->label_2->setStyleSheet("QLabel{font:12pt;}");

    QString week;
    QDateTime dateTime = QDateTime::currentDateTime();

    if (dateTime.toString("ddd") == "Mon")
        week = "星期一"; // Monday
    else if (dateTime.toString("ddd") == "Tue")
        week = "星期二"; // Tuesday
    else if (dateTime.toString("ddd") == "Wed")
        week = "星期三"; // Wednesday
    else if (dateTime.toString("ddd") == "Thu")
        week = "星期四"; // Thursday
    else if(dateTime.toString("ddd") == "Fri")
        week = "星期五"; // Friday
    else if (dateTime.toString("ddd") == "Sat")
        week = "星期六"; // Saturday
    else
        week = "星期日"; // Sunday

    QString currentTime = dateTime.toString("yyyy-MM-dd %1").arg(week);
    QDate day = QDate::currentDate();
    struct CCalendar datebase;
    mycalendat->ctcl_solar_to_lunar(day.year(),day.month(),day.day(),&datebase);
    QString chinesemonth = datebase.cmonth;

    if (chinesemonth == "一月")
        chinesemonth = "正月";
    if (chinesemonth == "十一月")
        chinesemonth = "冬月";
    if (chinesemonth == "十二月")
        chinesemonth = "腊月";

    QString chineseday = QString("农历 %1%2").arg(chinesemonth).arg(datebase.cday);
    QString chineseyear = QString("%1年(%2年)").arg(datebase.ganzhi).arg(datebase.shengxiao);

    QString chineseyi = QString("%1").arg(datebase.yi);
    QStringList chineseyilist = chineseyi.split("、");
    QString chineseji = QString("%2").arg(datebase.ji);
    QStringList chinesejilist = chineseji.split("、");

    QFont font;
    QPalette pa;
    font.setPointSize(48);
    font.setBold(true);
    this->label_10->setFont(font);
    this->label_10->setText(QString::number(day.day()));
    font.setBold(false);
    font.setPointSize(9);
    this->label_12->setFont(font);
    this->label_12->setText(currentTime);
    font.setPointSize(10);
    this->label_13->setFont(font);
    this->label_13->setText(chineseday);
    this->label_14->setFont(font);
    this->label_14->setText(chineseyear);
    font.setPointSize(15);
    this->label_15->setFont(font);
    font.setPointSize(10);
    this->label_17->setFont(font);
    this->label_18->setFont(font);

    QString yi=QString("");
    QString ji=QString("");
    if(chineseyilist.count() == 0 )
       yi =QString("");
    if(chineseyilist.count() >= 5)
       yi = QString("").append(chineseyilist.at(0)).append("\n").append(chineseyilist.at(1)).append("\n").append(chineseyilist.at(2)).append("\n").append(chineseyilist.at(3)).append("\n").append(chineseyilist.at(4));
    if(chineseyilist.count() == 4)
       yi = QString("").append(chineseyilist.at(0)).append("\n").append(chineseyilist.at(1)).append("\n").append(chineseyilist.at(2)).append("\n").append(chineseyilist.at(3));
    if (chineseyilist.count() == 3)
       yi = QString("").append(chineseyilist.at(0)).append("\n").append(chineseyilist.at(1)).append("\n").append(chineseyilist.at(2));
    if (chineseyilist.count() == 2)
       yi = QString("").append(chineseyilist.at(0)).append("\n").append(chineseyilist.at(1));
    if (chineseyilist.count() == 1)
       yi = QString("").append(chineseyilist.at(0)).append("\n");
    this->label_17->setText(yi);

    if(chinesejilist.count() == 0 )
       ji =QString("");
    if(chinesejilist.count() >= 5)
       ji = QString("").append(chinesejilist.at(0)).append("\n").append(chinesejilist.at(1)).append("\n").append(chinesejilist.at(2)).append("\n").append(chinesejilist.at(3)).append("\n").append(chinesejilist.at(4));
    if(chinesejilist.count() == 4)
       ji = QString("").append(chinesejilist.at(0)).append("\n").append(chinesejilist.at(1)).append("\n").append(chinesejilist.at(2)).append("\n").append(chinesejilist.at(3));
    if (chinesejilist.count() == 3)
       ji = QString("").append(chinesejilist.at(0)).append("\n").append(chinesejilist.at(1)).append("\n").append(chinesejilist.at(2));
    if (chinesejilist.count() == 2)
       ji = QString("").append(chinesejilist.at(0)).append("\n").append(chinesejilist.at(1));
    if (chinesejilist.count() == 1)
       ji = QString("").append(chinesejilist.at(0)).append("\n");
    this->label_18->setText(ji);

    QString cnote=mycalendat->ctcl_displaydata(day.year(),day.month(),day.day());
    QString haveplan=QString("今日有行程安排");
    QString noplan=QString("今日无行程安排");
    int num = cnote.count();
    while (num > 0 && cnote.at(num-1).isSpace())
    {
        num--;
    }

    if(cnote.isEmpty() || num == 0)
        this->label_19->setText(noplan);
    else
        this->label_19->setText(haveplan);

    pa.setColor(QPalette::WindowText,Qt::white);
    this->label->setPalette(pa);
    this->label_2->setPalette(pa);
    this->label_15->setPalette(pa);
    this->label_4->setPalette(pa);
    this->label_5->setPalette(pa);
    this->label_6->setPalette(pa);
    this->label_7->setPalette(pa);
    this->label_8->setPalette(pa);

    pa.setColor(QPalette::WindowText,QColor(255,255,255));
    this->label_3->setPalette(pa);
    this->label_9->setPalette(pa); 

    pa.setColor(QPalette::WindowText,Qt::black);
    this->label_18->setPalette(pa);

    pa.setColor(QPalette::WindowText,QColor(235,74,20));
    this->label_10->setPalette(pa);
    this->label_12->setPalette(pa);
    this->label_13->setPalette(pa);
    this->label_14->setPalette(pa);

    pa.setColor(QPalette::WindowText,Qt::white);
    this->label_19->setPalette(pa);

    pa.setColor(QPalette::WindowText,Qt::red);
    this->label_11->setPalette(pa);
    this->label_17->setPalette(pa);

    map = new QMap<QString, DateItem *>();

    for (int i = 1; i <= 6; i++)
    {
        for (int j = 1; j <= 7; j++)
        {
            DateItem *dateitem = new DateItem(this);
            if (i <= 5)
            {
                dateitem->show();
            }
            else
            {
                dateitem->hide();
            }

            map->insert(QString("%1-%2").arg(i).arg(j), dateitem);

            if ((i < 6) || (i == 6 && (j == 1 || j == 2)))
            {
                connect(dateitem, SIGNAL(clicked(QString)), this, SLOT(resetcalendardate(QString)));
                connect(dateitem, SIGNAL(day(QString)), this, SLOT(setclickday(QString)));
                connect(dateitem, SIGNAL(resetColor()), this, SLOT(resetDateItemColor()));
            }
        }
    }

    setItemLayout();
    setCalendar();

    QTimer *timer = new QTimer(this);
    timer->setInterval(1000);
    connect(timer,SIGNAL(timeout()),this,SLOT(setTime()));
    timer->start();

    QBitmap objBitmap(size());
    QPainter painter(&objBitmap);
    painter.fillRect(rect(),Qt::white);
    painter.setBrush(QColor(0,0,0));
    painter.drawRoundedRect(this->rect(),10,10);
    setMask(objBitmap);

    aboutDlg = new AboutDialog();
    aboutDlg->hide();

    this->createTray();

    note = new Cnote;
    QDesktopWidget desktop;
    int width = desktop.screenGeometry().width();
    note->setGeometry(QRect(width-400,80,224,280));
    connect(note,SIGNAL(save(QString)),this,SLOT(savedata(QString)));
    note->hide();
}
Example #20
0
Window::Window(testApp * _app)
{
	
	QWidget * content = new QWidget();

	ofApp = _app;
//	tab = new QTabWidget;
	viewCombo = new QComboBox();

    glWidget = new GLWidget(ofApp);
	glWidget->setFixedWidth(500);
	glWidget->setFixedHeight(500);
	
//	content->setFixedWidth(500);
//	content->setFixedHeight(500);
	
	glWidget->viewCombo = viewCombo;
	
	QTimer *timer = new QTimer(this);
    timer->setInterval(20);
	QObject::connect(timer, SIGNAL(timeout()), glWidget, SLOT(update()));
	QObject::connect(timer, SIGNAL(timeout()), glWidget, SLOT(updateGL()));
	timer->start();
	
    setWindowTitle(tr("Illutron Robot"));
	
	QTimer *settingsTimer = new QTimer(this);
    settingsTimer->setInterval(1000);
	QObject::connect(settingsTimer, SIGNAL(timeout()), this, SLOT(saveSettings()));
	settingsTimer->start();


	
	
	//GENERAL SETTINGS TAB
	QLabel *fpsLabel = new QLabel(tr("FPS"));
	
	QWidget *settingsGroupBox = new QWidget();
	QGridLayout *settingsGrid = new QGridLayout;
	settingsGrid->setAlignment(Qt::AlignTop);
	settingsGrid->addWidget(new QLabel(tr("FPS:")), 0, 0);
	settingsGrid->addWidget(fpsLabel, 0,1);
	settingsGrid->setColumnStretch(1,20);
	settingsGroupBox->setLayout(settingsGrid);
	
	//tab->addTab(settingsGroupBox, "General");
	
	/*
	QDockWidget *dockWidget = new QDockWidget(tr("General"), this);
	dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea |
								Qt::RightDockWidgetArea);
	dockWidget->setWidget(settingsGroupBox);*/
	//addDockWidget(Qt::RightDockWidgetArea, dockWidget);
	
	setTabPosition(Qt::RightDockWidgetArea,QTabWidget::East);

	
	

	//SETUP MAIN LAYOUT
    QHBoxLayout *mainLayout = new QHBoxLayout;
	QWidget *glGroupBox = new QWidget();
	QVBoxLayout *glLayout = new QVBoxLayout;
	
	
	glGroupBox->setLayout(glLayout);
	glLayout->addWidget(viewCombo);
	glLayout->addWidget(glWidget);
	glLayout->setAlignment(Qt::AlignTop);
	
	mainLayout->addWidget(glGroupBox);
//	mainLayout->addWidget(tab);
	
    content->setLayout(mainLayout);
	
	setCentralWidget(content);
	
	
	//GENERAL EVENT CONNECTIONS
	//connect(xSlider, SIGNAL(valueChanged(int)), glWidget, SLOT(setXRotation(int))); //This line connects the x slider to the testApp
   // connect(rotateSlider, SIGNAL(valueChanged(int)), glWidget, SLOT(setRotateSlider(int)));
	connect(glWidget, SIGNAL(frameRateChanged(double)), fpsLabel, SLOT(setNum(double)));
	//connect(tabLayout, SIGNAL(valueChanged(int)), glWidget, SLOT(setXRotation(int)));

	settings = new QSettings("BrandtsRobot", "Illutron");
	
	setUnifiedTitleAndToolBarOnMac(true);
	
	lock = new QAction(QIcon(QString(ofToDataPath("lock.png", true).c_str())), tr("Lock"),this);
	lock->setShortcut( QKeySequence(Qt::ControlModifier + Qt::Key_L));

	QObject::connect(lock, SIGNAL(triggered()), this, SLOT(toggleLock()));

	toolbar = addToolBar(tr("Toolbar"));
	setIconSize(QSize(20,20));
	toolbar->addAction(lock);
	statusBar()->showMessage(tr("Locked"));
	
	setDockOptions(QMainWindow::AnimatedDocks | QMainWindow::AllowTabbedDocks | QMainWindow::AllowNestedDocks);

}
Example #21
0
QssEditor::QssEditor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QssEditor),
    m_changed(false)
{
    ui->setupUi(this);

    // some default values
    QHash<QString, QVariant> defaultValues;

    defaultValues.insert(SETTING_PREVIEW_DELAY, 750);

    Settings::instance()->addDefaultValues(defaultValues);

    resetWindowTitle();

    // icons
    ui->toolOpen->setIcon(QIcon::fromTheme("document-open", QIcon(":/images/open.png")));
    ui->toolSave->setIcon(QIcon::fromTheme("document-save", QIcon(":/images/save.png")));
    ui->toolSaveAs->setIcon(QIcon::fromTheme("document-save-as", QIcon(":/images/saveas.png")));
    ui->toolClose->setIcon(QIcon::fromTheme("window-close", QIcon(":/images/close.png")));
    ui->toolUndo->setIcon(QIcon::fromTheme("edit-undo", QIcon(":/images/undo.png")));
    ui->toolRedo->setIcon(QIcon::fromTheme("edit-redo", QIcon(":/images/redo.png")));
    ui->toolOptions->setIcon(QIcon::fromTheme("preferences-system", QIcon(":/images/options.png")));

    // application shortcuts
    new QShortcut(QKeySequence::Quit, this, SLOT(slotQuit()));
    new QShortcut(QKeySequence::Find, this, SLOT(slotFind()));
    new QShortcut(QKeySequence::FindNext, this, SLOT(slotFindNext()));
    new QShortcut(QKeySequence::HelpContents, this, SLOT(slotAbout()));

    // shortcuts
    ui->toolOpen->setShortcut(QKeySequence::Open);
    ui->toolSave->setShortcut(QKeySequence::Save);
    ui->toolSaveAs->setShortcut(QKeySequence::SaveAs);
    ui->toolClose->setShortcut(QKeySequence::Close);

    // built-in Qt icon
    ui->toolAboutQt->setIcon(QIcon(
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    ":/qt-project.org/qmessagebox/images/qtlogo-64.png"
#else
    ":/trolltech/qmessagebox/images/qtlogo-64.png"
#endif
                                 ));

    // menu for toolbutton
    QMenu *toolButtonMenu = new QMenu(this);
    toolButtonMenu->addAction("Item1");
    toolButtonMenu->addSeparator();
    toolButtonMenu->addAction("Item2");
    ui->toolButton->setMenu(toolButtonMenu);

    m_timerDelayedApply = new QTimer(this);
    m_timerDelayedApply->setSingleShot(true);
    connect(m_timerDelayedApply, SIGNAL(timeout()), this, SLOT(slotApplyCss()));
    resetPreviewDelay();

    QTimer *timerProgress = new QTimer(this);
    timerProgress->setInterval(500);
    connect(timerProgress, SIGNAL(timeout()), this, SLOT(slotProgress()));
    timerProgress->start();

    ui->splitter->setCollapsible(0, false);
    ui->splitter->setStretchFactor(0, 1);

    // splitter size
    QList<int> list = QList<int>() << width()/2 << width()/2;
    ui->splitter->setSizes(list);

    // some MDI windows
    QMdiSubWindow *mdi = ui->mdiArea->addSubWindow(new QLabel("MDI", ui->mdiArea));
    mdi->resize(160, 80);

#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    ui->tree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
    ui->tree->header()->setResizeMode(QHeaderView::ResizeToContents);
    ui->table->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
#endif

    ui->tree->topLevelItem(0)->setExpanded(true);

    ui->text->setCaretLineVisible(true);
    ui->text->setCaretLineBackgroundColor(QColor("gainsboro"));

    ui->text->setAutoIndent(true);
    ui->text->setIndentationGuides(false);
    ui->text->setIndentationsUseTabs(true);
    ui->text->setIndentationWidth(4);

    ui->text->setMarginsBackgroundColor(QColor("gainsboro"));
    ui->text->setMarginLineNumbers(1, true);
    ui->text->setMarginWidth(1, 50);

    ui->text->setAutoCompletionSource(QsciScintilla::AcsAll);
    ui->text->setAutoCompletionReplaceWord(true);
    ui->text->setAutoCompletionCaseSensitivity(false);
    ui->text->setAutoCompletionUseSingle(QsciScintilla::AcusAlways);
    ui->text->setAutoCompletionThreshold(0);

    ui->text->setBraceMatching(QsciScintilla::SloppyBraceMatch);
    ui->text->setMatchedBraceBackgroundColor(Qt::yellow);
    ui->text->setUnmatchedBraceForegroundColor(Qt::blue);

    // QSS lexer
    QsciLexerQSS *lexQss = new QsciLexerQSS(this);
    ui->text->setLexer(lexQss);

    ui->text->setFocus();
    ui->text->installEventFilter(this);

    restoreLastFiles();

    QTimer::singleShot(0, this, SLOT(slotDelayedOpen()));
}
Example #22
0
int
main(int argc, char *argv[]) {
    // Let logx get and strip out its arguments
    logx::ParseLogArgs(argc, argv);
    
    // Instantiate our QCoreApplication
    App = new QCoreApplication(argc, argv);

    // XML-RPC server port number
    static const int DEFAULT_XMLRPC_PORT = HCREXECUTIVE_PORT;
    int xmlrpcPortNum;
    
    // procmap instance name
    std::string instanceName;

    // Get HcrExecutive's options
    po::options_description opts("Options");
    opts.add_options()
        ("help,h", "Describe options")
        ("instance,i",
                po::value<std::string>(&instanceName)->default_value("ops"),
                "instance name for procmap connection")
        ("xmlrpcPortNum,x",
                po::value<int>(&xmlrpcPortNum)->default_value(DEFAULT_XMLRPC_PORT),
                "XML-RPC server port number")
        ;
    bool argError = false;
    po::variables_map vm;
    try {
        po::store(po::command_line_parser(argc, argv).options(opts).run(), vm);
        po::notify(vm);
    } catch (...) {
        argError = true;
    }

    // Give usage information and exit if 1) help was requested, or 2) there
    // is an argument error
    if (vm.count("help") || argError) {
        std::cout << "Usage: " << argv[0] <<
                  " [OPTION]..." << std::endl;
        std::cout << opts << std::endl;
        exit(1);
    }
    
    // Initialize registration with procmap if instance is specified
    if (instanceName.size() > 0) {
        PMU_auto_init("HcrExecutive", instanceName.c_str(), PROCMAP_REGISTER_INTERVAL);
        ILOG << "Initializing procmap registration as instance '" << 
                instanceName << "'";
    }

    ILOG << "HcrExecutive (" << getpid() << ") started";

    PMU_auto_register("initializing");

    // Initialize our RPC server
    xmlrpc_c::registry myRegistry;
    myRegistry.addMethod("getStatus", new GetStatusMethod);
    myRegistry.addMethod("setApsValveControl", new SetApsValveControlMethod);
    myRegistry.addMethod("setRequestedHmcMode", new SetRequestedHmcModeMethod);
    myRegistry.addMethod("setHvRequested", new SetHvRequestedMethod);
    QXmlRpcServerAbyss rpcServer(&myRegistry, xmlrpcPortNum);
    
    // Start a thread to get HcrPmc730Daemon status on a regular basis.
    HcrPmc730StatusThread hcrPmc730StatusThread("localhost",
                                                HCRPMC730DAEMON_PORT);
    QObject::connect(App, SIGNAL(aboutToQuit()),
                     &hcrPmc730StatusThread, SLOT(quit()));
    hcrPmc730StatusThread.start();
    
    // Start a thread to get MotionControlDaemon status on a regular basis
    MotionControlStatusThread mcStatusThread("localhost",
                                             MOTIONCONTROLDAEMON_PORT);
    QObject::connect(App, SIGNAL(aboutToQuit()), &mcStatusThread, SLOT(quit()));
    mcStatusThread.start();
    
    // MaxPowerFmqClient instance
    MaxPowerFmqClient maxPowerClient("fmqp://localhost/tmp/fmq/max_power/wband/shmem_15000");
    QObject::connect(App, SIGNAL(aboutToQuit()), &maxPowerClient, SLOT(quit()));
    
    // Instantiate the object which will monitor pressure and control the
    // Active Pressurization System (APS)
    TheApsControl = new ApsControl(hcrPmc730StatusThread);
    
    // Instantiate the object which will implement safety monitoring for the
    // transmitter
    TheTransmitControl = new TransmitControl(hcrPmc730StatusThread, 
                                             mcStatusThread,
                                             maxPowerClient);
    
    // catch a control-C or kill to shut down cleanly
    signal(SIGINT, sigHandler);
    signal(SIGTERM, sigHandler);
 
    // Set up a timer to periodically register with PMU so it knows we're still
    // alive.
    QTimer registrationTimer;
    registrationTimer.setInterval(REGISTRATION_INTERVAL_SECS * 1000);   // interval in ms
    QFunctionWrapper registrationFuncWrapper(updateRegistration);
    QObject::connect(&registrationTimer, SIGNAL(timeout()),
            &registrationFuncWrapper, SLOT(callFunction()));
    registrationTimer.start();

    // Set up a timer to log status information occasionally
    QTimer statusTimer;
    statusTimer.setInterval(LOG_STATUS_INTERVAL_SECS * 1000);
    QFunctionWrapper statusFuncWrapper(logStatus);
    QObject::connect(&statusTimer, SIGNAL(timeout()),
            &statusFuncWrapper, SLOT(callFunction()));
    statusTimer.start();
    
    // Now just run the application until somebody or something interrupts it
    try {
        App->exec();
    } catch (std::exception & e) {
        ELOG << "Application stopped on exception: " << e.what();
    } catch (...) {
        ELOG << "Application stopped on unknown exception";
    }

    // Unregister with procmap
    PMU_auto_unregister();

    // Clean up before exit
    delete(TheTransmitControl);
    delete(TheApsControl);

    // Wait up to 1/2 second (max) for all of our threads to finish
    int maxWaitMsecs = 500;
    QDateTime giveUpTime(QDateTime::currentDateTime().addMSecs(maxWaitMsecs));
    if (! mcStatusThread.wait(QDateTime::currentDateTime().msecsTo(giveUpTime))) {
        WLOG << "mcStatusThread is still running at exit";
    }
    if (! hcrPmc730StatusThread.wait(QDateTime::currentDateTime().msecsTo(giveUpTime))) {
        WLOG << "hcrPmc730StatusThread is still running at exit";
    }

    ILOG << "HcrExecutive (" << getpid() << ") exiting";

    return 0;
} 
Example #23
0
void Tunneld::promiseChannelCleanup(ToxTunChannel *chan)
{
    qDebug()<<chan<<sender();
    QObject *snderobj = (QObject*)sender();
    QTimer *repeat_timer = NULL;

    qDebug()<<snderobj->objectName()<<snderobj->metaObject()->className();
    if (chan == NULL) {
        repeat_timer = (QTimer*)snderobj;
        assert(repeat_timer != NULL);
        int conid = repeat_timer->property("conid").toInt();
        if (!m_conid_chans.contains(conid)) {
            qDebug()<<"maybe too late repeat check self sock close timer event";
            repeat_timer->deleteLater();
            return;
        }
        chan = m_conid_chans[conid];
        assert(chan != NULL);
    } else {
        // snderobj is ENetPoll or QTcpSocket
    }
    QTcpSocket *sock = chan->m_sock;
    ENetPeer *enpeer = chan->m_enpeer;

    //////////
    QHash<QString, bool> promise_results;

    promise_results["sock_closed"] = chan->sock_closed;
    // promise_results["enet_closed"] = chan->enet_closed;
    promise_results["peer_sock_closed"] = chan->peer_sock_closed;

    bool promise_result = true;
    for (auto it = promise_results.begin(); it != promise_results.end(); it ++) {
        QString key = it.key();
        bool val = it.value();
        promise_result = promise_result && val;
    }

    if (true) {
        // 检测对方最近的回包情况
        if (!promise_result && repeat_timer == NULL
            && promise_results["peer_sock_closed"] && !promise_results["sock_closed"]) {
            qDebug()<<"here";
            if (chan->last_recv_peer_pkt_time == QDateTime()) {
                qDebug()<<"maybe can close socket right now, because recv nothing forever";
            }
            
            QTimer *t = new QTimer();
            t->setInterval(500);
            t->setSingleShot(true);
            t->setProperty("conid", QVariant(chan->m_conid));
            // // QObject::connect(t, &QTimer::timeout, this, &Tunneld::promiseChannelCleanup, Qt::QueuedConnection);
            QObject::connect(t, SIGNAL(timeout()), this, SLOT(promiseChannelCleanup()), Qt::QueuedConnection);
            qDebug()<<"start repeat check sock close timer:";
            t->start();
        }
        if (!promise_result && repeat_timer != NULL
            && promise_results["peer_sock_closed"] && !promise_results["sock_closed"]) {
            //
            QDateTime now_time = QDateTime::currentDateTime();
            uint32_t last_recv_to_now_time = chan->last_recv_peer_pkt_time.msecsTo(now_time);
            qDebug()<<"here:"<<last_recv_to_now_time<<enpeer->lastReceiveTime;
            if (last_recv_to_now_time > 7000) {
                qDebug()<<"last recv to now, force close self socket:"<<last_recv_to_now_time
                        <<enpeer->incomingPeerID<<enpeer->outgoingPeerID;
                // 不能直接关闭,要在当前函数执行完后,即下一次事件的时候开始执行。
                QTimer::singleShot(1, sock, &QTcpSocket::close);
                // QTimer *t = new QTimer();
                // t->setSingleShot(true);
                // QObject::connect(t, &QTimer::timeout, sock, &QTcpSocket::close, Qt::QueuedConnection);
                // t->start(1);
                
                repeat_timer->deleteLater();
            } else {
                repeat_timer->start();
            }
        }
    }
    
    if (!promise_result) {
        qDebug()<<"promise nooooot satisfied:"<<promise_results<<chan->m_conid;
        return;
    }
    
    chan->promise_close_time = QDateTime::currentDateTime();
    qDebug()<<"promise satisfied."<<chan->m_conid;

    ///// do cleanup
    bool force_closed = chan->force_closed;
    
    // enpeer->toxchan = NULL;  // cleanup
    peerRemoveChan(enpeer, chan);
    
    this->m_sock_chans.remove(sock);
    // this->m_enpeer_chans.remove(enpeer);
    this->m_conid_chans.remove(chan->m_conid);

    delete chan;
    sock->disconnect();
    sock->deleteLater();
    if (repeat_timer != NULL) repeat_timer->deleteLater();
    qDebug()<<"curr chan size:"<<this->m_sock_chans.count()<<this->m_conid_chans.count();

    if (force_closed) {
        return;
    }

    // 延时关闭enet_peer
    QTimer *t = new QTimer();
    auto later_close_timeout = [enpeer, t]() {
        qDebug()<<enpeer<<enpeer->state;
        if (enpeer->state != ENET_PEER_STATE_CONNECTED) {
            qDebug()<<"warning, peer currently not connected:"<<enpeer->incomingPeerID;
        }

        if (! (enet_list_empty (& enpeer -> outgoingReliableCommands) &&
               enet_list_empty (& enpeer -> outgoingUnreliableCommands) && 
               enet_list_empty (& enpeer -> sentReliableCommands))) {
            qDebug()<<"warning, maybe has unsent packet:"<<enpeer->incomingPeerID;
        }

        qDebug()<<"last recv time:"<<enpeer->incomingPeerID
        <<enetx_time_diff(enpeer->lastReceiveTime, enet_time_get());

        qDebug()<<"restore peer timeout, ping interval";
        enet_peer_timeout(enpeer, ENET_PEER_TIMEOUT_LIMIT*2,
                          ENET_PEER_TIMEOUT_MINIMUM*2, ENET_PEER_TIMEOUT_MAXIMUM*2);
        enet_peer_ping_interval(enpeer, ENET_PEER_PING_INTERVAL*2);

        // enet_peer_disconnect_now(enpeer, qrand());
        enet_peer_disconnect_later(enpeer, qrand());
        t->deleteLater();
    };

    qDebug()<<"last recv time:"<<enpeer->incomingPeerID
            <<enetx_time_diff(enpeer->lastReceiveTime, enet_time_get());
    // QTimer::singleShot(5678, later_close_timeout);
    t->setInterval(5678);
    t->setSingleShot(true);
    QObject::connect(t, &QTimer::timeout, later_close_timeout);
    t->start();
}
Example #24
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    //управление шасси
    nam = new QNetworkAccessManager(this);
    ui->setupUi(this);

    connect(ui->forwardButton,SIGNAL(pressed()),this,SLOT(forvard()));
    connect(ui->forwardButton,SIGNAL(released()),this,SLOT(stop()));

    connect(ui->backButton,SIGNAL(pressed()),this,SLOT(back()));
    connect(ui->backButton,SIGNAL(released()),this,SLOT(stop()));

    connect(ui->rightUpButton,SIGNAL(pressed()),this,SLOT(rightUp()));
    connect(ui->rightUpButton,SIGNAL(released()),this,SLOT(stop()));

    connect(ui->rightDwButton,SIGNAL(pressed()),this,SLOT(rightDw()));
    connect(ui->rightDwButton,SIGNAL(released()),this,SLOT(stop()));

    connect(ui->leftUpButton,SIGNAL(pressed()),this,SLOT(leftUp()));
    connect(ui->leftUpButton,SIGNAL(released()),this,SLOT(stop()));

    connect(ui->leftDwButton,SIGNAL(pressed()),this,SLOT(leftDw()));
    connect(ui->leftDwButton,SIGNAL(released()),this,SLOT(stop()));

    connect(ui->strafeLButton,SIGNAL(pressed()),this,SLOT(strafeL()));
    connect(ui->strafeLButton,SIGNAL(released()),this,SLOT(stop()));

    connect(ui->strafeRButton,SIGNAL(pressed()),this,SLOT(strafeR()));
    connect(ui->strafeRButton,SIGNAL(released()),this,SLOT(stop()));

    //вывод доступных портов
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
        ui->gpsname_comboBox->addItem(info.portName());


    // гдето тут функция получения настроек
    idmain ="0";
    portname ="ttyUSB0";
    statusURL ="http://192.168.1.66/status.xml";
    connector.idmain=idmain;

    //чтение порта
    timer.setSingleShot(true);
    connect(&serial, SIGNAL(readyRead()),this, SLOT(readRequest()));
    connect(&timer, SIGNAL(timeout()),this, SLOT(processTimeout()));

    startSlave(portname);

    //создаем объект для работы с БД
    connector.activateConnection();

    //настройка элемента выбора даты архива
    ui->timeNow->setMinimumDate(QDate::currentDate().addYears(-1));
    ui->timeNow->setMaximumDate(QDate::currentDate().addYears(5));
    ui->timeNow->setMinimumTime(QTime::currentTime().addSecs(-3600));
    ui->timeNow->setMaximumTime(QTime::currentTime().addSecs(3600));
    ui->timeNow->setDateTime(QDateTime::currentDateTime());
    ui->timeNow->setDisplayFormat("yyyy-MM-dd hh:mm:ss");

    //рисуем на слоях глобуса
    layer = new MyPaintLayer(ui->MarbleWidget);
    ui->MarbleWidget->addLayer(layer);
    ui->MarbleWidget->installEventFilter(layer);

    //отсечка прорисовки
    seconds.setInterval(1000);

    QObject::connect(&seconds, SIGNAL(timeout()), ui->MarbleWidget, SLOT(update()));
    QObject::connect(&seconds, SIGNAL(timeout()), SLOT( getStatusXML()));
    QObject::connect(&seconds, SIGNAL(timeout()), SLOT( sendALL()));

    QObject::connect(nam, SIGNAL(finished(QNetworkReply*)),
                     SLOT(StatusDownloaded(QNetworkReply*)));

    seconds.start();

 }
Example #25
0
ImageArea::ImageArea(const bool &isOpen, const QString &filePath, QWidget *parent) :
    QWidget(parent), mIsEdited(false), mIsPaint(false), mIsResize(false)
{
    setMouseTracking(true);

    mRightButtonPressed = false;
    mFilePath.clear();
    makeFormatsFilters();
    initializeImage();
    mZoomFactor = 1;

    mAdditionalTools = new AdditionalTools(this);

    mUndoStack = new QUndoStack(this);
    mUndoStack->setUndoLimit(DataSingleton::Instance()->getHistoryDepth());

    if(isOpen && filePath.isEmpty())
    {
        open();
    }
    else if(isOpen && !filePath.isEmpty())
    {
        open(filePath);
    }
    else
    {
        QPainter *painter = new QPainter(mImage);
        painter->fillRect(0, 0,
                          DataSingleton::Instance()->getBaseSize().width(),
                          DataSingleton::Instance()->getBaseSize().height(),
                          Qt::white);
        painter->end();

        resize(mImage->rect().right() + 6,
               mImage->rect().bottom() + 6);
    }

    QTimer *autoSaveTimer = new QTimer(this);
    autoSaveTimer->setInterval(DataSingleton::Instance()->getAutoSaveInterval() * 1000);
    connect(autoSaveTimer, SIGNAL(timeout()), this, SLOT(autoSave()));
    connect(mAdditionalTools, SIGNAL(sendNewImageSize(QSize)), this, SIGNAL(sendNewImageSize(QSize)));

    autoSaveTimer->start();

    SelectionInstrument *selectionInstrument = new SelectionInstrument(this);
    connect(selectionInstrument, SIGNAL(sendEnableCopyCutActions(bool)), this, SIGNAL(sendEnableCopyCutActions(bool)));
    connect(selectionInstrument, SIGNAL(sendEnableSelectionInstrument(bool)), this, SIGNAL(sendEnableSelectionInstrument(bool)));

    // Instruments handlers
    mInstrumentsHandlers.fill(0, (int)INSTRUMENTS_COUNT);
    mInstrumentsHandlers[CURSOR] = selectionInstrument;
    mInstrumentsHandlers[PEN] = new PencilInstrument(this);
    mInstrumentsHandlers[LINE] = new LineInstrument(this);
    mInstrumentsHandlers[ERASER] = new EraserInstrument(this);
    mInstrumentsHandlers[RECTANGLE] = new RectangleInstrument(this);
    mInstrumentsHandlers[ELLIPSE] = new EllipseInstrument(this);
    mInstrumentsHandlers[FILL] = new FillInstrument(this);
    mInstrumentsHandlers[SPRAY] = new SprayInstrument(this);
    mInstrumentsHandlers[MAGNIFIER] = new MagnifierInstrument(this);
    mInstrumentsHandlers[COLORPICKER] = new ColorpickerInstrument(this);
    mInstrumentsHandlers[CURVELINE] = new CurveLineInstrument(this);
    mInstrumentsHandlers[TEXT] = new TextInstrument(this);

    // Effects handlers
    mEffectsHandlers.fill(0, (int)EFFECTS_COUNT);
    mEffectsHandlers[NEGATIVE] = new NegativeEffect(this);
    mEffectsHandlers[GRAY] = new GrayEffect(this);
    mEffectsHandlers[BINARIZATION] = new BinarizationEffect(this);
    mEffectsHandlers[GAUSSIANBLUR] = new GaussianBlurEffect(this);
    mEffectsHandlers[GAMMA] = new GammaEffect(this);
    mEffectsHandlers[SHARPEN] = new SharpenEffect(this);
    mEffectsHandlers[CUSTOM] = new CustomEffect(this);
}
ModuleChain* ModuleChainFactory::fabricateModuleChain(CHAINTYPE chaintype, DataStreamTypes::TYPE datastreamtype, Device *dev)
{
    //chain
    ModuleChain *chain  = new ModuleChain();

    //set update intervall
    QTimer *timer = new QTimer();
    //callulate the timer intervall
    int frequenz = MODULE_UPDATE_FREQUENZY_IN_HZ;
    if(MODULE_UPDATE_FREQUENZY_IN_HZ<0||MODULE_UPDATE_FREQUENZY_IN_HZ>100)
    {
        frequenz = 50;
        qWarning(" ModuleChainFactory::fabricateModuleChain  MODULE_UPDATE_FREQUENZY_IN_HZ in an unnormal range, will set to 50");
    }
    int intervall = 1000 / frequenz;
    timer->setInterval(intervall);

    qDebug("ModuleChainFactory::fabricateModuleChain: will fabricate ModulChain of ModuleChainFactory::CHAINTYPE(%i) and DataStreamTypes::TYPE(%i)",chaintype, datastreamtype);

    //debug
    bool succ = false;

    //declerate the vid chain
    SourceVideo *vidSourc;
    DisplayVideo *vidDisplay;
    LoggerVideo *vidLogger;

    //declare the sensor chain
//    SourceSensor *senSourc;
//    DisplaySensor *senDisplay;
//    LoggerSensor *senLogger;

//    //declare the audio chain
//    SourceAudio *audSource;
//    DisplayAudio *audDisplay;
//    LoggerAudio *audLogger;

    switch(chaintype)
    {
        case TYPE_NORMAL:
                    switch(datastreamtype)
                    {
                        case DataStreamTypes::VIDEO:
                                                //init the objects
                                                vidSourc = new SourceVideo();
                                                vidDisplay = new DisplayVideo();
                                                vidLogger = new LoggerVideo();

                                                //gave the threads an own event queue
                                                vidSourc->moveToThread(vidSourc);

                                                //add the given device to the Source
                                                vidSourc->addDevice(dev);

                                                //call init after specify the cam sort
                                                vidSourc->init();

                                                //connect the signals, make a list
                                                // source -> display
                                                succ = QObject::connect(vidSourc, SIGNAL(sendData(DataFrame::SPtr)),
                                                                        vidDisplay, SLOT(receiveData(DataFrame::SPtr)));
                                                //check display -> logger
                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");

                                                succ = QObject::connect(vidDisplay, SIGNAL(sendData(DataFrame::SPtr)),
                                                                        vidLogger, SLOT(receiveData(DataFrame::SPtr)));
                                                //check
                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");

                                                //connect the timer -> source
                                                succ = QObject::connect(timer, SIGNAL(timeout()),
                                                                        vidSourc, SLOT(sendYourProcessedData()));
                                                //check
                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");



                                                //make the list
                                                chain->appendModule(vidSourc);
                                                chain->appendModule(vidDisplay);
                                                chain->appendModule(vidLogger);

                                                //new way start timer when run is called
                                                chain->addTimerReference(timer);

                                                //old way start timer in time
                                                //start the timer
                                                //timer->start();

                                                break;

//NOT USED HERE*********************************************************
//                        case DataStreamTypes::AUDIO:
//                                                qDebug("ModuleChainFactory::fabricateModuleChain CHAINTYPE::NORMAL DataStreamTypes::AUDIO  constructed");
//                                                //init the objects
//                                                audSource = new SourceAudio();
//                                                audDisplay = new DisplayAudio();
//                                                audLogger = new LoggerAudio();


//                                                //gave the threads an own event queue
//                                                audSource->moveToThread(audSource);

//                                                //add the given device to the Source
//                                                audSource->addDevice(dev);

//                                                //connect the signals, make a list
//                                                // source -> display
//                                                succ = QObject::connect(audSource, SIGNAL(sendData(DataFrame::SPtr)),
//                                                        audDisplay, SLOT(receiveData(DataFrame::SPtr)));
//                                                //check
//                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");

//                                                succ = QObject::connect(audDisplay, SIGNAL(sendData(DataFrame::SPtr)),
//                                                audLogger, SLOT(receiveData(DataFrame::SPtr)));
//                                                //check
//                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");

//                                                //connect the timer -> source
//                                                succ = QObject::connect(timer, SIGNAL(timeout()),
//                                                                        audSource, SLOT(sendYourProcessedData()));
//                                                //check
//                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");

//                                                //
//                                                //make the list
//                                                chain->appendModule(audSource);
//                                                chain->appendModule(audDisplay);
//                                                chain->appendModule(audLogger);

//                                                //new way start timer when run is called
//                                                chain->addTimerReference(timer);

//                                                break;
//                        case DataStreamTypes::SENSOR:
//                                                //init the objects
//                                                senSourc = new SourceSensor();
//                                                senDisplay = new DisplaySensor();
//                                                senLogger = new LoggerSensor();


//                                                //gave the threads an own event queue
//                                                senSourc->moveToThread(senSourc);

//                                                //add the given device to the Source
//                                                senSourc->addDevice(dev);

//                                                //connect the signals, make a list
//                                                // source -> display
//                                                succ = QObject::connect(senSourc, SIGNAL(sendData(DataFrame::SPtr)),
//                                                        senDisplay, SLOT(receiveData(DataFrame::SPtr)));
//                                                //check
//                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");

//                                                succ = QObject::connect(senDisplay, SIGNAL(sendData(DataFrame::SPtr)),
//                                                senLogger, SLOT(receiveData(DataFrame::SPtr)));
//                                                //check
//                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");

//                                                //connect the timer -> source
//                                                succ = QObject::connect(timer, SIGNAL(timeout()),
//                                                                        senSourc, SLOT(sendYourProcessedData()));
//                                                //check
//                                                if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");

//                                                //
//                                                //make the list
//                                                chain->appendModule(senSourc);
//                                                chain->appendModule(senDisplay);
//                                                chain->appendModule(senLogger);

//                                                //new way start timer when run is called
//                                                chain->addTimerReference(timer);

//                                                break;
//****************************************************************************
                        default:  qWarning("ModuleChainFactory::fabricateModuleChain unexpect parameter,DataStreamTypes::TYPE(%i)",datastreamtype);
                                  break;
                    }//end switch datastreamtype

                    break; // break normal

        case TYPE_SHORT:

            switch(datastreamtype)
            {
            //TODO see above   case TYPE_NORMAL to imagine how it works
            case DataStreamTypes::VIDEO:

                                    //init the objects
                                    vidSourc = new SourceVideo();
                                    vidLogger = new LoggerVideo();

                                    //gave the threads an own event queue
                                    vidSourc->moveToThread(vidSourc);

                                    //add the given device to the Source
                                    vidSourc->addDevice(dev);

                                    //call init after specify the cam sort
                                    vidSourc->init();


                                    //connect the signals, make a list
                                    // source -> display
                                    succ = QObject::connect(vidSourc, SIGNAL(sendData(DataFrame::SPtr)),
                                                            vidLogger, SLOT(receiveData(DataFrame::SPtr)));
                                    //check display -> logger
                                    if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");


                                    //connect the timer -> source
                                    succ = QObject::connect(timer, SIGNAL(timeout()),
                                                            vidSourc, SLOT(sendYourProcessedData()));
                                    //check
                                    if(!succ)qWarning("ModuleChainFactory::fabricateModuleChain error while connect the moduls");


                                    //make the list
                                    chain->appendModule(vidSourc);
                                    chain->appendModule(vidLogger);

                                    //new way start timer when run is called
                                    chain->addTimerReference(timer);


                break;
            default:  qWarning("ModuleChainFactory::fabricateModuleChain unexpect parameter, DataStreamTypes::TYPE(%i)",datastreamtype);
                break;
            }//end switch datastreamtype
        break; //SHORT end


        case TYPE_EXTRA:
        default:
            qWarning("ModuleChainFactory::fabricateModuleChain unexpect parameter, CHAINTYPE(%i)",chaintype);
            break;
    }

    return chain;
}
/*
 * The routeTcpMessage() receives messages from any TCP connection. The Daemon can be connected with server and deskApp at the same time, but it will know which connection received data.
 * Any message arrive by TCP must to have two parts. The first part defines the data size of the coming package (second part) and must to be an 8 bytes String (always 8 bytes).
 *
 * The algoritm works like this:
 * When some data arrive it verifies (using the hasPackage variable) if is the first part or the second one of the complete message;
 * If hasPackage is true then is especting the second part of the message, otherwise the dada just arrived is the size information.
 *
 * The information of size correspond to the size of the message package. So, when more data arrive it verifies if the size is greater than or equals to the expected size.
 * If true the message is all here and can go on, otherwise the message is coming and it will wait for more data.
 *
 * When all the message arrives it will interpret and route it (by message type) to the right way.
 *
 */
void RFIDMonitorDaemon::routeTcpMessage()
{
    QTcpSocket *connection = (QTcpSocket *) QObject::sender();

    static bool hasPackage = false;
    static quint64 packageSize = 0;

    if( ! hasPackage){

        if((quint64)connection->bytesAvailable() < sizeof(quint64))
            return;

        //    	m_tcpSocket->read((char *)&packageSize, sizeof(quint64));
        QString packageSizeStr(connection->read(sizeof(quint64)));
        packageSize = packageSizeStr.toULongLong();

        qDebug() <<  QString("Message = %1 - Size of coming package: %2").arg(packageSizeStr).arg(QString::number(packageSize));
        hasPackage = true;
    }

    if((quint64)connection->bytesAvailable() >=  packageSize){
        QByteArray data(connection->read(packageSize));

        json::NodeJSMessage nodeMessage;

        nodeMessage.read(QJsonDocument::fromJson(data).object());
        QString messageType(nodeMessage.type());

        qDebug() << QString("New Message Received: %1").arg(QString(data));


        if(messageType == "SYN-ALIVE"){

            tcpSendMessage(connection, buildMessage(m_configManager->identification(), "ACK-ALIVE").toJson());
            qDebug() << QString("New Message Received: %1").arg(messageType);
        }
        else if (messageType == "ACK-SYN") {

            QJsonObject obj(nodeMessage.jsonData());
            if(!obj.isEmpty()){
                m_configManager->setIdentification(obj);
            }

            bool statusDateTime = m_configManager->setDateTime(nodeMessage.dateTime());
            QJsonObject response = m_configManager->identification();
            response["success"] = QJsonValue(statusDateTime);

            tcpSendMessage(connection, buildMessage(response, "ACK").toJson());

            // Informe RFIDMonitor that server is now connected. Wait 2 seconds;
            if(connection->objectName() == "server"){
                isConnected = true;
                QTimer *timer = new QTimer();
                timer->setSingleShot(true);
                timer->setInterval(2000);
                connect(timer, &QTimer::timeout, [=](){
                    ipcSendMessage(buildMessage(QJsonObject(), "SYNC").toJson());
                    timer->deleteLater();
                });
                timer->start();
            }
        }else if (messageType == "GET-CONFIG") {
            tcpSendMessage(connection, buildMessage(m_configManager->currentConfig(), "CONFIG").toJson());

        }else if (messageType == "READER-COMMAND") {

            QJsonObject command(nodeMessage.jsonData());
            /*
             * When a 'reader command' message is received is because someone is sending a command to the reader. So it needs to send also who is doing this.
             * To perform this it uses a field called 'sender' that carry the name of who is sending the 'command message'.
             * And based on that, it will respond to the server connection or to the deskApp connection
             *
             * see reoutIcpMessage (messageType == "READER-RESPONSE")
             */
            if(connection->objectName() == "server")
                command.insert("sender", QString("server"));
            else
                command.insert("sender", QString("app"));

            ipcSendMessage(buildMessage(command, "READER-COMMAND").toJson());

        }else if (messageType == "NEW-CONFIG") {

            QJsonObject newConfig(nodeMessage.jsonData());
            bool ackConf;
            if(m_configManager->newConfig(newConfig))
            {
                // Send a message to stop the RFIDMonitor
                emit restartMonitor();
                ackConf = true;
            }else{
                ackConf = false;
            }
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(ackConf));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NEW-CONFIG").toJson());

            if(m_tcpAppSocket->isOpen())
                m_tcpAppSocket->close();

        }else if (messageType == "DATETIME") {

            QJsonObject dataObj;
            dataObj["success"] =  QJsonValue(m_configManager->setDateTime(nodeMessage.dateTime()));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK").toJson());

        }else if (messageType == "ACK-DATA") {
            // A ACK-DATA message means that the server is trying to inform the RFIDMonitor that some data is now synced. So, it just send this message to the RFIDMonitor.
            ipcSendMessage(data);

        }else if (messageType == "GET-NET-CONFIG") {
            // Only return the network configuration.
            tcpSendMessage(connection, buildMessage(m_configManager->netConfig(), "NET-CONFIG").toJson());

        }else if (messageType == "NEW-NET") {

            QJsonObject network = nodeMessage.jsonData();
            // Receive a new configuration for the network (ssid and password).
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(m_configManager->setNetConfig(network)));

            // returns a message ACK-NET to inform the sender that the new configuration was set
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NET").toJson());

            // Try to restar the network service to already use the new configuration
            bool resetNet = m_configManager->restartNetwork();
            qDebug() <<  QString(resetNet? "Network restarted" : "Networkt Don't restarted");

        }else if (messageType == "ACK-UNKNOWN") {
            QJsonDocument unknown(nodeMessage.jsonData());
            QJsonObject oldMessage(unknown.object().value("unknownmessage").toObject());
            qDebug() <<  "The server don't understand the message type: " << oldMessage.value("type").toString();
            qDebug() <<  "ERROR message: " << unknown.object().value("errorinfo").toString();

        }else if (messageType == "FULL-READ"){
            ipcSendMessage(data);

        }else{
            /* When receives a message that can't be interpreted like any type is an unknown message.
             * In this case an ACK-UNKNOWN message is built and sent to the connection that received this message
             */
            qDebug() <<  "UNKNOWN MESSAGE";
            QJsonObject unknownObj;
            unknownObj.insert("unknownmessage", QJsonValue(QJsonDocument::fromJson(data).object()));
            unknownObj.insert("errorinfo", QString("Unknown message received"));
            tcpSendMessage(connection, buildMessage(unknownObj, "ACK-UNKNOWN").toJson());
        }

        /* when all the process is done, reset the expecting message size to zero and the haspackage to false.
         * Then when more data arrive it must to be the size information again.
         */
        packageSize = 0;
        hasPackage = false;
    }
}
Example #28
0
void addlens::on_Save_clicked()

{

    strcpy(lensStructure.cIol,ui->IOL->text().toStdString().c_str());

    strcpy(lensStructure.cCompany,ui->Company->text().toStdString().c_str());

    if(ui->Anterior->isChecked()==1 && ui->Posterior->isChecked()==0)

        strcpy(lensStructure.cType,"Anterior");

    else if(ui->Anterior->isChecked()==0 && ui->Posterior->isChecked()==1)

        strcpy(lensStructure.cType,"Posterior");

    else

        strcpy(lensStructure.cType,"Anterior");

    strcpy(lensStructure.cA_SRKT,ui->AVal_1->text().toStdString().c_str());

    strcpy(lensStructure.cA_SRKII,ui->AVal_2->text().toStdString().c_str());

    strcpy(lensStructure.cA0,ui->A0val->text().toStdString().c_str());

    strcpy(lensStructure.cA1,ui->A1val->text().toStdString().c_str());

    strcpy(lensStructure.cA2,ui->A2val->text().toStdString().c_str());

    strcpy(lensStructure.cAcd,ui->Acdval->text().toStdString().c_str());

    strcpy(lensStructure.cSf,ui->Sfval->text().toStdString().c_str());

    lens lensLocalTemp;

    int flag=0;

    ifstream fileLensIn;

    fileLensIn.open("lens.dat",ios::binary);

    while(fileLensIn.read((char*)&lensLocalTemp,sizeof(lensLocalTemp)))

    {

        if(strcmp(lensLocalTemp.cIol,lensStructure.cIol)==0)

            flag++;

    }

    if(strcmp(lensStructure.cIol,"")==0 || strcmp(lensStructure.cA_SRKII,"")==0 || strcmp(lensStructure.cCompany,"")==0||strcmp(lensStructure.cA_SRKT,"")==0,strcmp(lensStructure.cA0,"")==0||strcmp(lensStructure.cA1,"")==0||strcmp(lensStructure.cAcd,"")==0||strcmp(lensStructure.cSf,"")==0)

    {

        p=new prompta("One or more fields is/are empty!",this);

        p->move(200,200);

        p->show();

        QTimer *msgBoxCloseTimer = new QTimer(this);

        msgBoxCloseTimer->setInterval(3000);

        msgBoxCloseTimer->setSingleShot(true);

        connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

        msgBoxCloseTimer->start();

        p->exec();

    }
    else
    {

        if(flag==0)

        {

            ofstream fileLensOut;

            fileLensOut.open("lens.dat",ios::binary|ios::app);

            fileLensOut.write((char*)&lensStructure,sizeof(lensStructure));

            fileLensOut.close();

            p=new prompta("Record was added.",this);

            p->move(200,200);

            p->show();

            QTimer *msgBoxCloseTimer = new QTimer(this);

            msgBoxCloseTimer->setInterval(3000);

            msgBoxCloseTimer->setSingleShot(true);

            connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

            msgBoxCloseTimer->start();

            p->exec();

            ui->A0val->clear();

            ui->A1val->clear();

            ui->A2val->clear();

            ui->Acdval->clear();

            ui->AVal_1->clear();

            ui->AVal_2->clear();

            ui->Company->clear();

            ui->IOL->clear();

            ui->Sfval->clear();

            this->close();

        }

        else

        {

            p=new prompta("IOL exists already!",this);

            p->move(200,200);

            p->show();

            QTimer *msgBoxCloseTimer = new QTimer(this);

            msgBoxCloseTimer->setInterval(3000);

            msgBoxCloseTimer->setSingleShot(true);

            connect(msgBoxCloseTimer, SIGNAL(timeout()), p, SLOT(reject())); // or accept()

            msgBoxCloseTimer->start();

            p->exec();

        }

    }
}
Example #29
0
void MapQuestRunner::retrieveRoute( const RouteRequest *route )
{
    if ( route->size() < 2 ) {
        return;
    }

    QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()["mapquest"];

    if ( settings.value( "appKey" ).toString().isEmpty() )
    {
        return;
    }

    QString url = "http://open.mapquestapi.com/directions/v1/route?callback=renderAdvancedNarrative&outFormat=xml&narrativeType=text&shapeFormat=raw&generalize=0";
    GeoDataCoordinates::Unit const degree = GeoDataCoordinates::Degree;
    append( &url, "from", QString::number( route->source().latitude( degree ), 'f', 6 ) + ',' + QString::number( route->source().longitude( degree ), 'f', 6 ) );
    for ( int i=1; i<route->size(); ++i ) {
        append( &url, "to", QString::number( route->at( i ).latitude( degree ), 'f', 6 ) + ',' + QString::number( route->at( i ).longitude( degree ), 'f', 6 ) );
    }

    QString const unit = MarbleGlobal::getInstance()->locale()->measurementSystem() == MarbleLocale::MetricSystem ? "k" : "m";
    append( &url, "units", unit );

    if ( settings["noMotorways"].toInt() ) {
        append( &url, "avoids", "Limited Access" );
    }
    if ( settings["noTollroads"].toInt() ) {
        append( &url, "avoids", "Toll road" );
    }
    if ( settings["noFerries"].toInt() ) {
        append( &url, "avoids", "Ferry" );
    }

    if ( !settings["preference"].toString().isEmpty() ) {
        append( &url, "routeType", settings["preference"].toString() );
    }

    if ( !settings["ascending"].toString().isEmpty() && !settings["descending"].toString().isEmpty() ) {
            if ( settings["ascending"].toString() == "AVOID_UP_HILL"
                       && settings["descending"].toString() == "AVOID_DOWN_HILL" ) {
                append( &url, "roadGradeStrategy", "AVOID_ALL_HILLS" );
            }
            else if ( settings["ascending"].toString() == "FAVOR_UP_HILL"
                         && settings["descending"].toString() == "FAVOR_DOWN_HILL" ) {
                append( &url, "roadGradeStrategy", "FAVOR_ALL_HILLS" );
            }
            else if ( settings["ascending"].toString() == "DEFAULT_STRATEGY"
                         && settings["descending"].toString() == "DEFAULT_STRATEGY" ) {
                append( &url, "roadGradeStrategy", "DEFAULT_STRATEGY" );
            }
            else if ( settings["ascending"].toString() == "DEFAULT_STRATEGY" ) {
                append( &url, "roadGradeStrategy", settings["descending"].toString() );
            }
            else if ( settings["descending"].toString() == "DEFAULT_STRATEGY" ) {
                append( &url, "roadGradeStrategy", settings["ascending"].toString() );
            }
            else if ( settings["descending"].toString() == "AVOID_DOWN_HILL" ) {
                append( &url, "roadGradeStrategy", settings["descending"].toString() );
            }
            else if ( settings["ascending"].toString() == "AVOID_UP_HILL" ) {
                append( &url, "roadGradeStrategy", settings["ascending"].toString() );
            }
        }
    QUrl qurl(url);
// FIXME: verify that this works with special characters.
#if QT_VERSION >= 0x050000
    QUrlQuery urlQuery;
    urlQuery.addQueryItem( "key", settings.value( "appKey" ).toByteArray() );
    qurl.setQuery(urlQuery);
#else
    qurl.addEncodedQueryItem( "key", settings.value( "appKey" ).toByteArray() );
#endif
    m_request.setUrl( qurl );
    m_request.setRawHeader( "User-Agent", HttpDownloadManager::userAgent( "Browser", "MapQuestRunner" ) );

    QEventLoop eventLoop;

    QTimer timer;
    timer.setSingleShot( true );
    timer.setInterval( 15000 );

    connect( &timer, SIGNAL(timeout()),
             &eventLoop, SLOT(quit()));
    connect( this, SIGNAL(routeCalculated(GeoDataDocument*)),
             &eventLoop, SLOT(quit()) );

    // @todo FIXME Must currently be done in the main thread, see bug 257376
    QTimer::singleShot( 0, this, SLOT(get()) );
    timer.start();

    eventLoop.exec();
}
Example #30
0
/** Constructor. Parses the command-line arguments, resets Rshare's
 * configuration (if requested), and sets up the GUI style and language
 * translation. */
Rshare::Rshare(QStringList args, int &argc, char **argv, const QString &dir)
: QApplication(argc, argv)
{
  mStartupTime = QDateTime::currentDateTime();
  localServer = NULL;

  //Initialize connection to LocalServer to know if other process runs.
  {
    QString serverName = QString(TARGET);

    if (!args.isEmpty()) {
      // load into shared memory
      QBuffer buffer;
      buffer.open(QBuffer::ReadWrite);
      QDataStream out(&buffer);
      out << args;
      int size = buffer.size();

      QSharedMemory newArgs;
      newArgs.setKey(serverName + "_newArgs");
      if (newArgs.isAttached()) newArgs.detach();

      if (!newArgs.create(size)) {
        std::cerr << "(EE) Rshare::Rshare Unable to create shared memory segment of size:"
                  << size << " error:" << newArgs.errorString().toStdString() << "." << std::endl;
#ifdef Q_OS_UNIX
        std::cerr << "Look with `ipcs -m` for nattch==0 segment. And remove it with `ipcrm -m 'shmid'`." << std::endl;
        //No need for windows, as it removes shared segment directly even when crash.
#endif
        newArgs.detach();
        ::exit(EXIT_FAILURE);
      }
      newArgs.lock();
      char *to = (char*)newArgs.data();
      const char *from = buffer.data().data();
      memcpy(to, from, qMin(newArgs.size(), size));
      newArgs.unlock();

      // Connect to the Local Server of the main process to notify it
      // that a new process had been started
      QLocalSocket localSocket;
      localSocket.connectToServer(QString(TARGET));

      std::cerr << "Rshare::Rshare waitForConnected to other instance." << std::endl;
      if( localSocket.waitForConnected(100) )
      {
        std::cerr << "Rshare::Rshare Connection etablished. Waiting for disconnection." << std::endl;
        localSocket.waitForDisconnected(1000);
        newArgs.detach();
        std::cerr << "Rshare::Rshare Arguments was sended." << std::endl
                  << " To disable it, in Options - General - Misc," << std::endl
                  << " uncheck \"Use Local Server to get new Arguments\"." << std::endl;
        ::exit(EXIT_SUCCESS); // Terminate the program using STDLib's exit function
      }
      newArgs.detach();
    }
    // No main process exists
    // Or started without arguments
    // So we start a Local Server to listen for connections from new process
    localServer= new QLocalServer();
    QObject::connect(localServer, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished()));
    updateLocalServer();
  }

#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
  qInstallMessageHandler(qt_msg_handler);
#else
  qInstallMsgHandler(qt_msg_handler);
#endif

#ifndef __APPLE__

  /* set default window icon */
  setWindowIcon(QIcon(":/icons/logo_128.png"));

#endif

  mBlink = true;
  QTimer *timer = new QTimer(this);
  timer->setInterval(500);
  connect(timer, SIGNAL(timeout()), this, SLOT(blinkTimer()));
  timer->start();

  timer = new QTimer(this);
  timer->setInterval(60000);
  connect(timer, SIGNAL(timeout()), this, SIGNAL(minuteTick()));
  timer->start();

  /* Read in all our command-line arguments. */
  parseArguments(args);

  /* Check if we're supposed to reset our config before proceeding. */
  if (_args.contains(ARG_RESET)) {
    Settings->reset();
  }
  
  /* Handle the -loglevel and -logfile options. */
  if (_args.contains(ARG_LOGFILE))
    _log.open(_args.value(ARG_LOGFILE));
  if (_args.contains(ARG_LOGLEVEL)) {
    _log.setLogLevel(Log::stringToLogLevel(
                      _args.value(ARG_LOGLEVEL)));
    if (!_args.contains(ARG_LOGFILE))
      _log.open(stdout);
  }
  if (!_args.contains(ARG_LOGLEVEL) && 
      !_args.contains(ARG_LOGFILE))
    _log.setLogLevel(Log::Off);

  /* config directory */
  useConfigDir = false;
  if (dir != "")
  {
  	setConfigDirectory(dir);
  }

  /** Initialize support for language translations. */
  //LanguageSupport::initialize();

  resetLanguageAndStyle();

  /* Switch off auto shutdown */
  setQuitOnLastWindowClosed ( false );

	/* Initialize GxsIdDetails */
	GxsIdDetails::initialize();
}