/* * 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()); } }
//----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- tPerformanceWidget::tPerformanceWidget( tIInstrumentProductFactory* pProductFactory, QWidget* pParent ) : QWidget( pParent ) , m_Mode( tPerformanceWidget::eModeAuto ) { Assert( pProductFactory ); if ( pProductFactory ) { setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); m_pLayout = new QGridLayout( this ); m_pLayout->setSpacing( 0 ); m_pLayout->setContentsMargins( 0, 0, 0, 0 ); m_pGaugeStack = new tSlidingStackedWidget( this ); m_pGaugeStack->setSpeed( 300 ); m_pGaugeStack->setAnimation( QEasingCurve::OutQuad ); m_pGaugeStack->setWrap( true ); m_pLayout->addWidget( m_pGaugeStack, 0, 1, 2, 1 ); tGaugeParams gaugeParams = tGaugeParams(); gaugeParams.m_SliderParams.m_LeftHandScale = false; // Bar graphs m_pVmgPerfGraph = new tPerfSliderGauge( DATA_TYPE_SPEED_WATER, this, gaugeParams ); m_pGaugeStack->addWidget( m_pVmgPerfGraph ); m_Gauges << m_pVmgPerfGraph; m_pReachingPerfGraph = new tPerfSliderGauge( DATA_TYPE_POLAR_PERFORMANCE, this, gaugeParams ); m_pGaugeStack->addWidget( m_pReachingPerfGraph ); m_Gauges << m_pReachingPerfGraph; // Digital gauges m_pTargetBspGauge = pProductFactory->GetDigitalGauge( DATA_TYPE_TARGET_BOAT_SPEED, this ); m_pTargetBspGauge->SetBorders( false, false, true, true ); m_pTargetBspGauge->SetTaperedBorder( true, false ); m_pLayout->addWidget( m_pTargetBspGauge, 0, 0 ); m_Gauges << m_pTargetBspGauge; m_pTargetTwaGauge = pProductFactory->GetDigitalGauge( DATA_TYPE_TARGET_TRUE_WIND_ANGLE, this ); m_pTargetTwaGauge->SetBorders( false, false, true, false ); m_pTargetTwaGauge->SetTaperedBorder( false, true ); m_pLayout->addWidget( m_pTargetTwaGauge, 1, 0 ); m_Gauges << m_pTargetTwaGauge; m_pPolarSpeedGauge = pProductFactory->GetDigitalGauge( DATA_TYPE_POLAR_SPEED, this ); m_pPolarSpeedGauge->SetBorders( false, false, true, true ); m_pPolarSpeedGauge->SetTaperedBorder( true, false ); m_pLayout->addWidget( m_pPolarSpeedGauge, 0, 0 ); m_Gauges << m_pPolarSpeedGauge; m_pBoatSpeedGauge = pProductFactory->GetDigitalGauge( DATA_TYPE_SPEED_WATER, this ); m_pBoatSpeedGauge->SetBorders( false, false, true, false ); m_pBoatSpeedGauge->SetTaperedBorder( false, true ); m_pLayout->addWidget( m_pBoatSpeedGauge, 1, 0 ); m_Gauges << m_pBoatSpeedGauge; int dataBoxW = Widgets::GetThirdScreenWidth(); m_pVmgPerfGraph->setFixedSize( Widgets::GetScreenWidth() - dataBoxW, Widgets::GetScreenHeight() ); m_pReachingPerfGraph->setFixedSize( Widgets::GetScreenWidth() - dataBoxW, Widgets::GetScreenHeight() ); m_pTargetBspGauge->setFixedSize( dataBoxW, Widgets::GetHalfScreenHeight() ); m_pTargetTwaGauge->setFixedSize( dataBoxW, Widgets::GetHalfScreenHeight() ); m_pPolarSpeedGauge->setFixedSize( dataBoxW, Widgets::GetHalfScreenHeight() ); m_pBoatSpeedGauge->setFixedSize( dataBoxW, Widgets::GetHalfScreenHeight() ); SetUpdateRates(); Connect( tInstrumentDataManager::Instance(), SIGNAL( UpdateRatesChanged() ), this, SLOT( SetUpdateRates() ) ); UpdatePerfGauge(); QTimer* pTimer = new QTimer( this ); pTimer->setInterval( 1000 ); Connect( pTimer, SIGNAL( timeout() ), this, SLOT( UpdatePerfGauge() ) ); pTimer->start(); } }
BitcoinGUI::BitcoinGUI(QWidget *parent): QMainWindow(parent), clientModel(0), walletModel(0), encryptWalletAction(0), changePassphraseAction(0), unlockWalletAction(0), lockWalletAction(0), aboutQtAction(0), trayIcon(0), notificator(0), rpcConsole(0), nWeight(0) { resize(850, 550); setWindowTitle(tr("PsychoCoin") + " - " + tr("Wallet")); #ifndef Q_OS_MAC qApp->setWindowIcon(QIcon(":icons/bitcoin")); setWindowIcon(QIcon(":icons/bitcoin")); #else setUnifiedTitleAndToolBarOnMac(true); QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon createActions(); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create the tray icon (or setup the dock icon) createTrayIcon(); // Create tabs overviewPage = new OverviewPage(); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); transactionsPage->setLayout(vbox); addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab); receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab); sendCoinsPage = new SendCoinsDialog(this); signVerifyMessageDialog = new SignVerifyMessageDialog(this); centralWidget = new QStackedWidget(this); centralWidget->addWidget(overviewPage); centralWidget->addWidget(transactionsPage); centralWidget->addWidget(addressBookPage); centralWidget->addWidget(receiveCoinsPage); centralWidget->addWidget(sendCoinsPage); setCentralWidget(centralWidget); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); labelEncryptionIcon = new QLabel(); labelStakingIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelStakingIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); if (GetBoolArg("-staking", true)) { QTimer *timerStakingIcon = new QTimer(labelStakingIcon); connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon())); timerStakingIcon->start(30 * 1000); updateStakingIcon(); } // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = qApp->style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this); // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage())); connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); rpcConsole = new RPCConsole(this); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); // Clicking on "Verify Message" in the address book sends you to the verify message tab connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString))); // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString))); gotoOverviewPage(); }
int main(int argc, char **argv) { MPI::Init(argc, argv); QApplication app(argc, argv); LibGeoDecomp::Typemaps::initializeMaps(); MPI::Aint displacements[] = {0}; MPI::Datatype memberTypes[] = {MPI::CHAR}; int lengths[] = {sizeof(CanvasCell)}; MPI::Datatype objType; objType = MPI::Datatype::Create_struct(1, lengths, displacements, memberTypes); objType.Commit(); MPI::Datatype particleType; lengths[0] = sizeof(Particle); particleType = MPI::Datatype::Create_struct(1, lengths, displacements, memberTypes); particleType.Commit(); ParticleWidget *widget = 0; CanvasInitializer *init = getInit1(); HiParSimulator<CanvasCell, RecursiveBisectionPartition<2> > *sim = new HiParSimulator<CanvasCell, RecursiveBisectionPartition<2> >( init, MPILayer().rank() ? 0 : new NoOpBalancer(), 1000, 1, particleType); std::cout << "Simulator created ...\n"; // HiParSimulator<CanvasCell, RecursiveBisectionPartition<2> > sim( // new CanvasInitializer(dim.x(), dim.y()), // MPILayer().rank() ? 0 : new NoOpBalancer(), // 1000, // 1, // particleType); ForceSteerer *steerer = new ForceSteerer(1); sim->addSteerer(steerer); std::cout << "Steerer added ...\n"; Storage * storage = 0; if (MPILayer().rank() == 0) { storage = new Storage; widget = new ParticleWidget(*storage, init->gridDimensions(), Qt::black); widget->resize(1000, 500); widget->show(); std::cout << "Widget created ...\n"; } sim->addWriter(new TracingWriter<CanvasCell>(100, 100000)); sim->addWriter(new ParticleWriter(storage, init->gridDimensions(), 1, particleType)); FakeSimulator fakeSim(sim); // DebugOutput logger; QTimer timer; QTimer timerGL; QObject::connect(&timer, SIGNAL(timeout()), &fakeSim, SLOT(step())); // QObject::connect(&widget, SIGNAL(newFrame()), // &logger, SLOT(newFrame())); // QObject::connect(&widget, SIGNAL(forceRecorded(QPoint, QPoint)), // &logger, SLOT(addForce(QPoint, QPoint))); QObject::connect(storage, SIGNAL(forceRecorded(QVector2D, QVector2D)), steerer, SLOT(addForce(QVector2D, QVector2D))); QObject::connect(&timerGL, SIGNAL(timeout()), widget, SLOT(updateGL())); timer.start(10); timerGL.start(10); app.exec(); delete sim; MPI::Finalize(); }
CQplayerGUI::CQplayerGUI(QWidget *parent) : QDialog(parent), ui(new Ui::CQplayerGUI) { translator = new MyTranslator(":/language_thai.ini"); disableTimer.setSingleShot(true); disableTimer.setInterval(3000); connect(&disableTimer,SIGNAL(timeout()),this,SLOT(slot_disableTime())); versionCtrl = new VersionSender("RoomMedia",1,1,12,ZTools::getCarID()); ztpmForTest = new ZTPManager(8319,QHostAddress("224.102.228.40")); connect(ztpmForTest,SIGNAL(readyRead()),this,SLOT(slot_procTestZtp())); ZTPManager* ztpm = new ZTPManager(6633,QHostAddress("224.102.228.41")); connect(ztpm,SIGNAL(readyRead()),this,SLOT(slot_turnOffHeart())); QTimer* timer = new QTimer(); timer->setSingleShot(false); timer->setInterval(3000); timer->start(); connect(timer,SIGNAL(timeout()),this,SLOT(sendHeart())); ui->setupUi(this); char buf[10]; sprintf(buf,"%02d",ZTools::getCarID()); ui->carIDLabel->setText(buf); btn[0] = ui->btn_ch0; btn[1] = ui->btn_ch1; btn[2] = ui->btn_ch2; btn[3] = ui->btn_ch3; btn[4] = ui->btn_ch4; btn[5] = ui->btn_ch5; btn[6] = ui->btn_ch6; btn[7] = ui->btn_ch7; btn[8] = ui->btn_ch8; stackPanel = new StackPanel(translator,ui->frameMovie); stackPanel->hide(); GlobalInfo* global = GlobalInfo::getInstance(); global->playerGui = this; WorkThread::getInstance()->start(); setWindowFlags(Qt::FramelessWindowHint|(windowFlags() & (~Qt::WindowCloseButtonHint))); serial = new RoomPanel(); cqAudio = new CQAudio(ui->frameMovie,stackPanel,0); media = new CQMedia(ui->frameMovie->winId(),0); connect(media,SIGNAL(error(CQGstBasic::ErrorType)),this,SLOT(onMediaSignal(CQGstBasic::ErrorType))); ui->sliderVlm->setSliderPosition(10); // QTimer::singleShot(1000,this,SLOT(on_btn_ch0_clicked())); channel = -1; playState = STOP; screenInit(); updateTimer = new QTimer; updateTimer->setSingleShot(false); updateTimer->setInterval(1000); connect(updateTimer,SIGNAL(timeout()),this,SLOT(updateTime())); updateTimer->start(); switchLanguage = new QTimer; switchLanguage->setSingleShot(false); connect(switchLanguage,SIGNAL(timeout()),this,SLOT(refresh())); switchLanguage->setInterval(10000); switchLanguage->start(); }
void PictureFlowAnimator::update() { if(!animateTimer.isActive()) return; if(step == 0) return; if(!state) return; int speed = 16384/4; #if 1 // deaccelerate when approaching the target const int max = 2 * 65536; int fi = frame; fi -= (target << 16); if(fi < 0) fi = -fi; fi = qMin(fi, max); int ia = IANGLE_MAX * (fi-max/2) / (max*2); speed = 512 + 16384 * (PFREAL_ONE+fsin(ia))/PFREAL_ONE; #endif frame += speed*step; int index = frame >> 16; int pos = frame & 0xffff; int neg = 65536 - pos; int tick = (step < 0) ? neg : pos; PFreal ftick = (tick * PFREAL_ONE) >> 16; if(step < 0) index++; if(state->centerIndex != index) { state->centerIndex = index; frame = index << 16; state->centerSlide.slideIndex = state->centerIndex; for(int i = 0; i < (int)state->leftSlides.count(); i++) state->leftSlides[i].slideIndex = state->centerIndex-1-i; for(int i = 0; i < (int)state->rightSlides.count(); i++) state->rightSlides[i].slideIndex = state->centerIndex+1+i; } state->centerSlide.angle = (step * tick * state->angle) >> 16; state->centerSlide.cx = -step * fmul(state->offsetX, ftick); state->centerSlide.cy = fmul(state->offsetY, ftick); if(state->centerIndex == target) { stop(target); state->reset(); return; } for(int i = 0; i < (int)state->leftSlides.count(); i++) { SlideInfo& si = state->leftSlides[i]; si.angle = state->angle; si.cx = -(state->offsetX + state->spacing*i*PFREAL_ONE + step*state->spacing*ftick); si.cy = state->offsetY; } for(int i = 0; i < (int)state->rightSlides.count(); i++) { SlideInfo& si = state->rightSlides[i]; si.angle = -state->angle; si.cx = state->offsetX + state->spacing*i*PFREAL_ONE - step*state->spacing*ftick; si.cy = state->offsetY; } if(step > 0) { PFreal ftick = (neg * PFREAL_ONE) >> 16; state->rightSlides[0].angle = -(neg * state->angle) >> 16; state->rightSlides[0].cx = fmul(state->offsetX, ftick); state->rightSlides[0].cy = fmul(state->offsetY, ftick); }
bool VehicleConfigurationHelper::saveChangesToController(bool save) { qDebug() << "Saving modified objects to controller. " << m_modifiedObjects.count() << " objects in found."; const int OUTER_TIMEOUT = 3000 * 20; // 10 seconds timeout for saving all objects const int INNER_TIMEOUT = 2000; // 1 second timeout on every save attempt ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); Q_ASSERT(pm); UAVObjectUtilManager *utilMngr = pm->getObject<UAVObjectUtilManager>(); Q_ASSERT(utilMngr); QTimer outerTimeoutTimer; outerTimeoutTimer.setSingleShot(true); QTimer innerTimeoutTimer; innerTimeoutTimer.setSingleShot(true); connect(utilMngr, SIGNAL(saveCompleted(int, bool)), this, SLOT(uAVOTransactionCompleted(int, bool))); connect(&innerTimeoutTimer, SIGNAL(timeout()), &m_eventLoop, SLOT(quit())); connect(&outerTimeoutTimer, SIGNAL(timeout()), this, SLOT(saveChangesTimeout())); outerTimeoutTimer.start(OUTER_TIMEOUT); for (int i = 0; i < m_modifiedObjects.count(); i++) { QPair<UAVDataObject *, QString> *objPair = m_modifiedObjects.at(i); m_transactionOK = false; UAVDataObject *obj = objPair->first; QString objDescription = objPair->second; if (UAVObject::GetGcsAccess(obj->getMetadata()) != UAVObject::ACCESS_READONLY && obj->isSettings()) { emit saveProgress(m_modifiedObjects.count() + 1, ++m_progress, objDescription); m_currentTransactionObjectID = obj->getObjID(); connect(obj, SIGNAL(transactionCompleted(UAVObject *, bool)), this, SLOT(uAVOTransactionCompleted(UAVObject *, bool))); while (!m_transactionOK && !m_transactionTimeout) { // Allow the transaction to take some time innerTimeoutTimer.start(INNER_TIMEOUT); // Set object updated obj->updated(); if (!m_transactionOK) { m_eventLoop.exec(); } innerTimeoutTimer.stop(); } disconnect(obj, SIGNAL(transactionCompleted(UAVObject *, bool)), this, SLOT(uAVOTransactionCompleted(UAVObject *, bool))); if (m_transactionOK) { qDebug() << "Object " << obj->getName() << " was successfully updated."; if (save) { m_transactionOK = false; m_currentTransactionObjectID = obj->getObjID(); // Try to save until success or timeout while (!m_transactionOK && !m_transactionTimeout) { // Allow the transaction to take some time innerTimeoutTimer.start(INNER_TIMEOUT); // Persist object in controller utilMngr->saveObjectToFlash(obj); if (!m_transactionOK) { m_eventLoop.exec(); } innerTimeoutTimer.stop(); } m_currentTransactionObjectID = -1; } } if (!m_transactionOK) { qDebug() << "Transaction timed out when trying to save: " << obj->getName(); } else { qDebug() << "Object " << obj->getName() << " was successfully saved."; } } else {
BitcoinGUI::BitcoinGUI(QWidget *parent): QMainWindow(parent), clientModel(0), walletModel(0), encryptWalletAction(0), changePassphraseAction(0), unlockWalletAction(0), lockWalletAction(0), aboutQtAction(0), trayIcon(0), notificator(0), rpcConsole(0), nWeight(0) { setFixedSize(970, 550); QFontDatabase::addApplicationFont(":/fonts/Bebas"); setWindowTitle(tr("Pentaquark") + " - " + tr("Wallet")); qApp->setStyleSheet("QMainWindow { background-image:url(:images/bkg);border:none; } #frame { } QToolBar QLabel { padding-top: 0px;padding-bottom: 0px;spacing: 10px;} QToolBar QLabel:item { padding-top: 0px;padding-bottom: 0px;spacing: 10px;} #toolbar2 { border:none;width:0px;hight:0px;padding-top:40px;padding-bottom:0px; background-color: transparent; } #labelMiningIcon { padding-left:5px;font-family:Century Gothic;width:100%;font-size:10px;text-align:center;color:red; } QMenu { background-color: qlineargradient(spread:pad, x1:0.511, y1:1, x2:0.482909, y2:0, stop:0 rgba(232,232,232), stop:1 rgba(232,232,232)); color: red; padding-bottom:10px; } QMenu::item { color: red; background: transparent; } QMenu::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgba(99,99,99,45), stop: 1 rgba(99,99,99,45)); } QMenuBar { background-color: white; color: red; } QMenuBar::item { font-size:12px;padding-bottom:3px;padding-top:3px;padding-left:15px;padding-right:15px;color: red; background-color: white; } QMenuBar::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgba(99,99,99,45), stop: 1 rgba(99,99,99,45)); }"); #ifndef Q_OS_MAC qApp->setWindowIcon(QIcon(":icons/pentaquark")); setWindowIcon(QIcon(":icons/pentaquark")); #else setUnifiedTitleAndToolBarOnMac(true); QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon createActions(); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create the tray icon (or setup the dock icon) createTrayIcon(); // Create tabs overviewPage = new OverviewPage(); statisticsPage = new StatisticsPage(this); blockBrowser = new BlockBrowser(this); chatWindow = new ChatWindow(this); #ifdef ENABLE_TRADE_REQUIRE_QT5 tradingDialogPage = new tradingDialog(this); tradingDialogPage->setObjectName("tradingDialog"); #endif // radioPage = new Radio(this); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); transactionsPage->setLayout(vbox); addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab); receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab); sendCoinsPage = new SendCoinsDialog(this); signVerifyMessageDialog = new SignVerifyMessageDialog(this); centralWidget = new QStackedWidget(this); centralWidget->addWidget(overviewPage); centralWidget->addWidget(statisticsPage); centralWidget->addWidget(blockBrowser); centralWidget->addWidget(chatWindow); #ifdef ENABLE_TRADE_REQUIRE_QT5 centralWidget->addWidget(tradingDialogPage); #endif // centralWidget->addWidget(radioPage); centralWidget->addWidget(transactionsPage); centralWidget->addWidget(addressBookPage); centralWidget->addWidget(receiveCoinsPage); centralWidget->addWidget(sendCoinsPage); setCentralWidget(centralWidget); // Create status bar // Status bar notification icons labelEncryptionIcon = new QLabel(); labelStakingIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); if (GetBoolArg("-staking", true)) { QTimer *timerStakingIcon = new QTimer(labelStakingIcon); connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon())); timerStakingIcon->start(30 * 1000); updateStakingIcon(); } // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); addToolBarBreak(Qt::LeftToolBarArea); QToolBar *toolbar2 = addToolBar(tr("Tabs toolbar")); addToolBar(Qt::LeftToolBarArea,toolbar2); toolbar2->setOrientation(Qt::Vertical); toolbar2->setMovable( false ); toolbar2->setObjectName("toolbar2"); toolbar2->setFixedWidth(28); toolbar2->setIconSize(QSize(28,54)); toolbar2->addWidget(labelEncryptionIcon); toolbar2->addWidget(labelStakingIcon); toolbar2->addWidget(labelConnectionsIcon); toolbar2->addWidget(labelBlocksIcon); toolbar2->setStyleSheet("#toolbar2 QToolButton { background: transparent;border:none;padding:0px;margin:0px;height:54px;width:28px; }"); syncIconMovie = new QMovie(":/movies/update_spinner", "gif", this); // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage())); connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); #ifdef ENABLE_TRADE_REQUIRE_QT5 connect(TradingAction, SIGNAL(triggered()), tradingDialogPage, SLOT(InitTrading())); #endif // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); rpcConsole = new RPCConsole(this); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); // Clicking on "Verify Message" in the address book sends you to the verify message tab connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString))); // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString))); gotoOverviewPage(); }
void Mwindow::initUI() { /* Menu */ QMenu *fileMenu = menuBar()->addMenu("&File"); QMenu *editMenu = menuBar()->addMenu("&Edit"); QAction *Open = new QAction("&Open", this); QAction *Quit = new QAction("&Quit", this); QAction *playAc = new QAction("&Play/Pause", this); QAction *aboutAc = new QAction("&About", this); Open->setShortcut(QKeySequence("Ctrl+O")); Quit->setShortcut(QKeySequence("Ctrl+Q")); fileMenu->addAction(Open); fileMenu->addAction(aboutAc); fileMenu->addAction(Quit); editMenu->addAction(playAc); connect(Open, SIGNAL(triggered()), this, SLOT(openFile())); connect(playAc, SIGNAL(triggered()), this, SLOT(play())); connect(aboutAc, SIGNAL(triggered()), this, SLOT(about())); connect(Quit, SIGNAL(triggered()), qApp, SLOT(quit())); /* Buttons for the UI */ playBut = new QPushButton("Play"); QObject::connect(playBut, SIGNAL(clicked()), this, SLOT(play())); QPushButton *stopBut = new QPushButton("Stop"); QObject::connect(stopBut, SIGNAL(clicked()), this, SLOT(stop())); QPushButton *muteBut = new QPushButton("Mute"); QObject::connect(muteBut, SIGNAL(clicked()), this, SLOT(mute())); volumeSlider = new QSlider(Qt::Horizontal); QObject::connect(volumeSlider, SIGNAL(sliderMoved(int)), this, SLOT(changeVolume(int))); volumeSlider->setValue(80); slider = new QSlider(Qt::Horizontal); slider->setMaximum(1000); QObject::connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(changePosition(int))); /* A timer to update the sliders */ QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateInterface())); timer->start(100); /* Central Widgets */ QWidget* centralWidget = new QWidget; videoWidget = new QWidget; videoWidget->setAutoFillBackground( true ); QPalette plt = palette(); plt.setColor( QPalette::Window, Qt::black ); videoWidget->setPalette( plt ); /* Put all in layouts */ QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(playBut); layout->addWidget(stopBut); layout->addWidget(muteBut); layout->addWidget(volumeSlider); QVBoxLayout *layout2 = new QVBoxLayout; layout2->addWidget(videoWidget); layout2->addWidget(slider); layout2->addLayout(layout); centralWidget->setLayout(layout2); setCentralWidget(centralWidget); resize( 600, 400); }
void initializeGL(){ { rotate_value = 0; constexpr static char vs[] = R"(#version 450 layout(location=0) in vec4 iposition; layout(location=1) in vec4 inormal_ ; layout(location=1) uniform mat4 MVP ; layout(location=3) uniform mat4 NMVP ; layout(location=2) uniform vec4 light_pos = vec4(1,1,-1,1); out vec4 color ; void main(){ gl_Position = MVP * iposition ; vec4 inormal = NMVP * inormal_ ; vec3 light = light_pos.xyz - gl_Position.xyz ; light = normalize( light ); float v = smoothstep(0,1, dot(light , normalize( inormal.xyz ) )); v*=0.85; v+=0.05; color = vec4(v,v,v,1) ; } )"; constexpr static char fs[] = R"(#version 450 out vec4 fcolor ; in vec4 color ; void main(){ fcolor = color ; } )"; program = gl::VFProgramLoadSources(vs,fs); } glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glClearDepth(1); glClearColor(0,0,0,0); #ifdef _DEBUG_OPENGL_QT_ QGLDebugTool::setSimpleCallbackFunction(); QGLDebugTool::test(); #endif gl::createBuffers(1, &pointsNormalBuffer); gl::createBuffers(1,&indexBuffer); { gl::VertexNormalElementCallBack callBack ; callBack.loadFile( ":/model.zip" ); gl::bufferData(indexBuffer, callBack.triangles.size()*sizeof(callBack.triangles[0]), &callBack.triangles[0] ); gl::bufferData(pointsNormalBuffer, callBack.pointNormal.size()*sizeof(callBack.pointNormal[0]), &callBack.pointNormal[0]); const double scale__ = (std::max)({ double(callBack.xMax) - callBack.xMin , double(callBack.yMax) - callBack.yMin, double(callBack.zMax) - callBack.zMin }); modelScaleBase = glm::scale(glm::vec3( float( 1.50 / scale__), float( 1.50 / scale__), float(-1.50 / scale__) )); modelScale = modelScaleBase; normalMatrix = glm::mat4( 1,0, 0,0, 0,1, 0,0, 0,0,-1,0, 0,0, 0,1 ); indexCount = 3 * callBack.triangles.size() ; } gl::createVertexArrays(1,&vao); vao.bindBuffer(0, pointsNormalBuffer, 0, sizeof(gl::Float) * 6, 0, gl::NamedVertexArrayObject::Size::Three); vao.bindBuffer(1, pointsNormalBuffer, 0, sizeof(gl::Float) * 6, sizeof(gl::Float) * 3, gl::NamedVertexArrayObject::Size::Three); vao.bindElementBuffer(indexBuffer); { typedef void(QTimer::*TT)(); timer.connect( &timer,TT(&QTimer::timeout), [this]() { rotate(); super->updateGL(); } ); } timer.start(666); }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->PixelDisplay1->setSize(DISPLAY_XSIZE, DISPLAY_YSIZE); ui->PixelDisplay1->setDataEncoding(PixelDisplay::MONOCHROME_3310_8bit); ui->PixelDisplay1->setScale(3.0); ui->PixelDisplay2->setSize(DISPLAY_XSIZE, DISPLAY_YSIZE); ui->PixelDisplay2->setDataEncoding(PixelDisplay::MONOCHROME_3310_8bit); ui->PixelDisplay2->setScale(3.0); StatusLabel_LCD0 = new QLabel(this); StatusLabel_LCD1 = new QLabel(this); ui->statusBar->addWidget(StatusLabel_LCD0); ui->statusBar->addWidget(StatusLabel_LCD1); keyDriver1 = new keyDriver(this, 10, 300, 50); // size of enum buttons ? // Signals and slots mapping // View viewSignalMapper = new QSignalMapper(this); viewSignalMapper->setMapping(ui->actionX1, 1); viewSignalMapper->setMapping(ui->actionX2, 2); viewSignalMapper->setMapping(ui->actionX3, 3); viewSignalMapper->setMapping(ui->actionX4, 4); viewSignalMapper->setMapping(ui->actionX5, 5); connect(ui->actionX1, SIGNAL(triggered()), viewSignalMapper, SLOT (map())); connect(ui->actionX2, SIGNAL(triggered()), viewSignalMapper, SLOT (map())); connect(ui->actionX3, SIGNAL(triggered()), viewSignalMapper, SLOT (map())); connect(ui->actionX4, SIGNAL(triggered()), viewSignalMapper, SLOT (map())); connect(ui->actionX5, SIGNAL(triggered()), viewSignalMapper, SLOT (map())); connect(viewSignalMapper, SIGNAL(mapped(const int &)), this, SLOT(on_viewScale_changed(const int &))); // Control buttons press btnPressSignalMapper = new QSignalMapper(this); btnPressSignalMapper->setMapping(ui->pushButton_esc, APP_KEY_ESC); btnPressSignalMapper->setMapping(ui->pushButton_left, APP_KEY_LEFT); btnPressSignalMapper->setMapping(ui->pushButton_right, APP_KEY_RIGHT); btnPressSignalMapper->setMapping(ui->pushButton_ok, APP_KEY_OK); btnPressSignalMapper->setMapping(ui->pushButton_encoder, APP_KEY_ENCODER); connect(ui->pushButton_esc, SIGNAL(pressed()), btnPressSignalMapper, SLOT(map())); connect(ui->pushButton_left, SIGNAL(pressed()), btnPressSignalMapper, SLOT(map())); connect(ui->pushButton_right, SIGNAL(pressed()), btnPressSignalMapper, SLOT(map())); connect(ui->pushButton_ok, SIGNAL(pressed()), btnPressSignalMapper, SLOT(map())); connect(ui->pushButton_encoder, SIGNAL(pressed()), btnPressSignalMapper, SLOT(map())); connect(btnPressSignalMapper, SIGNAL(mapped(const int &)), keyDriver1, SLOT(keyPress(const int &))); // Control buttons release btnReleaseSignalMapper = new QSignalMapper(this); btnReleaseSignalMapper->setMapping(ui->pushButton_esc, APP_KEY_ESC); btnReleaseSignalMapper->setMapping(ui->pushButton_left, APP_KEY_LEFT); btnReleaseSignalMapper->setMapping(ui->pushButton_right, APP_KEY_RIGHT); btnReleaseSignalMapper->setMapping(ui->pushButton_ok, APP_KEY_OK); btnReleaseSignalMapper->setMapping(ui->pushButton_encoder, APP_KEY_ENCODER); connect(ui->pushButton_esc, SIGNAL(released()), btnReleaseSignalMapper, SLOT(map())); connect(ui->pushButton_left, SIGNAL(released()), btnReleaseSignalMapper, SLOT(map())); connect(ui->pushButton_right, SIGNAL(released()), btnReleaseSignalMapper, SLOT(map())); connect(ui->pushButton_ok, SIGNAL(released()), btnReleaseSignalMapper, SLOT(map())); connect(ui->pushButton_encoder, SIGNAL(released()), btnReleaseSignalMapper, SLOT(map())); connect(btnReleaseSignalMapper, SIGNAL(mapped(const int &)), keyDriver1, SLOT(keyRelease(const int &))); connect(keyDriver1, SIGNAL(onKeyEvent(int,int)), this, SLOT(onKeyDriverEvent(int, int))); connect(ui->updateButton,SIGNAL(clicked()),this, SLOT(on_LCD_update())); connect(&updateTimer,SIGNAL(timeout()),this,SLOT(on_LCD_update())); connect(&secondsTimer,SIGNAL(timeout()),this,SLOT(on_secondsTimer())); connect(ui->PixelDisplay1, SIGNAL(touchMove()), this, SLOT(on_touchMove()) ); connect(ui->PixelDisplay1, SIGNAL(touchPress()), this, SLOT(on_touchPress()) ); connect(ui->PixelDisplay1, SIGNAL(touchRelease()), this, SLOT(on_touchRelease()) ); connect(ui->PixelDisplay2, SIGNAL(touchMove()), this, SLOT(on_touchMove()) ); connect(ui->PixelDisplay2, SIGNAL(touchPress()), this, SLOT(on_touchPress()) ); connect(ui->PixelDisplay2, SIGNAL(touchRelease()), this, SLOT(on_touchRelease()) ); qApp->installEventFilter( this ); // This does shrinking of a form when inner widgets are resized //layout()->setSizeConstraint(QLayout::SetFixedSize); pt2Myself = this; registerLogCallback((cbLogPtr)&MainWindow::addLogWrapper); registerLcdUpdateCallback((cbLcdUpdatePtr)&MainWindow::updateDisplayWrapper); guiInitialize(); // Start seconds timer //secondsTimer.start(1000); // Start update timer if (ui->updateCheckBox->checkState()) { updateTimer.start(ui->updateSpinBox->value()); } }
void doit(vtkObject* vtkNotUsed(obj), unsigned long vtkNotUsed(event), void* client_data, void* vtkNotUsed(param)) { QTimer* t = reinterpret_cast<QTimer*>(client_data); t->stop(); }
/*! MyWindow constructor * \param w - window width * \param h - window hight */ MyWindow::MyWindow(int w, int h) : num_of_colors(18) { myBar = new QTabWidget(this); setCentralWidget(myBar); m_width = w; m_height = h; tab_number = 0; number_of_tabs = 0; testlayer = new Qt_layer( myBar ); colors_flag = true; statusBar(); m_scailing_factor = 2; // Traits Group QActionGroup *traitsGroup = new QActionGroup( this ); // Connected later traitsGroup->setExclusive( TRUE ); /*setSegmentTraits = new QAction("Segment Traits", QPixmap( (const char**)line_xpm ), "&Segment Traits", 0 ,traitsGroup, "Segment Traits" ); setSegmentTraits->setToggleAction( TRUE ); setPolylineTraits = new QAction("Polyline Traits", QPixmap( (const char**)polyline_xpm ), "&Polyline Traits", 0 , traitsGroup, "Polyline Traits" ); setPolylineTraits->setToggleAction( TRUE ); #ifdef CGAL_USE_CORE setConicTraits = new QAction("Conic Traits", QPixmap( (const char**)conic_xpm ), "&Conic Traits", 0 , traitsGroup, "Conic Traits" ); setConicTraits->setToggleAction( TRUE ); #endif */ // Snap Mode Group setSnapMode = new QAction("Snap Mode", QPixmap( (const char**)snapvertex_xpm ), "&Snap Mode", 0 , this, "Snap Mode" ); setSnapMode->setToggleAction( TRUE ); setGridSnapMode = new QAction("Grid Snap Mode", QPixmap( (const char**)snapgrid_xpm ), "&Grid Snap Mode", 0 , this, "Grid Snap Mode" ); setGridSnapMode->setToggleAction( TRUE ); // insert - delete - point_location Mode Group QActionGroup *modeGroup = new QActionGroup( this ); // Connected later modeGroup->setExclusive( TRUE ); insertMode = new QAction("Insert", QPixmap( (const char**)insert_xpm ), "&Insert", 0 , modeGroup, "Insert" ); insertMode->setToggleAction( TRUE ); deleteMode = new QAction("Delete", QPixmap( (const char**)delete_xpm ), "&Delete", 0 , modeGroup, "Delete" ); deleteMode->setToggleAction( TRUE ); pointLocationMode = new QAction("PointLocation", QPixmap( (const char**)pointlocation_xpm ), "&Point Location", 0 , modeGroup, "Point Location" ); pointLocationMode->setToggleAction( TRUE ); dragMode = new QAction("Drag", QPixmap( (const char**)hand_xpm ), "&Drag", 0 , modeGroup, "Drag" ); dragMode->setToggleAction( TRUE ); // zoom in zoominBt = new QAction("Zoom in", QPixmap( (const char**)zoomin_xpm ), "&Zoom in", 0 , this, "Zoom in" ); // zoom out zoomoutBt = new QAction("Zoom out", QPixmap( (const char**)zoomout_xpm ), "&Zoom out", 0 , this, "Zoom out" ); // color dialog color_dialog_bt = new QAction("Choose color", QPixmap( (const char**)demo_colors_xpm ), "&choose color", 0 , this, "choose color" ); // Cartograms carto_new = new QAction("New instance", QPixmap( (const char**)carto_new_xpm ), "&New instance", 0 , this, "New instance" ); carto_weights = new QAction("Set weights", QPixmap( (const char**)carto_weights_xpm ), "&Set weights", 0 , this, "Set weights" ); carto_start = new QAction("Start Cartogram", QPixmap( (const char**)carto_start_xpm ), "&Start Cartogram", 0 , this, "Start Cartogram" ); carto_it = new QAction("Next step", QPixmap( (const char**)carto_nextIt_xpm ), "&Next step", 0 , this, "Next step" ); /* #ifdef CGAL_USE_CORE // Conic Type Group QActionGroup *conicTypeGroup = new QActionGroup( this ); // Connected later conicTypeGroup->setExclusive( TRUE ); setCircle = new QAction("Circle", QPixmap( (const char**)demo_conic_circle_xpm ), "&Circle", 0 ,conicTypeGroup, "Circle" ); setCircle->setToggleAction( TRUE ); setSegment = new QAction("Segment", QPixmap( (const char**)demo_conic_segment_xpm ), "&Segment", 0 ,conicTypeGroup, "Segment" ); setSegment->setToggleAction( TRUE ); setEllipse = new QAction("Ellipse", QPixmap( (const char**)demo_conic_ellipse_xpm ), "&Ellipse", 0 ,conicTypeGroup, "Ellipse" ); setEllipse->setToggleAction( TRUE ); setParabola = new QAction("3 Points Arc", QPixmap( (const char**)demo_conic_3points_xpm ), "&3 Points Arc", 0 ,conicTypeGroup, "3 Points Arc" ); setParabola->setToggleAction( TRUE ); setHyperbola = new QAction("5 Points Arc", QPixmap( (const char**)demo_conic_5points_xpm ), "&5 Points Arc", 0 ,conicTypeGroup, "5 Points Arc" ); setHyperbola->setToggleAction( TRUE ); #endif */ //create a timer for checking if somthing changed QTimer *timer = new QTimer( this ); connect( timer, SIGNAL(timeout()), this, SLOT(timer_done()) ); timer->start( 200, FALSE ); // file menu QPopupMenu * file = new QPopupMenu( this ); menuBar()->insertItem( "&File", file ); /* file->insertItem("&Open Segment File...", this, SLOT(fileOpenSegment())); file->insertItem("&Open Polyline File...", this, SLOT(fileOpenPolyline()));\ file->insertItem("&Open Segment Arr File...", this, SLOT(fileOpenSegmentPm())); file->insertItem("&Open Polyline Arr File...", this, SLOT(fileOpenPolylinePm())); file->insertItem("&Open Conic Pm File", this, SLOT(fileOpenConicPm())); */ file->insertItem("&Open Input File...", this, SLOT(fileOpenSegment())); file->insertItem("&Open Output File...", this, SLOT(fileOpenConic())); file->insertItem("&Save...", this, SLOT(fileSave())); file->insertItem("&Save As...", this, SLOT(fileSaveAs())); //file->insertItem("&Save to ps...", this, SLOT(fileSave_ps())); file->insertSeparator(); file->insertItem("&Print...", this , SLOT(print())); file->insertSeparator(); file->insertItem( "&Close", this, SLOT(close()), CTRL+Key_X ); file->insertItem( "&Quit", qApp, SLOT( closeAllWindows() ), CTRL+Key_Q ); menuBar()->insertSeparator(); // tab menu QPopupMenu * tab = new QPopupMenu( this ); menuBar()->insertItem( "&Tab", tab ); /* tab->insertItem("Add &Segment Tab", this, SLOT(add_segment_tab())); tab->insertItem("Add &Polyline Tab", this, SLOT(add_polyline_tab())); #ifdef CGAL_USE_CORE tab->insertItem("Add &Conic Tab", this, SLOT(add_conic_tab())); tab->insertSeparator(); #endif */ tab->insertItem("Remove &Tab", this, SLOT(remove_tab())); menuBar()->insertSeparator(); // mode menu QPopupMenu * mode = new QPopupMenu( this ); menuBar()->insertItem( "&Mode", mode ); insertMode->addTo( mode ); deleteMode->addTo( mode ); pointLocationMode->addTo( mode ); dragMode->addTo( mode ); menuBar()->insertSeparator(); // snap mode menu QPopupMenu * snap_mode = new QPopupMenu( this ); menuBar()->insertItem( "&Snap mode", snap_mode ); setSnapMode->addTo(snap_mode); setGridSnapMode->addTo(snap_mode); menuBar()->insertSeparator(); // traits menu /*QPopupMenu * traits = new QPopupMenu( this ); menuBar()->insertItem( "&Traits Type", traits ); setSegmentTraits->addTo(traits); setPolylineTraits->addTo(traits); #ifdef CGAL_USE_CORE setConicTraits->addTo(traits); #endif */ // options menu QPopupMenu * options = new QPopupMenu( this ); menuBar()->insertItem( "&Options", options ); options->insertSeparator(); //options->insertItem("Overlay...", this, SLOT(overlay_pm())); options->insertSeparator(); options->insertItem("Properties...", this, SLOT(properties())); options->insertSeparator(); options->insertItem("Show Grid", this, SLOT(showGrid())); options->insertItem("Hide Grid", this, SLOT(hideGrid())); options->insertSeparator(); //options->insertItem("Conic Type", this, SLOT(conicType())); //options->insertSeparator(); options->insertItem("Unbounded Face Color...", this, SLOT(backGroundColor())); options->insertSeparator(); options->insertItem("Edge Color...", this, SLOT(changeEdgeColor())); options->insertSeparator(); options->insertItem("Vertex Color...", this, SLOT(changeVertexColor())); options->insertSeparator(); /*options->insertItem("Point-Locaiton Strategy....", this , SLOT(pointLocationStrategy())); */ QToolBar *modeTools = new QToolBar( this, "mode operations" ); modeTools->setLabel( "Mode Operations" ); insertMode->addTo( modeTools ); deleteMode->addTo( modeTools ); pointLocationMode->addTo( modeTools ); dragMode->addTo( modeTools ); modeTools->addSeparator(); QToolBar *snapModeTools = new QToolBar( this, "snapMode operations" ); snapModeTools->setLabel( "Snap Mode Operations" ); snapModeTools->addSeparator(); setSnapMode->addTo( snapModeTools ); setGridSnapMode->addTo( snapModeTools ); snapModeTools->addSeparator(); /*QToolBar *traitsTool = new QToolBar( this, "traits type" ); traitsTool->setLabel( "Traits Type" ); traitsTool->addSeparator(); setSegmentTraits->addTo( traitsTool ); setPolylineTraits->addTo( traitsTool ); #ifdef CGAL_USE_CORE setConicTraits->addTo( traitsTool ); #endif traitsTool->addSeparator(); */ QToolBar *zoomTool = new QToolBar( this, "zoom" ); zoomTool->setLabel( "Zoom" ); zoomTool->addSeparator(); zoomoutBt->addTo( zoomTool ); zoominBt->addTo( zoomTool ); zoomTool->addSeparator(); QToolBar *colorTool = new QToolBar( this, "color" ); colorTool->addSeparator(); colorTool->setLabel("Choose color"); color_dialog_bt->addTo(colorTool); colorTool->addSeparator(); QToolBar *cartoTool = new QToolBar( this, "cartograms" ); cartoTool->addSeparator(); cartoTool->setLabel("Cartograms"); carto_new->addTo(cartoTool); carto_weights->addTo(cartoTool); carto_start->addTo(cartoTool); carto_it->addTo(cartoTool); cartoTool->addSeparator(); /* #ifdef CGAL_USE_CORE conicTypeTool = new QToolBar( this, "conic type" ); conicTypeTool->setLabel( "Conic Type" ); conicTypeTool->addSeparator(); setSegment->addTo( conicTypeTool ); setCircle->addTo( conicTypeTool ); setEllipse->addTo( conicTypeTool ); setParabola->addTo( conicTypeTool ); setHyperbola->addTo( conicTypeTool ); #endif */ connect( zoomoutBt, SIGNAL( activated () ) , this, SLOT( zoomout() ) ); connect( zoominBt, SIGNAL( activated () ) , this, SLOT( zoomin() ) ); connect (color_dialog_bt , SIGNAL( activated()) , this , SLOT(openColorDialog() ) ); // connect mode group connect( modeGroup, SIGNAL( selected(QAction*) ), this, SLOT( updateMode(QAction*) ) ); // connect Traits Group /* connect( traitsGroup, SIGNAL( selected(QAction*) ), this, SLOT( updateTraitsType(QAction*) ) ); #ifdef CGAL_USE_CORE // connect Conic Type Group connect( conicTypeGroup, SIGNAL( selected(QAction*) ), this, SLOT( updateConicType(QAction*) ) ); #endif */ // connect Snap Mode connect( setSnapMode, SIGNAL( toggled( bool ) ) , this, SLOT( updateSnapMode( bool ) ) ); connect( setGridSnapMode, SIGNAL( toggled( bool ) ) , this, SLOT( updateGridSnapMode( bool ) ) ); // connect the change of current tab connect( myBar, SIGNAL( currentChanged(QWidget * ) ), this, SLOT( update() ) ); // connect cartogram actions connect( carto_start, SIGNAL( activated () ) , this, SLOT( cartogram_start() ) ); connect( carto_weights, SIGNAL( activated () ) , this, SLOT( cartogram_weights() ) ); connect( carto_it, SIGNAL( activated () ) , this, SLOT( print_all_weights())); connect( carto_new, SIGNAL( activated () ) , this, SLOT( cartogram_balance() ) ); colors = new QColor[num_of_colors]; colors[0] = Qt::blue; colors[1] = Qt::gray; colors[2] = Qt::green; colors[3] = Qt::cyan; colors[4] = Qt::magenta; colors[5] = Qt::darkRed; colors[6] = Qt::darkGreen; colors[7] = Qt::darkBlue; colors[8] = Qt::darkMagenta; colors[9] = Qt::darkCyan; colors[10] = Qt::yellow; colors[11] = Qt::white; colors[12] = Qt::darkGray; colors[13] = Qt::gray; colors[14] = Qt::red; colors[15] = Qt::cyan; colors[16] = Qt::darkYellow; colors[17] = Qt::lightGray; //state flag old_state = 0; add_conic_tab(); resize(m_width,m_height); }
BitcoinGUI::BitcoinGUI(QWidget *parent): QMainWindow(parent), clientModel(0), walletModel(0), encryptWalletAction(0), changePassphraseAction(0), lockWalletToggleAction(0), aboutQtAction(0), trayIcon(0), notificator(0), rpcConsole(0) { resize(850, 550); setWindowTitle(tr("OHLCcoin") + " - " + tr("Wallet")); #ifndef Q_OS_MAC qApp->setWindowIcon(QIcon(":icons/bitcoin")); setWindowIcon(QIcon(":icons/bitcoin")); #else setUnifiedTitleAndToolBarOnMac(true); QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Accept D&D of URIs setAcceptDrops(true); setObjectName("cloakWallet"); setStyleSheet("#cloakWallet { background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 #eeeeee, stop:1.0 #fefefe); } QToolTip { color: #cecece; background-color: #333333; border:0px;} "); // Create actions for the toolbar, menu bar and tray/dock icon createActions(); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create the tray icon (or setup the dock icon) createTrayIcon(); // Create tabs overviewPage = new OverviewPage(); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); transactionsPage->setLayout(vbox); addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab); receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab); sendCoinsPage = new SendCoinsDialog(this); signVerifyMessageDialog = new SignVerifyMessageDialog(this); centralWidget = new QStackedWidget(this); centralWidget->addWidget(overviewPage); centralWidget->addWidget(transactionsPage); centralWidget->addWidget(addressBookPage); centralWidget->addWidget(receiveCoinsPage); centralWidget->addWidget(sendCoinsPage); setCentralWidget(centralWidget); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); labelEncryptionIcon = new QLabel(); labelMintingIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelMintingIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); labelEncryptionIcon->setObjectName("labelEncryptionIcon"); labelConnectionsIcon->setObjectName("labelConnectionsIcon"); labelBlocksIcon->setObjectName("labelBlocksIcon"); labelMintingIcon->setObjectName("labelMintingIcon"); labelEncryptionIcon->setStyleSheet("#labelEncryptionIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}"); labelConnectionsIcon->setStyleSheet("#labelConnectionsIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}"); labelBlocksIcon->setStyleSheet("#labelBlocksIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}"); labelMintingIcon->setStyleSheet("#labelMintingIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}"); // Set minting pixmap labelMintingIcon->setPixmap(QIcon(":/icons/minting").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelMintingIcon->setEnabled(false); // Add timer to update minting icon QTimer *timerMintingIcon = new QTimer(labelMintingIcon); timerMintingIcon->start(MODEL_UPDATE_DELAY); connect(timerMintingIcon, SIGNAL(timeout()), this, SLOT(updateMintingIcon())); // Add timer to update minting weights QTimer *timerMintingWeights = new QTimer(labelMintingIcon); timerMintingWeights->start(30 * 1000); connect(timerMintingWeights, SIGNAL(timeout()), this, SLOT(updateMintingWeights())); // Set initial values for user and network weights nWeight, nNetworkWeight = 0; // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = qApp->style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); statusBar()->setObjectName("cloakStatusBar"); statusBar()->setStyleSheet("#cloakStatusBar { border-top-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #4B4F52, stop:0.5 #8B8F92, stop:1.0 #8B8F92); border-top-width: 2px; border-top-style: inset; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #666666, stop:0.5 #323232, stop:1.0 #111111); background-image: url(:images/shadowbar); background-repeat: repeat-x; background-position: bottom center; color: #ffffff; } QToolTip { color: #ffffff; background-color: #9D0000; border-width: 1px;border-color:#CA0D0D;}"); syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this); // this->setStyleSheet("background-color: #effbef;"); // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage())); connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); rpcConsole = new RPCConsole(this); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); // Clicking on "Verify Message" in the address book sends you to the verify message tab connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString))); // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString))); gotoOverviewPage(); }
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(); }
BitcoinGUI::BitcoinGUI(const NetworkStyle *networkStyle, QWidget *parent) : QMainWindow(parent), clientModel(0), walletFrame(0), unitDisplayControl(0), labelStakingIcon(0), labelEncryptionIcon(0), labelConnectionsIcon(0), labelBlocksIcon(0), progressBarLabel(0), progressBar(0), progressDialog(0), appMenuBar(0), overviewAction(0), historyAction(0), masternodeAction(0), quitAction(0), sendCoinsAction(0), usedSendingAddressesAction(0), usedReceivingAddressesAction(0), signMessageAction(0), verifyMessageAction(0), aboutAction(0), receiveCoinsAction(0), optionsAction(0), toggleHideAction(0), encryptWalletAction(0), backupWalletAction(0), changePassphraseAction(0), aboutQtAction(0), openRPCConsoleAction(0), openAction(0), showHelpMessageAction(0), trayIcon(0), trayIconMenu(0), notificator(0), rpcConsole(0), tradingWindow(0), prevBlocks(0), spinnerFrame(0) { /* Open CSS when configured */ this->setStyleSheet(GUIUtil::loadStyleSheet()); GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this); QString windowTitle = tr("DarkNet Core") + " - "; #ifdef ENABLE_WALLET /* if compiled with wallet support, -disablewallet can still disable the wallet */ enableWallet = !GetBoolArg("-disablewallet", false); #else enableWallet = false; #endif // ENABLE_WALLET if(enableWallet) { windowTitle += tr("Wallet"); } else { windowTitle += tr("Node"); } QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", "")); if(!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle; windowTitle += " " + networkStyle->getTitleAddText(); #ifndef Q_OS_MAC QApplication::setWindowIcon(networkStyle->getAppIcon()); setWindowIcon(networkStyle->getAppIcon()); #else MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon()); #endif setWindowTitle(windowTitle); #if defined(Q_OS_MAC) && QT_VERSION < 0x050000 // This property is not implemented in Qt 5. Setting it has no effect. // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras. setUnifiedTitleAndToolBarOnMac(true); #endif rpcConsole = new RPCConsole(enableWallet ? this : 0); #ifdef ENABLE_WALLET if(enableWallet) { /** Create wallet frame*/ walletFrame = new WalletFrame(this); tradingWindow = new tradingDialog(this); } else #endif // ENABLE_WALLET { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. */ setCentralWidget(rpcConsole); } // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(networkStyle); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(networkStyle); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); unitDisplayControl = new UnitDisplayStatusBarControl(); labelStakingIcon = new QLabel(); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QPushButton(); labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable labelConnectionsIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}"); labelConnectionsIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelBlocksIcon = new QLabel(); if(enableWallet) { frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(unitDisplayControl); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); } frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelStakingIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(true); progressBar = new GUIUtil::ProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(true); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); // Jump directly to tabs in RPC-console connect(openInfoAction, SIGNAL(triggered()), rpcConsole, SLOT(showInfo())); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(showConsole())); connect(openNetworkAction, SIGNAL(triggered()), rpcConsole, SLOT(showNetwork())); connect(openPeersAction, SIGNAL(triggered()), rpcConsole, SLOT(showPeers())); connect(openRepairAction, SIGNAL(triggered()), rpcConsole, SLOT(showRepair())); connect(openConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showConfEditor())); connect(showBackupsAction, SIGNAL(triggered()), rpcConsole, SLOT(showBackups())); connect(labelConnectionsIcon, SIGNAL(clicked()), rpcConsole, SLOT(showPeers())); // Get restart command-line parameters and handle restart connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList))); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); connect(openTradingwindowAction, SIGNAL(triggered()), tradingWindow, SLOT(show())); // prevents an oben debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), tradingWindow, SLOT(hide())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); // Subscribe to notifications from core subscribeToCoreSignals(); QTimer *timerStakingIcon = new QTimer(labelStakingIcon); connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(setStakingStatus())); timerStakingIcon->start(10000); setStakingStatus(); }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Align last toolbar action to the right QWidget *empty = new QWidget(this); empty->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); ui->mainToolBar->insertWidget(ui->actionMonitor, empty); // Align last action to the right in the monitor toolbar QWidget *emptyMonitor = new QWidget(this); emptyMonitor->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); ui->monitorToolBar->insertWidget(ui->actionMonitor, emptyMonitor); // Hide monitor toolbar ui->monitorToolBar->setVisible(false); // Hide graphs widget ui->graphsWidget->setVisible(false); // Set monospaced font in the monitor const QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); ui->consoleText->setFont(fixedFont); // Set environment settings = new SettingsStore(CONFIG_INI); setArduinoBoard(); xmlFileName = ""; serial = NULL; // Set zoom scale of the web view float zoomScale = settings->zoomScale(); ui->webView->setZoomFactor(zoomScale); // Hide messages actionCloseMessages(); serialPortClose(); // Load blockly index loadBlockly(); // Set timer to update list of available ports updateSerialPorts(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateSerialPorts())); timer->start(5000); ui->consoleText->document()->setMaximumBlockCount(100); // Show/hide icon labels in the menu bar iconLabels(); // Set process process = new QProcess(); process->setProcessChannelMode(QProcess::MergedChannels); connect(process, SIGNAL(started()), this, SLOT(onProcessStarted())); connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(onProcessOutputUpdated())); connect(process, SIGNAL(finished(int)), this, SLOT(onProcessFinished(int))); // Show opened file name in status bar connect(statusBar(), SIGNAL(messageChanged(QString)), this, SLOT(onStatusMessageChanged(QString))); // Filter events to capture backspace key ui->webView->installEventFilter(this); }
/** Constructor */ PeersDialog::PeersDialog(QWidget *parent) : RsAutoUpdatePage(1000,parent), historyKeeper(Rshare::dataDirectory() + "/his1.xml") { /* Invoke the Qt Designer generated object setup routine */ ui.setupUi(this); connect( ui.peertreeWidget, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( peertreeWidgetCostumPopupMenu( QPoint ) ) ); connect( ui.peertreeWidget, SIGNAL( itemDoubleClicked ( QTreeWidgetItem *, int)), this, SLOT(chatfriend())); /* hide the Tree +/- */ ui.peertreeWidget -> setRootIsDecorated( false ); /* Set header resize modes and initial section sizes */ QHeaderView * _header = ui.peertreeWidget->header () ; _header->setResizeMode (0, QHeaderView::Custom); _header->setResizeMode (1, QHeaderView::Interactive); _header->setResizeMode (2, QHeaderView::Interactive); /*_header->setResizeMode (3, QHeaderView::Interactive); _header->setResizeMode (4, QHeaderView::Interactive); _header->setResizeMode (5, QHeaderView::Interactive); _header->setResizeMode (6, QHeaderView::Interactive); _header->setResizeMode (7, QHeaderView::Interactive);*/ _header->resizeSection ( 0, 25 ); _header->resizeSection ( 1, 100 ); _header->resizeSection ( 2, 100 ); /*_header->resizeSection ( 3, 120 ); _header->resizeSection ( 4, 100 ); _header->resizeSection ( 5, 230 ); _header->resizeSection ( 6, 120 ); _header->resizeSection ( 7, 220 );*/ // set header text aligment QTreeWidgetItem * headerItem = ui.peertreeWidget->headerItem(); headerItem->setTextAlignment(0, Qt::AlignHCenter | Qt::AlignVCenter); headerItem->setTextAlignment(1, Qt::AlignHCenter | Qt::AlignVCenter); headerItem->setTextAlignment(2, Qt::AlignHCenter | Qt::AlignVCenter); loadEmoticonsgroupchat(); //setWindowIcon(QIcon(QString(":/images/rstray3.png"))); connect(ui.lineEdit, SIGNAL(textChanged ( ) ), this, SLOT(checkChat( ) )); connect(ui.Sendbtn, SIGNAL(clicked()), this, SLOT(sendMsg())); connect(ui.emoticonBtn, SIGNAL(clicked()), this, SLOT(smileyWidgetgroupchat())); //connect( ui.msgSendList, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( msgSendListCostumPopupMenu( QPoint ) ) ); connect( ui.msgText, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(displayInfoChatMenu(const QPoint&))); connect(ui.textboldChatButton, SIGNAL(clicked()), this, SLOT(setFont())); connect(ui.textunderlineChatButton, SIGNAL(clicked()), this, SLOT(setFont())); connect(ui.textitalicChatButton, SIGNAL(clicked()), this, SLOT(setFont())); connect(ui.fontsButton, SIGNAL(clicked()), this, SLOT(getFont())); connect(ui.colorChatButton, SIGNAL(clicked()), this, SLOT(setColor())); ui.fontsButton->setIcon(QIcon(QString(":/images/fonts.png"))); _currentColor = Qt::black; QPixmap pxm(16,16); pxm.fill(_currentColor); ui.colorChatButton->setIcon(pxm); mCurrentFont = QFont("Comic Sans MS", 12); ui.lineEdit->setFont(mCurrentFont); setChatInfo(tr("Welcome to RetroShare's group chat."), QString::fromUtf8("blue")); QStringList him; historyKeeper.getMessages(him, "", "THIS", 8); foreach(QString mess, him) ui.msgText->append(mess); //setChatInfo(mess, "green"); QMenu * grpchatmenu = new QMenu(); grpchatmenu->addAction(ui.actionClearChat); ui.menuButton->setMenu(grpchatmenu); _underline = false; QTimer *timer = new QTimer(this); timer->connect(timer, SIGNAL(timeout()), this, SLOT(insertChat())); timer->start(500); /* half a second */ ui.peertreeWidget->sortItems( 1, Qt::AscendingOrder ); /* Hide platform specific features */ #ifdef Q_WS_WIN #endif }
/* GameBored contstructor * @param QWidget is the parent widget */ GameBored::GameBored(QWidget *parent) : QWidget(parent), ui(new Ui::GameBored) { ui->setupUi(this); // make scene QGraphicsScene * scene= new QGraphicsScene(); scene->setSceneRect(0,0,800,600); scene->setBackgroundBrush(QBrush(QImage(":/pics/bg"))); // make and add item to scene MyRect * player = new MyRect(); scene->addItem(player); // focus item so that it can receive keyboard events player->setFlag(QGraphicsItem::ItemIsFocusable); player->setFocus(); // add scene to new view QGraphicsView * view = new QGraphicsView(scene); //turn off scrollbars view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); Board= new QWidget; //Board->setFixedSize(400,400); // add view to new layout // add layout to central widget QVBoxLayout * vlayout = new QVBoxLayout(Board); vlayout->addWidget(view); this->setLayout(vlayout); // this->show(); view->setFixedSize(800,600); scene->setSceneRect(0,0,800,600); player->setPos(view->width()/2 -player->pixmap().width()/2, -28 /*view->height()- player->pixmap().height()*/); // constant creation of enemies QTimer* timer = new QTimer(); QObject::connect(timer,SIGNAL(timeout()),player,SLOT(spawn())); timer->start(2400); QTimer* timer2 = new QTimer(); QObject::connect(timer2,SIGNAL(timeout()),player,SLOT(spawn2())); timer2->start(5000); // play music mp3player = new QMediaPlayer(); mp3player->setMedia(QUrl("qrc:/audio/starfox.mp3")); mp3player->play(); // add score class to screen score = new Score(); scene->addItem(score); }
TestMFVideo(QGLFormat format = QGLFormat()) : GLWindow(format), m_video(2) { QTimer *timer = new QTimer(this); timer->start(41); connect(timer, SIGNAL(timeout()), this, SLOT(repaint())); }
int main(int argc, char* argv[]) { terrama2::core::initializeTerraMA(); terrama2::core::registerFactories(); auto& serviceManager = terrama2::core::ServiceManager::getInstance(); std::map<std::string, std::string> connInfo{{"PG_HOST", TERRAMA2_DATABASE_HOST}, {"PG_PORT", TERRAMA2_DATABASE_PORT}, {"PG_USER", TERRAMA2_DATABASE_USERNAME}, {"PG_PASSWORD", TERRAMA2_DATABASE_PASSWORD}, {"PG_DB_NAME", TERRAMA2_DATABASE_DBNAME}, {"PG_CONNECT_TIMEOUT", "4"}, {"PG_CLIENT_ENCODING", "UTF-8"} }; serviceManager.setLogConnectionInfo(connInfo); terrama2::services::analysis::core::initInterpreter(); QCoreApplication app(argc, argv); DataManagerPtr dataManager(new DataManager()); QUrl uri; uri.setScheme("postgis"); uri.setHost(QString::fromStdString(TERRAMA2_DATABASE_HOST)); uri.setPort(std::stoi(TERRAMA2_DATABASE_PORT)); uri.setUserName(QString::fromStdString(TERRAMA2_DATABASE_USERNAME)); uri.setPassword(QString::fromStdString(TERRAMA2_DATABASE_PASSWORD)); uri.setPath(QString::fromStdString("/" + TERRAMA2_DATABASE_DBNAME)); // DataProvider information terrama2::core::DataProvider* outputDataProvider = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr outputDataProviderPtr(outputDataProvider); outputDataProvider->id = 3; outputDataProvider->name = "DataProvider postgis"; outputDataProvider->uri = uri.url().toStdString(); outputDataProvider->intent = terrama2::core::DataProviderIntent::PROCESS_INTENT; outputDataProvider->dataProviderType = "POSTGIS"; outputDataProvider->active = true; dataManager->add(outputDataProviderPtr); // DataSeries information terrama2::core::DataSeries* outputDataSeries = new terrama2::core::DataSeries(); terrama2::core::DataSeriesPtr outputDataSeriesPtr(outputDataSeries); outputDataSeries->id = 3; outputDataSeries->name = "Analysis result"; outputDataSeries->semantics.code = "ANALYSIS_MONITORED_OBJECT-postgis"; outputDataSeries->dataProviderId = outputDataProviderPtr->id; // DataSet information terrama2::core::DataSet* outputDataSet = new terrama2::core::DataSet(); outputDataSet->active = true; outputDataSet->id = 2; outputDataSet->format.emplace("table_name", "dcp_result"); outputDataSeries->datasetList.emplace_back(outputDataSet); dataManager->add(outputDataSeriesPtr); std::string script = "moBuffer = Buffer(BufferType.object_plus_buffer, 2., \"km\")\n" "x = dcp.min(\"Serra do Mar\", \"Pluvio\", moBuffer)\n" "add_value(\"min\", x)\n" "x = dcp.max(\"Serra do Mar\", \"Pluvio\", moBuffer)\n" "add_value(\"max\", x)\n" "x = dcp.mean(\"Serra do Mar\", \"Pluvio\", moBuffer)\n" "add_value(\"mean\", x)\n" "x = dcp.median(\"Serra do Mar\", \"Pluvio\", moBuffer)\n" "add_value(\"median\", x)\n" "x = dcp.standard_deviation(\"Serra do Mar\", \"Pluvio\", moBuffer)\n" "add_value(\"standardDeviation\", x)\n"; Analysis* analysis = new Analysis; AnalysisPtr analysisPtr(analysis); analysis->id = 1; analysis->name = "Min DCP"; analysis->script = script; analysis->scriptLanguage = ScriptLanguage::PYTHON; analysis->type = AnalysisType::MONITORED_OBJECT_TYPE; analysis->active = false; analysis->outputDataSeriesId = 3; analysis->serviceInstanceId = 1; analysis->metadata["INFLUENCE_TYPE"] = "1"; analysis->metadata["INFLUENCE_RADIUS"] = "50"; analysis->metadata["INFLUENCE_RADIUS_UNIT"] = "km"; terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr dataProviderPtr(dataProvider); dataProvider->name = "Provider"; dataProvider->uri += TERRAMA2_DATA_DIR; dataProvider->uri += "/shapefile"; dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; dataProvider->dataProviderType = "FILE"; dataProvider->active = true; dataProvider->id = 1; dataManager->add(dataProviderPtr); terrama2::core::DataSeries* dataSeries = new terrama2::core::DataSeries(); terrama2::core::DataSeriesPtr dataSeriesPtr(dataSeries); dataSeries->dataProviderId = dataProvider->id; dataSeries->semantics.code = "STATIC_DATA-ogr"; dataSeries->semantics.dataSeriesType = terrama2::core::DataSeriesType::STATIC; dataSeries->name = "Monitored Object"; dataSeries->id = 1; dataSeries->dataProviderId = 1; //DataSet information terrama2::core::DataSet* dataSet = new terrama2::core::DataSet; terrama2::core::DataSetPtr dataSetPtr(dataSet); dataSet->active = true; dataSet->format.emplace("mask", "municipios_afetados.shp"); dataSet->id = 1; dataSeries->datasetList.push_back(dataSetPtr); dataManager->add(dataSeriesPtr); terrama2::core::DataProvider* dataProvider2 = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr dataProvider2Ptr(dataProvider2); dataProvider2->name = "Provider"; dataProvider2->uri += TERRAMA2_DATA_DIR; dataProvider2->uri += "/PCD_serrmar_INPE"; dataProvider2->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; dataProvider2->dataProviderType = "FILE"; dataProvider2->active = true; dataProvider2->id = 2; dataManager->add(dataProvider2Ptr); AnalysisDataSeries monitoredObjectADS; monitoredObjectADS.id = 1; monitoredObjectADS.dataSeriesId = dataSeriesPtr->id; monitoredObjectADS.type = AnalysisDataSeriesType::DATASERIES_MONITORED_OBJECT_TYPE; monitoredObjectADS.metadata["identifier"] = "objet_id_5"; //DataSeries information terrama2::core::DataSeries* dcpSeries = new terrama2::core::DataSeries; terrama2::core::DataSeriesPtr dcpSeriesPtr(dcpSeries); dcpSeries->dataProviderId = dataProvider2->id; auto& semanticsManager = terrama2::core::SemanticsManager::getInstance(); dcpSeries->semantics = semanticsManager.getSemantics("DCP-inpe"); dcpSeries->semantics.dataSeriesType = terrama2::core::DataSeriesType::DCP; dcpSeries->name = "Serra do Mar"; dcpSeries->id = 2; dcpSeries->dataProviderId = 2; //DataSet information terrama2::core::DataSetDcp* dcpDataset69034 = new terrama2::core::DataSetDcp; terrama2::core::DataSetDcpPtr dcpDataset69034Ptr(dcpDataset69034); dcpDataset69034->active = true; dcpDataset69034->format.emplace("mask", "69033.txt"); dcpDataset69034->format.emplace("timezone", "-02:00"); dcpDataset69034->dataSeriesId = 2; dcpDataset69034->id = 2; dcpDataset69034->position = std::shared_ptr<te::gm::Point>(new te::gm::Point(-44.46540, -23.00506, 4618, nullptr)); dcpSeries->datasetList.push_back(dcpDataset69034Ptr); terrama2::core::DataSetDcp* dcpDataset30886 = new terrama2::core::DataSetDcp; terrama2::core::DataSetDcpPtr dcpDataset30886Ptr(dcpDataset30886); dcpDataset30886->active = true; dcpDataset30886->format.emplace("mask", "30886.txt"); dcpDataset30886->format.emplace("timezone", "-02:00"); dcpDataset30886->dataSeriesId = 2; dcpDataset30886->id = 3; dcpDataset30886->position = std::shared_ptr<te::gm::Point>(new te::gm::Point(-46.121, -23.758, 4618, nullptr)); dcpSeries->datasetList.push_back(dcpDataset30886Ptr); AnalysisDataSeries dcpADS; dcpADS.id = 2; dcpADS.dataSeriesId = dcpSeriesPtr->id; dcpADS.type = AnalysisDataSeriesType::ADDITIONAL_DATA_TYPE; dataManager->add(dcpSeriesPtr); std::vector<AnalysisDataSeries> analysisDataSeriesList; analysisDataSeriesList.push_back(dcpADS); analysisDataSeriesList.push_back(monitoredObjectADS); analysis->analysisDataSeriesList = analysisDataSeriesList; analysis->schedule.frequency = 1; analysis->schedule.frequencyUnit = "min"; dataManager->add(analysisPtr); // Starts the service and adds the analysis Service service(dataManager); terrama2::core::ServiceManager::getInstance().setInstanceId(1); auto logger = std::make_shared<AnalysisLogger>(); logger->setConnectionInfo(connInfo); service.setLogger(logger); service.start(); service.addAnalysis(1); QTimer timer; QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit())); timer.start(30000); app.exec(); terrama2::core::finalizeTerraMA(); return 0; }
MainForm::MainForm( QApplication *app, const QString& songFilename ) : QMainWindow( 0, 0 ) , Object( __class_name ) { setMinimumSize( QSize( 1000, 500 ) ); setWindowIcon( QPixmap( Skin::getImagePath() + "/icon16.png" ) ); #ifndef WIN32 if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigusr1Fd)) qFatal("Couldn't create HUP socketpair"); snUsr1 = new QSocketNotifier(sigusr1Fd[1], QSocketNotifier::Read, this); connect(snUsr1, SIGNAL(activated(int)), this, SLOT( handleSigUsr1() )); #endif m_pQApp = app; m_pQApp->processEvents(); // Load default song Song *song = NULL; if ( !songFilename.isEmpty() ) { song = Song::load( songFilename ); if (song == NULL) { //QMessageBox::warning( this, "Hydrogen", trUtf8("Error loading song.") ); song = Song::get_empty_song(); song->set_filename( "" ); } } else { Preferences *pref = Preferences::get_instance(); bool restoreLastSong = pref->isRestoreLastSongEnabled(); QString filename = pref->getLastSongFilename(); if ( restoreLastSong && ( !filename.isEmpty() )) { song = Song::load( filename ); if (song == NULL) { //QMessageBox::warning( this, "Hydrogen", trUtf8("Error restoring last song.") ); song = Song::get_empty_song(); song->set_filename( "" ); } } else { song = Song::get_empty_song(); song->set_filename( "" ); } } h2app = new HydrogenApp( this, song ); h2app->addEventListener( this ); createMenuBar(); h2app->setStatusBarMessage( trUtf8("Hydrogen Ready."), 10000 ); initKeyInstMap(); // we need to do all this to support the keyboard playing // for all the window modes h2app->getMixer()->installEventFilter (this); h2app->getPatternEditorPanel()->installEventFilter (this); h2app->getPatternEditorPanel()->getPianoRollEditor()->installEventFilter (this); h2app->getSongEditorPanel()->installEventFilter (this); h2app->getPlayerControl()->installEventFilter(this); InstrumentEditorPanel::get_instance()->installEventFilter(this); h2app->getAudioEngineInfoForm()->installEventFilter(this); h2app->getDirector()->installEventFilter(this); // h2app->getPlayListDialog()->installEventFilter(this); installEventFilter( this ); showDevelWarning(); connect( &m_autosaveTimer, SIGNAL(timeout()), this, SLOT(onAutoSaveTimer())); m_autosaveTimer.start( 60 * 1000 ); #ifdef H2CORE_HAVE_LASH if ( Preferences::get_instance()->useLash() ){ LashClient* lashClient = LashClient::get_instance(); if (lashClient->isConnected()) { // send alsa client id now since it can only be sent // after the audio engine has been started. Preferences *pref = Preferences::get_instance(); if ( pref->m_sMidiDriver == "ALSA" ) { // infoLog("[LASH] Sending alsa seq id to LASH server"); lashClient->sendAlsaClientId(); } // start timer for polling lash events lashPollTimer = new QTimer(this); connect( lashPollTimer, SIGNAL( timeout() ), this, SLOT( onLashPollTimer() ) ); lashPollTimer->start(500); } } #endif //playlist display timer QTimer *playlistDisplayTimer = new QTimer(this); connect( playlistDisplayTimer, SIGNAL( timeout() ), this, SLOT( onPlaylistDisplayTimer() ) ); playlistDisplayTimer->start(30000); // update player control at // ~ playlist display timer //beatcouter Hydrogen::get_instance()->setBcOffsetAdjust(); // director EventQueue::get_instance()->push_event( EVENT_METRONOME, 1 ); EventQueue::get_instance()->push_event( EVENT_METRONOME, 3 ); undoView = new QUndoView(h2app->m_undoStack); undoView->setWindowTitle(tr("Undo history")); undoView->setWindowIcon( QPixmap( Skin::getImagePath() + "/icon16.png" ) ); //restore last playlist if( Preferences::get_instance()->isRestoreLastPlaylistEnabled() ){ bool loadlist = h2app->getPlayListDialog()->loadListByFileName( Preferences::get_instance()->getLastPlaylistFilename() ); if( !loadlist ){ _ERRORLOG ( "Error loading the playlist" ); } } }
void loadDicomPlugin::start(ctkPluginContext* context) { std::cout << "Load Dicom plugin start" << std::endl; instance = this; this->context = context; QTimer *pulseTimer = new QTimer(); connect(pulseTimer, SIGNAL(timeout()), this, SLOT(pulseTimerEvent())); pulseTimer->start(25); this->createWidgetsAndSignalSlotActions(); this->startDicomDataService(); m_ImageLoadedImage= false; m_CTImageDirectory = ""; m_DefaultZoomImageAxial= 1.5; m_DefaultZoomImageCoronal= 1.5; m_DefaultZoomImageSagittal= 1.5; m_DefaultZoomImageMPR= 1.5; m_WindowLevelImage= 500; m_WindowWidthImage= 300; m_MinWindowLevelValue= -1000; m_MaxWindowLevelValue= 4000; m_MinWindowWidhtValue= 0; m_MaxWindowWidhtValue= m_MaxWindowLevelValue - m_MinWindowLevelValue; m_toolFrameLoadDicomGUI.mainViewSliderWindowLevel->setMinimum(m_MinWindowLevelValue); m_toolFrameLoadDicomGUI.mainViewSliderWindowLevel->setMaximum(m_MaxWindowLevelValue); m_toolFrameLoadDicomGUI.mainViewSliderWindowWidht->setMinimum(m_MinWindowWidhtValue); m_toolFrameLoadDicomGUI.mainViewSliderWindowWidht->setMaximum(m_MaxWindowWidhtValue); //connect(m_toolFrameLoadDicomGUI.loadImageFilePushButton, SIGNAL(clicked()), this, SLOT(updateImageData())); connect(m_toolFrameLoadDicomGUI.loadImageFilePushButton, SIGNAL(clicked()),this, SLOT(readCTDataset())); connect(m_mainFrameDicomViewGUI.scrollBarAxial, SIGNAL(valueChanged(int)), this, SLOT(resliceImageViews(int))); connect(m_mainFrameDicomViewGUI.scrollBarSagittal, SIGNAL(valueChanged(int)), this, SLOT(resliceImageViews(int))); connect(m_mainFrameDicomViewGUI.scrollBarCoronal, SIGNAL(valueChanged(int)), this, SLOT(resliceImageViews(int))); connect(m_toolFrameLoadDicomGUI.mainViewSliderWindowLevel, SIGNAL(valueChanged(int)), this, SLOT(changeImageWindowing(int))); connect(m_toolFrameLoadDicomGUI.mainViewSliderWindowWidht, SIGNAL(valueChanged(int)), this, SLOT(changeImageWindowing(int))); m_toolFrameLoadDicomGUI.loadDicomProgressBar->setVisible(false); m_ImageWorldReference = AxesObjectImageType::New(); std::cout<<"initializeWorldReference OK"<<std::endl; igstk::Transform transform; transform.SetToIdentity( 1e300 ); m_PickedPoint= EllipsoidType::New(); m_PickedPoint->RequestSetTransformAndParent( transform , this->m_ViewMPR); m_PickedPointRepresentation= EllipsoidRepresentationType::New(); //m_PickedPointRepresentation->SetLogger(logger); m_PickedPoint->SetRadius( 2, 2, 2 ); m_PickedPointRepresentation->RequestSetEllipsoidObject( m_PickedPoint ); m_PickedPointRepresentation->SetColor(1.0,1.0,0.0); m_PickedPointRepresentation->SetOpacity(1.0); this->initializeQuadrantView(); }
PerformanceMeasurement::Panel::Panel(QWidget *parent) : QWidget(parent, 0, Qt::WStyle_NormalBorder | Qt::WDestructiveClose), Workspace::Instance( "Performance Measuremnt", vars, num_vars ), state( INIT1), duration( 0 ), lastRead( 0 ), timestep( 0 ), maxDuration( 0 ), maxTimestep( 0 ), jitter( 0 ) { QHBox *hbox; QBoxLayout *layout = new QVBoxLayout(this); setCaption("Real-time Benchmarks"); hbox = new QHBox(this); layout->addWidget(hbox); QChar mu = QChar(0x3BC); QString suffix = QString("s)"); QString labeltext = "Computation Time ("; labeltext.append(mu); labeltext.append(suffix); (void) (new QLabel(labeltext, hbox))->setFixedWidth(175); durationEdit = new QLineEdit(hbox); hbox = new QHBox(this); layout->addWidget(hbox); labeltext = "Peak Computation Time ("; labeltext.append(mu); labeltext.append(suffix); (void) (new QLabel(labeltext, hbox))->setFixedWidth(175); maxDurationEdit = new QLineEdit(hbox); hbox = new QHBox(this); layout->addWidget(hbox); labeltext = "Real-time Period ("; labeltext.append(mu); labeltext.append(suffix); (void) (new QLabel(labeltext, hbox))->setFixedWidth(175); timestepEdit = new QLineEdit(hbox); hbox = new QHBox(this); layout->addWidget(hbox); labeltext = "Peak Real-time Period ("; labeltext.append(mu); labeltext.append(suffix); (void) (new QLabel(labeltext, hbox))->setFixedWidth(175); maxTimestepEdit = new QLineEdit(hbox); QToolTip::add(maxTimestepEdit, "The worst case time step"); hbox = new QHBox(this); layout->addWidget(hbox); labeltext = "Real-time Jitter ("; labeltext.append(mu); labeltext.append(suffix); (void) (new QLabel(labeltext, hbox))->setFixedWidth(175); timestepJitterEdit = new QLineEdit(hbox); QToolTip::add(timestepJitterEdit, "The variance in the real-time period"); hbox = new QHBox(this); layout->addWidget(hbox); QPushButton *resetButton = new QPushButton("Reset", this); layout->addWidget(resetButton); QObject::connect(resetButton,SIGNAL(clicked(void)),this,SLOT(reset(void))); QTimer *timer = new QTimer(this); timer->start(500); QObject::connect(timer,SIGNAL(timeout(void)),this,SLOT(update(void))); // Connect states to workspace setData( Workspace::STATE, 0, &duration ); setData( Workspace::STATE, 1, &maxDuration ); setData( Workspace::STATE, 2, ×tep ); setData( Workspace::STATE, 3, &maxTimestep ); setData( Workspace::STATE, 4, &jitter ); setActive(true); saveStats = false; }
QObject* ScriptingModule::createTimer(bool single_shot) { QTimer* t = new QTimer(this); t->setSingleShot(single_shot); return t; }
void SplineRoad::RebuildRoadInt(bool editorAlign) { if (!rebuild && !editorAlign) return; rebuild = false; // segments range int segs = getNumPoints(); if (segs == 0 || segs == 1) return; using std::vector; using std::min; using std::max; UpdRot(); // if (vSegs.size() != segs || editorAlign) iDirtyId = -1; // force full int sMin = 0, sMax = segs; // update 4 segs only (fast) if (iDirtyId != -1 && segs >= 4) { // else !isLooped case ... sMin =/* max(0,*/ iDirtyId-2; sMax =/* min(segs,*/ iDirtyId+2; } // full rebuild QTimer ti; ti.update(); /// time if (iDirtyId == -1) { DestroyRoad(); for (int seg=0; seg < segs; ++seg) { RoadSeg rs; rs.empty = true; vSegs.push_back(rs); } } /// Auto angles prepass ... if (segs > 2) for (int seg=0; seg < segs; ++seg) { //int seg1 = (seg+1) % segs; // next int seg0 = (seg-1+segs) % segs; // prev if (mP[seg].aType == AT_Manual) { mP[seg].aYaw = mP[seg].mYaw; mP[seg].aRoll = mP[seg].mRoll; } else { mP[seg].aRoll = 0.f; /// ... roll getangle?, +180 loops?, len const Real dist = 0.1f; Vector3 vl = GetLenDir(seg, 0.f, dist) + GetLenDir(seg0, 1.f-dist, 1.f); //vl.normalise(); Vector3 vw = Vector3(vl.z, 0.f, -vl.x); //vw.normalise(); mP[seg].aYaw = GetAngle(vw.x, vw.z) *180.f/PI_d; if (mP[seg].aType == AT_Both) { mP[seg].aYaw += mP[seg].mYaw; mP[seg].aRoll += mP[seg].mRoll; } } } ///-------------------------------------------------------------------------------------------------------------------------- /// LOD ///-------------------------------------------------------------------------------------------------------------------------- //> data at lod 0 vector<int> viLSteps0; vector<Real> vSegTc0; vector<Vector3> vnSeg0; // normals const int lodDivs[LODs] = {1,2,4,8}; for (int lod = 0; lod < LODs; ++lod) { int lodDiv = lodDivs[lod]; Real lenDiv = lenDiv0 * lodDiv; LogR("LOD: "+toStr(lod)+" ---"); /// segment data pre pass //--------------------------------------------------------------------------------------- //> data at cur lod vector<int> viL, viW; // vi num steps for seg Length/Width vector<int> vbSegMrg; // bool 0 if seg merged, 1 if new vector<Real> vSegTc, vSegLen; vector<Vector3> vwSeg; vector<vector <int> > viwLS; // width steps per length point, for each seg vector<int> viwEq; // 1 if equal width steps at whole length, in seg Real sumLenMrg = 0.f, ltc = 0.f; int mrgGrp = 0; //# stats Real roadLen = 0.f, rdOnT = 0.f, rdPipe = 0.f, avgWidth = 0.f, stMaxH = FLT_MIN, stMinH = FLT_MAX; //if (lod == 0)? LogR("--- seg prepass ---"); for (int seg=0; seg < segs; ++seg) { int seg1 = (seg+1) % segs; // next int seg0 = (seg-1+segs) % segs; // prev // width steps -- Real sp = mP[seg].pipe, sp1 = mP[seg1].pipe, sp0 = mP[seg0].pipe; Real p = sp * iwPmul, pl = max(sp, sp1)* iwPmul/4; if (p < 0.f) p = 1.f; else p = 1.f + p; if (pl< 0.f) pl= 1.f; else pl= 1.f + pl; int iw = max(1, (int)(p * iw0 / lodDiv)); //* wid/widDiv.. viW.push_back(iw); int iwl = max(1, (int)(pl * iw0 / lodDiv)); // length steps | Real len = GetSegLen(seg); int il = int(len / lenDiv) / iwl * iwl + iwl; Real la = 1.f / il; viL.push_back(il); vSegLen.push_back(len); roadLen += len; //# if (sp > 0.f || sp1 > 0.f) rdPipe += len; //# ///- Merge conditions sumLenMrg += len; // mtr changes int hid = mP[seg].idMtr, hid1 = mP[seg1].idMtr, hid0 = mP[seg0].idMtr; LogR(toStr(sp0) + " " + toStr(sp) + " " + toStr(sp1)); // merge road and pipe segs, don't merge transitions if (sp != sp1 || sp != sp0 || hid != hid1 || hid != hid0) { sumLenMrg = 0.f; ++mrgGrp; vbSegMrg.push_back(1); } else // onTer change if (mP[seg].onTer != mP[seg1].onTer || mP[seg].onTer != mP[seg0].onTer) { sumLenMrg = 0.f; ++mrgGrp; vbSegMrg.push_back(1); } else if (sumLenMrg >= setMrgLen) { sumLenMrg -= setMrgLen; ++mrgGrp; vbSegMrg.push_back(1); // bNew }else vbSegMrg.push_back(0); // merged LogR("seg "+toStr(seg)+" iw "+toStr(iw)+" il "+toStr(il)+" pp "+toStr(sp)); if (lod==0) viLSteps0.push_back(il); /// length <dir> | Vector3 vl = GetLenDir(seg, 0, la), vw; vl.normalise(); Real ay = mP[seg].aYaw, ar = mP[seg].aRoll; /// width <dir> --- if (mP[seg].onTer && mP[seg1].onTer) // perpendicular on xz { vw = Vector3(vl.z, 0, -vl.x); vw.normalise(); //mP[seg].angle = atan2(vl.z, -vl.x)*180.f/PI_d+90.f; // set yaw.. }else vw = GetRot(ay,ar); // from angles /// normal <dir> / if (lod == 0) { Vector3 vn = vl.crossProduct(vw); vn.normalise(); //if (vn.y < 0.f) vn = -vn; // always up y+ vnSeg0.push_back(vn); } Real wiMul = mP[seg].width; if (editorAlign) // wider road for align terrain tool wiMul = wiMul*edWmul + edWadd; vw *= wiMul; vwSeg.push_back(vw); avgWidth += mP[seg].width * len; //# if (!mP[seg].onTer || !mP[seg1].onTer) rdOnT += len; //# // tcs seg il* len Real l = 0.f; for (int i = 0; i < il; ++i) // length +1 { // length dir Vector3 vl = GetLenDir(seg, l, l+la); l += la; ltc += vl.length(); } vSegTc.push_back(ltc); if (lod == 0) vSegTc0.push_back(ltc); } LogR("--- seg prepass2 viwLS ---"); for (int seg=0; seg < segs; ++seg) { int seg1 = (seg+1) % segs; // next int il = viL[seg]; vector<int> viwL; // width steps per lenght point in cur seg int iw0 = viW[seg], iw1 = viW[seg1]; //String ss=""; for (int i = -1; i <= il+1; ++i) // length +1 +2-gap { int ii = max(0, min(il, i)); int iw = iw0 + (int)( Real(ii)/Real(il) * (iw1-iw0) ); //if (i==0 || i == il) // ss += toStr(iw)+" "; viwL.push_back(iw); } int eq = iw1==iw0 ? 1 : 0; viwEq.push_back(eq); viwLS.push_back(viwL); //if (!eq) vbSegMrg[seg] = 1; //LogR("seg "+toStr(seg)+" >> "+ss); } //# stats at lod0, whole road bool stats = lod == 0 && iDirtyId == -1; if (stats) { st.Length = roadLen; st.WidthAvg = avgWidth / roadLen; st.OnTer = rdOnT / roadLen * 100.f; st.Pipes = rdPipe / roadLen * 100.f; segsMrg = mrgGrp; } //-------------------------------------------------------------------------------------------------------------------------- /// segment //-------------------------------------------------------------------------------------------------------------------------- //> mesh data W-wall C-column vector<Vector4> clr0/*empty*/, clr; vector<Vector3> pos,norm, posW,normW, posC,normC, posLod; vector<Vector2> tcs, tcsW, tcsC; Real tc1 = 0; ltc = 0; int iLmrg = 0, iLmrgW = 0, iLmrgC = 0; Vector3 vlOld; int sNum = sMax - sMin, segM = sMin;//, sNumO = sNum; while (sNum > 0) { int seg = (segM + segs) % segs; // iterator int seg1 = (seg+1) % segs; // next //if (lod == 0) //LogR("[Seg] cur: " + toStr(seg) + "/" + toStr(sNumO) + " all:" + toStr(segs));/**/ // on terrain (whole seg) bool onTer = mP[seg].onTer && mP[seg1].onTer; // on merging segs only for game in whole road rebuild // off for editor (partial, 4segs rebuild) bool bNew = true, bNxt = true; if (bMerge) { bNew = (segM == sMin/*1st*/) || vbSegMrg[seg]; bNxt = (segM+1 == sMax/*last*/) || vbSegMrg[seg1]; // next is new } if (bNew) //> new seg data { iLmrg = 0; iLmrgW = 0; iLmrgC = 0; pos.clear(); norm.clear(); tcs.clear(); clr.clear(); posW.clear(); normW.clear(); tcsW.clear(); posC.clear(); normC.clear(); tcsC.clear(); } // bullet create bool blt = true; // game always #ifdef ROAD_EDITOR // editor only sel segs for align ter tool blt = editorAlign && vSel.find(seg) != vSel.end(); #endif /// destroy old RoadSeg& rs = vSegs[seg]; if (!rs.empty && lod == 0) DestroySeg(seg); const int iwW = 7; // wall width steps - types.. const int iwC = colN; // column polygon steps // steps len int il = viL[seg]; Real la = 1.f / il; int il0= viLSteps0[seg]; Real la0= 1.f / il0 * skLen; Real l = -la0; // width //Real wi1 = abs(mP[seg].width), wi2 = abs(mP[seg1].width), wi12 = wi2-wi1; /// angles ()__ Real ay1 = mP[seg].aYaw, ay2 = mP[seg1].aYaw, ay21 = ay2-ay1; Real ar1 = mP[seg].aRoll,ar2 = mP[seg1].aRoll,ar21 = ar2-ar1; const Real asw = 180; // more than 180 swirl - wrong at start/end while (ay21 > asw) ay21 -= 2*asw; while (ay21 <-asw) ay21 += 2*asw; while (ar21 > asw) ar21 -= 2*asw; while (ar21 <-asw) ar21 += 2*asw; // tc begin,range Real tcBeg = (seg > 0) ? vSegTc[seg-1] : 0.f, tcEnd = vSegTc[seg], tcRng = tcEnd - tcBeg; Real tcBeg0= (seg > 0) ? vSegTc0[seg-1]: 0.f, tcEnd0 = vSegTc0[seg], tcRng0 = tcEnd0 - tcBeg0; Real tcRmul = tcRng0 / tcRng; //------------------------------------------------------------------------------------ // Length vertices //------------------------------------------------------------------------------------ //LogR( " __len"); if (mP[seg].idMtr >= 0) // -1 hides segment for (int i = -1; i <= il+1; ++i) // length +1 +2-gap { ++iLmrg; /// length <dir> | Vector3 vL0 = interpolate(seg, l); Vector3 vl = GetLenDir(seg, l, l+la), vw; Real len = vl.length(); vl.normalise(); // len tc if (i <= 0) ltc = 0; Real tc = ltc * tcRmul + tcBeg0; // skirt tc if (i == -1) tc =-skLen* tcRmul + tcBeg0; if (i == il+1) tc = skLen* tcRmul + tcEnd0; /// width <dir> -- if (mP[seg].onTer && mP[seg1].onTer) { vw = Vector3(vl.z, 0, -vl.x); } else /// angles ()__ { Real ay = ay1 + ay21 * l; // linear- Real ar = ar1 + ar21 * l; //Real ay = interpAYaw(seg,l); // spline~ //Real ar = interpARoll(seg,l); // err swirl.. vw = GetRot(ay,ar); // from angles } vw.normalise(); Vector3 vwn = vw; //Real wiMul = wi1 + wi12 * l; // linear- Real wiMul = interpWidth(seg, l); // spline~ if (editorAlign) // wider road for align terrain tool wiMul = wiMul*edWmul + edWadd; vw *= wiMul; // last vw = 1st form next seg if (i==il && seg < segs-1) vw = vwSeg[seg+1]; // on terrain ~~ bool onTer1 = onTer || mP[seg].onTer && i==0 || mP[seg1].onTer && i==il; /// normal <dir> / Vector3 vn = vl.crossProduct(vw); vn.normalise(); if (i==0) vn = vnSeg0[seg]; // seg start=end if (i==il) vn = vnSeg0[seg1]; //Vector3 vnu = vn; if (vnu.y < 0) vnu = -vnu; // always up y+ // width steps <-> //int iw = viW[seg]; int iw = viwLS[seg][i+1]; //i = -1 .. il+1 // pipe width Real l01 = max(0.f, min(1.f, Real(i)/Real(il) )); Real p1 = mP[seg].pipe, p2 = mP[seg1].pipe; Real pipe = p1 + (p2-p1)*l01; bool trans = (p1 == 0.f || p2 == 0.f) && !viwEq[seg]; Real trp = (p1 == 0.f) ? 1.f - l01 : l01; //LogR(" il="+toStr(i)+"/"+toStr(il)+" iw="+toStr(iw) // /*+(bNew?" New ":"") +(bNxt?" Nxt ":"")/**/); /// road ~ Width vertices //----------------------------------------------------------------------------------------------------------------- for (int w=0; w <= iw; ++w) // width +1 { // pos create Vector3 vP,vN; Real tcw = Real(w)/Real(iw); Real yTer = 0.f; if (pipe == 0.f) { // flat -- vP = vL0 + vw * (tcw - 0.5); vN = vn; yTer = mTerrain ? mTerrain->getHeightAtWorldPosition(vP.x, 0, vP.z) : 0.f; if (onTer1) // onTerrain { vP.y = yTer + fHeight * ((w==0 || w==iw) ? 0.15f : 1.f); vN = mTerrain ? getNormalAtWorldPosition(mTerrain, vP.x, vP.z, lenDiv*0.5f /*0.5f*/) : Vector3::UNIT_Y; } }else { /// pipe (_) Real oo = (tcw - 0.5)/0.5 * PI_d * pipe, so = sinf(oo), co = cosf(oo); vP = vL0 + vw * 0.5 * so + + vn * (0.5 - 0.5 * co) * wiMul; vN = vn * co + vwn * so; if (vN.y < 0.f) vN.y = -vN.y; if (trans) // transition from flat to pipe { vP += vw * (tcw - 0.5) * trp; } yTer = mTerrain ? mTerrain->getHeightAtWorldPosition(vP.x, 0, vP.z) : 0.f; } // skirt, gap patch_ if (i == -1 || i == il+1) vP -= vn * skH; // color - for minimap preview // ---~~~====~~~--- Real brdg = min(1.f, abs(vP.y - yTer) * 0.4f); //par ] height diff mul Real h = max(0.f, 1.f - abs(vP.y - yTer) / 30.f); // for grass dens tex Real blend = 0.f; //rand()%1000/1000.f; // TODO: blend 2materials...? Vector4 c(brdg,pipe, blend, h); //> data road pos.push_back(vP); norm.push_back(vN); tcs.push_back(Vector2(tcw * 1.f /**2p..*/, tc * tcMul)); clr.push_back(c); //# if (vP.y < stMinH) stMinH = vP.y; if (vP.y > stMaxH) stMaxH = vP.y; } /// wall ] //------------------------------------------------------------------------------------ struct stWiPntW { Real x,y, uv, nx,ny; }; // wall width points const static stWiPntW wiPntW[iwW+1][2] = { // section shape // normal road // pipe wall {{-0.5f, -0.1f, 0.0f, 1.0f, 0.0f}, {-0.28f, 0.7f, 0.0f, -1.0f, 0.0f}}, {{-0.5f, 1.2f, 0.5f, 0.5f, 0.5f}, {-0.28f, 0.5f, 0.2f, -0.5f, 0.5f}}, {{-0.56f, 1.2f, 0.2f, -0.5f, 0.5f}, {-0.28f, 0.0f, 0.2f, -0.5f, 0.0f}}, {{-0.56f,-0.9f, 1.6f, -0.5f,-0.5f}, {-0.2f, -0.9f, 0.5f, -0.1f,-0.5f}}, {{ 0.56f,-0.9f, 3.0f, 0.5f,-0.5f}, { 0.2f, -0.9f, 0.5f, 0.1f,-0.5f}}, {{ 0.56f, 1.2f, 1.6f, 0.5f, 0.5f}, { 0.28f, 0.0f, 0.2f, 0.5f, 0.0f}}, {{ 0.5f, 1.2f, 0.2f, -0.5f, 0.5f}, { 0.28f, 0.5f, 0.2f, 0.5f, 0.5f}}, {{ 0.5f, -0.1f, 0.5f, -1.0f, 0.0f}, { 0.28f, 0.7f, 0.2f, 1.0f, 0.0f}}}; Real uv = 0.f; // tc long if (!onTer) if (i >= 0 && i <= il) // length +1 { ++iLmrgW; for (int w=0; w <= iwW; ++w) // width +1 { int pp = (p1 > 0.f || p2 > 0.f) ? 1 : 0; // pipe wall stWiPntW wP = wiPntW[w][pp]; if (trans /*&& (w <= 3 || w >= iwW-3)*/) { wP.x *= 1 + trp; wP.y *= 1 - trp; } uv += wP.uv; Vector3 vP = vL0 + vw * wP.x + vn * wP.y; Vector3 vN = vwn * wP.nx + vn * wP.ny; vN.normalise(); //> data Wall posW.push_back(vP); normW.push_back(vN); tcsW.push_back(0.25f * Vector2(uv, tc * tcMul)); //pars } } /// columns | //------------------------------------------------------------------------------------ if (!onTer && mP[seg].cols > 0) if (i == il/2) // middle- { ++iLmrgC; const Real r = colR; // column radius for (int h=0; h <= 1; ++h) // height for (int w=0; w <= iwC; ++w) // width +1 { Real ht = (h==0) ? 0.f : vL0.y - (mTerrain ? mTerrain->getHeightAtWorldPosition(vL0) : 0.f); Real a = Real(w)/iwC *2*PI_d, //+PI_d/4.f x = r*cosf(a), y = r*sinf(a); Vector3 vlXZ(vl.x,0,vl.z); Real fl = 1.f/max(0.01f, vlXZ.length()); Vector3 vP = vL0 + fl * vl * x + vwn * y; Real yy; if (h==0) // top below road { yy = vn.y * -0.8f; //pars vP.y += yy; ht += yy; } else // bottom below ground { yy = (mTerrain ? mTerrain->getHeightAtWorldPosition(vP) : 0.f) - 0.3f; vP.y = yy; } ht += yy; Vector3 vN(vP.x-vL0.x,0,vP.z-vL0.z); vN.normalise(); //> data Col posC.push_back(vP); normC.push_back(vN); tcsC.push_back(Vector2( Real(w)/iwC * 4, ht * 0.2f )); //pars } } if (i == -1 || i == il) // add len { l += la0; ltc += len; } else { l += la; ltc += len; } } // Length vertices //------------------------------------------------------------------------------------ // lod vis points if (lod == 0) { int lps = max(2, (int)(vSegLen[seg] / lposLen)); for (int p=0; p <= lps; ++p) { Vector3 vp = interpolate(seg, Real(p)/Real(lps)); posLod.push_back(vp); } } //--------------------------------------------------------------------------------------------------------- /// create mesh indices //--------------------------------------------------------------------------------------------------------- if (bNxt && !pos.empty()) /*Merging*/ { String sEnd = toStr(idStr); ++idStr; String sMesh = "rd.mesh." + sEnd, sMeshW = sMesh + "W", sMeshC = sMesh + "C"; posBt.clear(); idx.clear(); // set for addTri at_pos = &pos; at_size = pos.size(); at_ilBt = iLmrg-2; /// road ~ int iiw = 0; //LogR( " __idx"); // equal width steps if (viwEq[seg]==1) for (int i = 0; i < iLmrg-1; ++i) // length-1 +2gap { int iw = viW[seg]; // grid w-1 x l-1 x2 tris for (int w=0; w < iw; ++w) // width-1 { //LogR( " il="+toStr(i)+"/"+toStr(il)+" iw="+toStr(iw)); int f0 = iiw + w, f1 = f0 + (iw+1); addTri(f0+0,f1+1,f0+1,i, blt); addTri(f0+0,f1+0,f1+1,i, blt); } iiw += iw+1; } else // pipe, diff width_ for (int i = 0; i < iLmrg-1; ++i) // length-1 +2gap { int iw = viwLS[seg][i], iw1 = viwLS[seg][i+1]; int sw = iw1 < iw ? 1 : 0; //LogR( " il="+toStr(i)+"/"+toStr(il)+" iw="+toStr(iw)); //int w=0; // test fans for (int w=0; w < iw -sw; ++w) // width-1 { int f0 = iiw + w, f1 = f0 + (iw+1); // |\ | f0+0 f0+1 // | \| f1+0 f1+1 if (sw==0) { addTri(f0+0,f1+1,f0+1,i, blt); addTri(f0+0,f1+0,f1+1,i, blt); } else { // |/| addTri(f0+0,f1+0,f0+1,i, blt); addTri(f0+1,f1+0,f1+1,i, blt); } } ///>>> fix gaps when iw changes - fan tris int ma = iw1 - iw, ms = -ma, m; for (m=0; m < ma; ++m) { int f0 = iiw + iw-1, f1 = f0 + (iw+2)+m; addTri(f0+1,f1+0,f1+1,i, blt); } for (m=0; m < ms; ++m) { int f0 = iiw + iw-sw -m, f1 = f0 + (iw+1); addTri(f0+0,f1+0,f0+1,i, blt); } iiw += iw + 1; } vSegs[seg].nTri[lod] = idx.size()/3; // create Ogre Mesh //----------------------------------------- MeshPtr meshOld = MeshManager::getSingleton().getByName(sMesh); if (!meshOld.isNull()) LogR("Mesh exists !!!" + sMesh); AxisAlignedBox aabox; MeshPtr mesh = MeshManager::getSingleton().createManual(sMesh,"General"); SubMesh* sm = mesh->createSubMesh(); int id = max(0,mP[seg].idMtr); if (isPipe(seg)) rs.sMtrRd = sMtrPipe[id]; else rs.sMtrRd = sMtrRoad[id] + (onTer ? "_ter" :""); CreateMesh(sm, aabox, pos,norm,clr,tcs, idx, rs.sMtrRd); MeshPtr meshW, meshC; // ] | bool wall = !posW.empty(); if (wall) { meshW = MeshManager::getSingleton().createManual(sMeshW,"General"); meshW->createSubMesh(); } bool cols = !posC.empty() && lod == 0; // cols have no lods if (cols) { meshC = MeshManager::getSingleton().createManual(sMeshC,"General"); meshC->createSubMesh(); } //*=*/wall = 0; cols = 0; // test /// wall ] //------------------------------------------------------------------------------------ // wall pipe glass mtr bool wPglass = isPipe(seg) && mP[seg].idMtr >= 1; // wall pipe glass mtr //bool wPglass = isPipe(seg) && StringUtil::match(sMtrPipe[mP[seg].idMtr], "*lass*"); if (wall) { idx.clear(); for (int i = 0; i < iLmrgW-1; ++i) // length { int iiW = (i+0)*(iwW+1); for (int w=0; w < iwW; ++w) // width { int f0 = iiW + w, f1 = f0 + (iwW+1); idx.push_back(f0+1); idx.push_back(f1+1); idx.push_back(f0+0); idx.push_back(f1+1); idx.push_back(f1+0); idx.push_back(f0+0); } } // front plates start,end const int Wid[4/*6*/][3] = {{2,1,0},{3,2,0},{5,4,7},{6,5,7}/*,{7,3,0},{4,3,7}*/}; int i,f, b = posW.size()-iwW-1; if (!isPipe(seg)) // no fronts in pipes for (f=0; f < 4; ++f) { for (i=0; i<=2; ++i) idx.push_back( Wid[f][i] ); for (i=0; i<=2; ++i) idx.push_back( Wid[f][2-i]+b ); } vSegs[seg].nTri[lod] += idx.size()/3; sm = meshW->getSubMesh(0); // for glass only.. rs.sMtrWall = !wPglass ? sMtrWall : sMtrWallPipe; if (!posW.empty()) CreateMesh(sm, aabox, posW,normW,clr0,tcsW, idx, rs.sMtrWall); } /// columns | //------------------------------------------------------------------------------------ if (cols) { idx.clear(); at_pos = &posC; for (int l=0; l < iLmrgC; ++l) for (int w=0; w < iwC; ++w) { int f0 = w + l*(iwC+1)*2, f1 = f0 + iwC+1; addTri(f0+0, f1+1, f0+1, 1, blt); addTri(f0+0, f1+0, f1+1, 1, blt); } vSegs[seg].nTri[lod] += idx.size()/3; sm = meshC->getSubMesh(0); //if (!posC.empty()) CreateMesh(sm, aabox, posC,normC,clr0,tcsC, idx, sMtrCol); } // add Mesh to Scene ----------------------------------------- Entity* ent = 0, *entW = 0, *entC = 0; SceneNode* node = 0, *nodeW = 0, *nodeC = 0; AddMesh(mesh, sMesh, aabox, &ent, &node, "."+sEnd); if (wPglass) { ent->setRenderQueueGroup(RQG_PipeGlass); //ent->setCastShadows(true); } if (wall /*&& !posW.empty()*/) { AddMesh(meshW, sMeshW, aabox, &entW, &nodeW, "W."+sEnd); entW->setCastShadows(true); // only cast } if (cols /*&& !posC.empty()*/) { AddMesh(meshC, sMeshC, aabox, &entC, &nodeC, "C."+sEnd); entC->setVisible(true); if (bCastShadow) entC->setCastShadows(true); } if (bCastShadow && !onTer) ent->setCastShadows(true); //>> store ogre data ------------ rs.road[lod].node = node; rs.wall[lod].node = nodeW; rs.road[lod].ent = ent; rs.wall[lod].ent = entW; rs.road[lod].mesh = mesh; rs.wall[lod].mesh = meshW; rs.road[lod].smesh = sMesh; rs.wall[lod].smesh = sMeshW; if (lod==0) { rs.col.node = nodeC; rs.col.ent = entC; rs.col.mesh = meshC; rs.col.smesh = sMeshC; } rs.empty = false; // new // copy lod points if (lod == 0) { for (size_t p=0; p < posLod.size(); ++p) rs.lpos.push_back(posLod[p]); posLod.clear(); } //# stats-- if (stats) { rs.mrgLod = (iMrgSegs % 2)*2+1; //- iMrgSegs++; // count, full } /// bullet trimesh at lod 0 ///------------------------------------------------------------------------------------ if (lod == 0 && blt) { btTriangleMesh* trimesh = new btTriangleMesh(); vbtTriMesh.push_back(trimesh); #define vToBlt(v) btVector3(v.x, -v.z, v.y) #define addTriB(a,b,c) trimesh->addTriangle(vToBlt(a), vToBlt(b), vToBlt(c), blt); size_t si = posBt.size(), a=0; // %3! for (size_t i=0; i < si/3; ++i,a+=3) addTriB(posBt[a], posBt[a+1], posBt[a+2]); // if (cols) // add columns^.. // Road ~ btCollisionShape* shape = new btBvhTriangleMeshShape(trimesh, true); shape->setUserPointer(isPipe(seg) ? (void*)7788 : (void*)7777); // mark as road, + mtrId.. //btRigidBody::btRigidBodyConstructionInfo infoT(0.f, 0, shape); //infoT.m_restitution = 0.0f; //infoT.m_friction = 0.8f; // 1 like terrain //pGame->collision.AddRigidBody(infoT); // old btCollisionObject* bco = new btCollisionObject(); btTransform tr; tr.setIdentity(); //tr.setOrigin(pc); bco->setActivationState(DISABLE_SIMULATION); bco->setCollisionShape(shape); bco->setWorldTransform(tr); bco->setFriction(0.8f); bco->setRestitution(0.f); //` bco->setCollisionFlags(bco->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_DISABLE_VISUALIZE_OBJECT/**/); #ifdef ROAD_EDITOR pApp->world->addCollisionObject(bco); #else pGame->collision.world->addCollisionObject(bco); pGame->collision.shapes.push_back(shape); #endif // Wall ] #ifndef ROAD_EDITOR // in Game if (wall) { trimesh = new btTriangleMesh(); vbtTriMesh.push_back(trimesh); for (int i = 0; i < iLmrgW-1; ++i) // length { int iiW = i* (iwW+1); for (int w=0; w < iwW; ++w) // width if (bRoadWFullCol || w==0 || w == iwW-1) // only 2 sides|_| optym+ { int f = iiW + w, f1 = f + (iwW+1); addTriB(posW[f+0], posW[f1+1], posW[f+1]); addTriB(posW[f+0], posW[f1+0], posW[f1+1]); } } btCollisionShape* shape = new btBvhTriangleMeshShape(trimesh, true); shape->setUserPointer((void*)7777); //- + road mtr id todo... btCollisionObject* bco = new btCollisionObject(); bco->setActivationState(DISABLE_SIMULATION); bco->setCollisionShape(shape); bco->setWorldTransform(tr); bco->setFriction(0.1f); bco->setRestitution(0.f); //` bco->setCollisionFlags(bco->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_DISABLE_VISUALIZE_OBJECT/**/); pGame->collision.world->addCollisionObject(bco); pGame->collision.shapes.push_back(shape); } #endif } }/*bNxt Merging*/ sNum--; segM++; // next } /// segment end //-------------------------------------------------------------------------------------------------------------------------- //# stats if (stats) st.HeightDiff = max(0.f, stMaxH - stMinH); } // lod end UpdLodVis(fLodBias); if (iDirtyId == -1) iOldHide = -1; if (iDirtyId == -1) //if (segs <= 4 || sMax - sMin > 4) { ti.update(); /// time float dt = ti.dt * 1000.f; LogO(String("::: Time Road Rebuild: ") + toStr(dt) + " ms"); } }
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); }
int main(int argc, char* argv[]) { terrama2::core::TerraMA2Init terramaRaii("example", 0); terrama2::core::registerFactories(); auto& serviceManager = terrama2::core::ServiceManager::getInstance(); te::core::URI uri("pgsql://"+TERRAMA2_DATABASE_USERNAME+":"+TERRAMA2_DATABASE_PASSWORD+"@"+TERRAMA2_DATABASE_HOST+":"+TERRAMA2_DATABASE_PORT+"/"+TERRAMA2_DATABASE_DBNAME); serviceManager.setLogConnectionInfo(uri); terrama2::services::analysis::core::PythonInterpreterInit pythonInterpreterInit; { QCoreApplication app(argc, argv); DataManagerPtr dataManager(new DataManager()); // DataProvider information terrama2::core::DataProvider* outputDataProvider = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr outputDataProviderPtr(outputDataProvider); outputDataProvider->id = 3; outputDataProvider->name = "DataProvider postgis"; outputDataProvider->uri = uri.uri(); outputDataProvider->intent = terrama2::core::DataProviderIntent::PROCESS_INTENT; outputDataProvider->dataProviderType = "POSTGIS"; outputDataProvider->active = true; dataManager->add(outputDataProviderPtr); auto& semanticsManager = terrama2::core::SemanticsManager::getInstance(); // DataSeries information terrama2::core::DataSeries* outputDataSeries = new terrama2::core::DataSeries(); terrama2::core::DataSeriesPtr outputDataSeriesPtr(outputDataSeries); outputDataSeries->id = 3; outputDataSeries->name = "Analysis result"; outputDataSeries->semantics = semanticsManager.getSemantics("ANALYSIS_MONITORED_OBJECT-postgis"); outputDataSeries->dataProviderId = outputDataProviderPtr->id; // DataSet information terrama2::core::DataSet* outputDataSet = new terrama2::core::DataSet(); outputDataSet->active = true; outputDataSet->id = 2; outputDataSet->dataSeriesId = outputDataSeries->id; outputDataSet->format.emplace("table_name", "zonal_history_ratio_analysis_result"); outputDataSeries->datasetList.emplace_back(outputDataSet); dataManager->add(outputDataSeriesPtr); Analysis* analysis = new Analysis; AnalysisPtr analysisPtr(analysis); analysis->id = 1; analysis->name = "Analysis"; analysis->active = true; std::string script = "x = grid.zonal.history.accum.max(\"geotiff 1\", \"30d\")\n" "add_value(\"max\", x)\n" "return"; analysis->script = script; analysis->outputDataSeriesId = 3; analysis->scriptLanguage = ScriptLanguage::PYTHON; analysis->type = AnalysisType::MONITORED_OBJECT_TYPE; analysis->serviceInstanceId = 1; terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr dataProvider1Ptr(dataProvider); dataProvider->name = "Provider"; dataProvider->uri = "file://"+TERRAMA2_DATA_DIR+"/shapefile"; dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; dataProvider->dataProviderType = "FILE"; dataProvider->active = true; dataProvider->id = 1; dataManager->add(dataProvider1Ptr); terrama2::core::DataSeries* dataSeries = new terrama2::core::DataSeries(); terrama2::core::DataSeriesPtr dataSeriesPtr(dataSeries); dataSeries->dataProviderId = dataProvider->id; dataSeries->semantics = semanticsManager.getSemantics("STATIC_DATA-ogr"); dataSeries->semantics.dataSeriesType = terrama2::core::DataSeriesType::GEOMETRIC_OBJECT; dataSeries->name = "Monitored Object"; dataSeries->id = 1; dataSeries->dataProviderId = 1; //DataSet information terrama2::core::DataSet* dataSet = new terrama2::core::DataSet; terrama2::core::DataSetPtr dataSetPtr(dataSet); dataSet->active = true; dataSet->format.emplace("mask", "estados_2010.shp"); dataSet->format.emplace("srid", "4326"); dataSet->id = 1; dataSet->dataSeriesId = 1; dataSeries->datasetList.push_back(dataSetPtr); dataManager->add(dataSeriesPtr); AnalysisDataSeries monitoredObjectADS; monitoredObjectADS.id = 1; monitoredObjectADS.dataSeriesId = dataSeriesPtr->id; monitoredObjectADS.type = AnalysisDataSeriesType::DATASERIES_MONITORED_OBJECT_TYPE; monitoredObjectADS.metadata["identifier"] = "nome"; // DataProvider information terrama2::core::DataProvider* dataProvider2 = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr dataProvider2Ptr(dataProvider2); dataProvider2->uri = "file://"+TERRAMA2_DATA_DIR+"/geotiff"; dataProvider2->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; dataProvider2->dataProviderType = "FILE"; dataProvider2->active = true; dataProvider2->id = 2; dataProvider2->name = "Local Geotiff"; dataManager->add(dataProvider2Ptr); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Data Series 2 ////////////////////////////////////////////////////////////////////////////////////////////////////////// terrama2::core::DataSeries* dataSeries2 = new terrama2::core::DataSeries(); terrama2::core::DataSeriesPtr dataSeries2Ptr(dataSeries2); dataSeries2->semantics = semanticsManager.getSemantics("GRID-static_geotiff"); dataSeries2->name = "geotiff 1"; dataSeries2->id = 2; dataSeries2->dataProviderId = 2; terrama2::core::DataSetGrid* dataSet1 = new terrama2::core::DataSetGrid(); dataSet1->active = true; dataSet1->format.emplace("mask", "Spot_Vegetacao_Jul2001_SP.tif"); dataSet1->id = 2; dataSeries2->datasetList.emplace_back(dataSet1); AnalysisDataSeries gridADS1; gridADS1.id = 2; gridADS1.dataSeriesId = dataSeries2Ptr->id; gridADS1.type = AnalysisDataSeriesType::ADDITIONAL_DATA_TYPE; dataManager->add(dataSeries2Ptr); std::vector<AnalysisDataSeries> analysisDataSeriesList; analysisDataSeriesList.push_back(monitoredObjectADS); analysisDataSeriesList.push_back(gridADS1); analysis->analysisDataSeriesList = analysisDataSeriesList; analysis->schedule.frequency = 1; analysis->schedule.frequencyUnit = "min"; dataManager->add(analysisPtr); terrama2::core::ServiceManager::getInstance().setInstanceId(1); Service service(dataManager); auto logger = std::make_shared<AnalysisLogger>(); logger->setConnectionInfo(uri); service.setLogger(logger); service.start(); service.addToQueue(analysisPtr->id, terrama2::core::TimeUtils::nowUTC()); QTimer timer; QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit())); timer.start(10000); app.exec(); } return 0; }
void UrlFactory::TryCorrectGoogleVersions() { QMutexLocker locker(&mutex); if(CorrectGoogleVersions && !IsCorrectGoogleVersions()) { QNetworkReply *reply; QNetworkRequest qheader; QNetworkAccessManager network; QEventLoop q; QTimer tT; tT.setSingleShot(true); connect(&network, SIGNAL(finished(QNetworkReply*)), &q, SLOT(quit())); connect(&tT, SIGNAL(timeout()), &q, SLOT(quit())); network.setProxy(Proxy); #ifdef DEBUG_URLFACTORY qDebug()<<"Correct GoogleVersion"; #endif //DEBUG_URLFACTORY setIsCorrectGoogleVersions(true); QString url = "https://maps.google.com"; qheader.setUrl(QUrl(url)); qheader.setRawHeader("User-Agent",UserAgent); reply=network.get(qheader); tT.start(Timeout); q.exec(); if(!tT.isActive()) return; tT.stop(); if( (reply->error()!=QNetworkReply::NoError)) { #ifdef DEBUG_URLFACTORY qDebug()<<"Try corrected version withou abort or error:"<<reply->errorString(); #endif //DEBUG_URLFACTORY return; } QString html=QString(reply->readAll()); QRegExp reg("\"*https://mt0.google.com/vt/lyrs=m@(\\d*)",Qt::CaseInsensitive); if(reg.indexIn(html)!=-1) { QStringList gc=reg.capturedTexts(); VersionGoogleMap = QString("m@%1").arg(gc[1]); VersionGoogleMapChina = VersionGoogleMap; #ifdef DEBUG_URLFACTORY qDebug()<<"TryCorrectGoogleVersions, VersionGoogleMap: "<<VersionGoogleMap; #endif //DEBUG_URLFACTORY } reg=QRegExp("\"*https://mt0.google.com/vt/lyrs=h@(\\d*)",Qt::CaseInsensitive); if(reg.indexIn(html)!=-1) { QStringList gc=reg.capturedTexts(); VersionGoogleLabels = QString("h@%1").arg(gc[1]); VersionGoogleLabelsChina = VersionGoogleLabels; #ifdef DEBUG_URLFACTORY qDebug()<<"TryCorrectGoogleVersions, VersionGoogleLabels: "<<VersionGoogleLabels; #endif //DEBUG_URLFACTORY } reg=QRegExp("\"*https://khm\\D?\\d.google.com/kh/v=(\\d*)",Qt::CaseInsensitive); if(reg.indexIn(html)!=-1) { QStringList gc=reg.capturedTexts(); VersionGoogleSatellite = gc[1]; VersionGoogleSatelliteKorea = VersionGoogleSatellite; VersionGoogleSatelliteChina = "s@" + VersionGoogleSatellite; qDebug()<<"TryCorrectGoogleVersions, VersionGoogleSatellite: "<<VersionGoogleSatellite; } reg=QRegExp("\"*https://mt0.google.com/vt/lyrs=t@(\\d*),r@(\\d*)",Qt::CaseInsensitive); if(reg.indexIn(html)!=-1) { QStringList gc=reg.capturedTexts(); VersionGoogleTerrain = QString("t@%1,r@%2").arg(gc[1]).arg(gc[2]); VersionGoogleTerrainChina = VersionGoogleTerrain; #ifdef DEBUG_URLFACTORY qDebug()<<"TryCorrectGoogleVersions, VersionGoogleTerrain: "<<VersionGoogleTerrain; #endif //DEBUG_URLFACTORY } reply->deleteLater(); }
/* * 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; } }