Example #1
0
void Application::initializeTranslation()
{
    Preferences *const pref = Preferences::instance();
    // Load translation
    QString localeStr = pref->getLocale();

    if (m_qtTranslator.load(QLatin1String("qtbase_") + localeStr, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) ||
        m_qtTranslator.load(QLatin1String("qt_") + localeStr, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            qDebug("Qt %s locale recognized, using translation.", qUtf8Printable(localeStr));
    else
        qDebug("Qt %s locale unrecognized, using default (en).", qUtf8Printable(localeStr));

    installTranslator(&m_qtTranslator);

    if (m_translator.load(QLatin1String(":/lang/qbittorrent_") + localeStr))
        qDebug("%s locale recognized, using translation.", qUtf8Printable(localeStr));
    else
        qDebug("%s locale unrecognized, using default (en).", qUtf8Printable(localeStr));
    installTranslator(&m_translator);

#ifndef DISABLE_GUI
    if (localeStr.startsWith("ar") || localeStr.startsWith("he")) {
        qDebug("Right to Left mode");
        setLayoutDirection(Qt::RightToLeft);
    }
    else {
        setLayoutDirection(Qt::LeftToRight);
    }
#endif
}
Example #2
0
 void printParamArgs(CgtParams index, const QVariant &value)
 {
     qInfo("  Arg1: %s", qUtf8Printable(CgtParamsMap[index])); //-V108
     if (value.type() == QVariant::String) {
         qInfo("  Arg2: \"%s\"", qUtf8Printable(value.toString()));
     } else {
         qInfo("  Arg2: %s", qUtf8Printable(value.toString()));
     }
 }
Example #3
0
void Multicaster::readyRead()
{
    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());

        QHostAddress senderAddr;
        quint16 senderPort;

        // Here it is assumed that if a datagram is fragmented, it can
        // be dismissed and treated as a UDP unreliability
        qint64 r = socket->readDatagram(datagram.data(), datagram.size(),
            &senderAddr, &senderPort);
        if (r != datagram.size())
        {
            // Ignore errors and datagrams of incorrect size.
            qDebug() << "Multicaster::readyRead()"
                << "readDatagram() returned" << r << ", but"
                << datagram.size() << "expected. Ignored.";
            return;
        }

        if (senderPort != settings.port) {
            // Ignore datagrams sent from unknown ports.
            qDebug() << "Multicaster::readyRead()"
                << "Received datagram from port" << senderPort
                << ", but expected port is" << settings.port
                << ". Ignored.";
            return;
        }

        if (senderAddr == ownIp) {
            // Ignore datagrams sent by this host to itself.
            return;
        }

        // Debug.
        if (settings.debugWasteEachNthDatagramReceived > 0)
        {
            static int count = 0;
            if (++count % settings.debugWasteEachNthDatagramReceived == 0)
            {
                DEBUG_LOG_WASTED("    " << datagram << "<-x-"
                    << qUtf8Printable(senderAddr.toString()));
                return;
            }
        }

        LOG("    " << datagram << "<---"
            << qUtf8Printable(senderAddr.toString()));

        emit datagramReceived(datagram, senderAddr.toString());
    }
}
void FilterExpressionToolBar::onFilterDropped(QString description, QString filter)
{
    if ( filter.length() == 0 )
        return;

    filter_expression_new(qUtf8Printable(description),
            qUtf8Printable(filter), qUtf8Printable(description), TRUE);

    save_migrated_uat("Display expressions", &prefs.filter_expressions_old);
    filterExpressionsChanged();
}
Example #5
0
void ProgramUpdater::rssDownloadFinished(const QString &url, const QByteArray &data)
{
    Q_UNUSED(url);
    qDebug("Finished downloading the new qBittorrent updates RSS");

#ifdef Q_OS_MAC
    const QString OS_TYPE {"Mac OS X"};
#elif defined(Q_OS_WIN)
    const QString OS_TYPE {((QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7)
            && QSysInfo::currentCpuArchitecture().endsWith("64"))
        ? "Windows x64" : "Windows"};
#endif

    QString version;
    QXmlStreamReader xml(data);
    bool inItem = false;
    QString updateLink;
    QString type;

    while (!xml.atEnd()) {
        xml.readNext();

        if (xml.isStartElement()) {
            if (xml.name() == "item")
                inItem = true;
            else if (inItem && xml.name() == "link")
                updateLink = getStringValue(xml);
            else if (inItem && xml.name() == "type")
                type = getStringValue(xml);
            else if (inItem && xml.name() == "version")
                version = getStringValue(xml);
        }
        else if (xml.isEndElement()) {
            if (inItem && xml.name() == "item") {
                if (type.compare(OS_TYPE, Qt::CaseInsensitive) == 0) {
                    qDebug("The last update available is %s", qUtf8Printable(version));
                    if (!version.isEmpty()) {
                        qDebug("Detected version is %s", qUtf8Printable(version));
                        if (isVersionMoreRecent(version))
                            m_updateUrl = updateLink;
                    }
                    break;
                }

                inItem = false;
                updateLink.clear();
                type.clear();
                version.clear();
            }
        }
    }

    emit updateCheckFinished(!m_updateUrl.isEmpty(), version, m_invokedByUser);
}
Example #6
0
bool Utils::Fs::isRegularFile(const QString &path)
{
    struct ::stat st;
    if (::stat(path.toUtf8().constData(), &st) != 0) {
        //  analyse erno and log the error
        const auto err = errno;
        qDebug("Could not get file stats for path '%s'. Error: %s"
               , qUtf8Printable(path), qUtf8Printable(strerror(err)));
        return false;
    }

    return (st.st_mode & S_IFMT) == S_IFREG;
}
void
ChatController::sendMessage(const QString& text) {
  qDebug("chat.sendMessage(\"%s\")", qUtf8Printable(text)); // DEBUG

  QSqlQuery sql_query;
  sql_query.prepare("SELECT conreality.message_send(session_user, ?)");
  sql_query.bindValue(0, text);
  sql_query.exec();
  const auto error = sql_query.lastError();
  if (error.isValid()) {
    qFatal("PostgreSQL: %s.", qUtf8Printable(error.text()));
  }
}
Example #8
0
CommandLinePluginInterface::RunResult LdapPlugin::handle_query( const QStringList& arguments )
{
	QString objectType = arguments.value( 0 );
	QString filter = arguments.value( 1 );
	QStringList results;

	if( objectType == "rooms" )
	{
		results = ldapDirectory().computerRooms( filter );
	}
	else if( objectType == "computers" )
	{
		results = ldapDirectory().computers( filter );
	}
	else if( objectType == "groups" )
	{
		results = ldapDirectory().groups( filter );
	}
	else if( objectType == "users" )
	{
		results = ldapDirectory().users( filter );
	}
	else
	{
		return InvalidArguments;
	}

	for( const auto& result : qAsConst( results ) )
	{
		printf( "%s\n", qUtf8Printable( result ) );
	}

	return Successful;
}
Example #9
0
/////////////////////////////////////// PRIVATE FUNCTIONS////////////////////////////////
//
//  Function to get information about the server and write results to data members
void NotifyClient::getServerInformation()
{
  // return if we don't have valid connection
  if (! b_validconnection) return; 
  
  // get the server information
  QDBusMessage reply = notifyclient->call(QLatin1String("GetServerInformation"));
  
  if (reply.type() == QDBusMessage::ReplyMessage) {
    QList<QVariant> outargs = reply.arguments();
    s_name = outargs.at(0).toString();
    s_vendor = outargs.at(1).toString();
    s_version = outargs.at(2).toString();
    s_spec_version = outargs.at(3).toString();
  }
  
  else {
    if (reply.type() == QDBusMessage::InvalidMessage)
      qCritical("CMST - Invalid reply received to GetServerInformation method.");
    
    else if (reply.type() == QDBusMessage::ErrorMessage) 
    #if QT_VERSION >= 0x050400 
			qCritical("CMST - Error reply received to GetServerInforation method: %s", qUtf8Printable(reply.errorMessage()) );
    #else
      qCritical("CMST - Error reply received to GetServerInforation method: %s", qPrintable(reply.errorMessage()) );
    #endif
  } // else some error occured
  

  return;
}
bool MeshDocumentFromNvm(MeshDocument &md, QString filename_nvm, QString model_filename)
{
    md.addNewMesh(model_filename,QString("model"));
    std::vector<Shotm> shots;
    const QString path = QFileInfo(filename_nvm).absolutePath();
    //const QString path_im = QFileInfo(image_list_filename).absolutePath()+QString("/");

    std::vector<std::string>   image_filenames;
    vcg::tri::io::ImporterNVM<CMeshO>::Open(md.mm()->cm,shots,image_filenames, qUtf8Printable(filename_nvm));
    md.mm()->updateDataMask(MeshModel::MM_VERTCOLOR);

    QString curr_path = QDir::currentPath();
    //QFileInfo imi(image_list_filename);

    //QDir::setCurrent(imi.absoluteDir().absolutePath());
    QStringList image_filenames_q;
    for(size_t i  = 0; i < image_filenames.size(); ++i)
        image_filenames_q.push_back(QString::fromStdString(image_filenames[int(i)]));

    for(size_t i=0 ; i<shots.size() ; i++){
        md.addNewRaster();
        const QString fullpath_image_filename = image_filenames_q[int(i)];
        md.rm()->addPlane(new Plane(fullpath_image_filename,Plane::RGBA));
        md.rm()->setLabel(image_filenames_q[int(i)].section('/',1,2));
        md.rm()->shot = shots[int(i)];
        /*md.rm()->shot.Intrinsics.ViewportPx[0]=md.rm()->currentPlane->image.width();
        md.rm()->shot.Intrinsics.ViewportPx[1]=md.rm()->currentPlane->image.height();
        md.rm()->shot.Intrinsics.CenterPx[0]=(int)((double)md.rm()->shot.Intrinsics.ViewportPx[0]/2.0f);
        md.rm()->shot.Intrinsics.CenterPx[1]=(int)((double)md.rm()->shot.Intrinsics.ViewportPx[1]/2.0f);*/

    }
    QDir::setCurrent(curr_path);

    return true;
}
Net::DownloadHandler *Net::DownloadManager::download(const DownloadRequest &downloadRequest)
{
    // Process download request
    const QNetworkRequest request = createNetworkRequest(downloadRequest);
    const ServiceID id = ServiceID::fromURL(request.url());
    const bool isSequentialService = m_sequentialServices.contains(id);

    auto downloadHandler = new DownloadHandlerImpl {downloadRequest, this};
    connect(downloadHandler, &DownloadHandler::finished, downloadHandler, &QObject::deleteLater);
    connect(downloadHandler, &QObject::destroyed, this, [this, id, downloadHandler]()
    {
        m_waitingJobs[id].removeOne(downloadHandler);
    });

    if (!isSequentialService || !m_busyServices.contains(id)) {
        qDebug("Downloading %s...", qUtf8Printable(downloadRequest.url()));
        if (isSequentialService)
            m_busyServices.insert(id);
        downloadHandler->assignNetworkReply(m_networkManager.get(request));
    }
    else {
        m_waitingJobs[id].enqueue(downloadHandler);
    }

    return downloadHandler;
}
Example #12
0
void Net::DownloadHandler::processFinishedDownload()
{
    QString url = m_reply->url().toString();
    qDebug("Download finished: %s", qUtf8Printable(url));
    // Check if the request was successful
    if (m_reply->error() != QNetworkReply::NoError) {
        // Failure
        qDebug("Download failure (%s), reason: %s", qUtf8Printable(url), qUtf8Printable(errorCodeToString(m_reply->error())));
        emit downloadFailed(m_downloadRequest.url(), errorCodeToString(m_reply->error()));
        this->deleteLater();
    }
    else {
        // Check if the server ask us to redirect somewhere else
        const QVariant redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if (redirection.isValid()) {
            // We should redirect
            handleRedirection(redirection.toUrl());
        }
        else {
            // Success
            QByteArray replyData = m_reply->readAll();
            if (m_reply->rawHeader("Content-Encoding") == "gzip") {
                // decompress gzip reply
                replyData = Utils::Gzip::decompress(replyData);
            }

            if (m_downloadRequest.saveToFile()) {
                QString filePath;
                if (saveToFile(replyData, filePath))
                    emit downloadFinished(m_downloadRequest.url(), filePath);
                else
                    emit downloadFailed(m_downloadRequest.url(), tr("I/O Error"));
            }
            else {
                emit downloadFinished(m_downloadRequest.url(), replyData);
            }

            this->deleteLater();
        }
    }
}
Example #13
0
bool DbFunc::execQuery(QSqlQuery& query, const QString& sql,
                       const ArgList& args)
{
    // Executes an existing query (in place) with the supplied SQL/args.
    // THIS IS THE MAIN POINT THROUGH WHICH ALL QUERIES SHOULD BE EXECUTED.
    query.prepare(sql);
    addArgs(query, args);

#ifdef DEBUG_SQL_QUERY
    {
        qDebug() << "Executing:" << qUtf8Printable(sql);
        QDebug debug = qDebug().nospace();
        debug << "... args: ";
        DebugFunc::debugConcisely(debug, args);
    }  // endl on destruction
#endif

    bool success = query.exec();
#ifdef DEBUG_QUERY_END
    qDebug() << "... query finished";
#endif
    if (!success) {
        qCritical() << "Query failed; error was:" << query.lastError();
    }
#ifdef DEBUG_SQL_RESULT
    if (success && query.isSelect() && !query.isForwardOnly()) {
        qDebug() << "Resultset preview:";
        int row = 0;
        while (query.next()) {
            QDebug debug = qDebug().nospace();
            QSqlRecord rec = query.record();
            int ncols = rec.count();
            debug << "... row " << row << ": ";
            for (int col = 0; col < ncols; ++col) {
                if (col > 0) {
                    debug << "; ";
                }
                debug << rec.fieldName(col) << "=";
                DebugFunc::debugConcisely(debug, query.value(col));
            }
            ++row;
        }  // endl on destruction
        if (row == 0) {
            qDebug() << "<no rows>";
        }
        query.seek(QSql::BeforeFirstRow);  // the original starting position
    }
#endif
    return success;
    // The return value is boolean (success?).
    // Use query.next() to iterate through a result set; see
    // http://doc.qt.io/qt-4.8/sql-sqlstatements.html
}
Example #14
0
void XmlParserTest::initTestCase()
{
	try
	{
		// Create a validator
		validator = createValidator(QStringLiteral(":/courses/course.xsd"));
	}
	catch (Exception& e)
	{
		QFAIL(qUtf8Printable(e.message()));
	}
}
void Net::DownloadManager::handleReplyFinished(const QNetworkReply *reply)
{
    const ServiceID id = ServiceID::fromURL(reply->url());
    const auto waitingJobsIter = m_waitingJobs.find(id);
    if ((waitingJobsIter == m_waitingJobs.end()) || waitingJobsIter.value().isEmpty()) {
        m_busyServices.remove(id);
        return;
    }

    auto handler = static_cast<DownloadHandlerImpl *>(waitingJobsIter.value().dequeue());
    qDebug("Downloading %s...", qUtf8Printable(handler->url()));
    handler->assignNetworkReply(m_networkManager.get(createNetworkRequest(handler->downloadRequest())));
    handler->disconnect(this);
}
Example #16
0
void ScanFoldersModel::addTorrentsToSession(const QStringList &pathList)
{
    for (const QString &file : pathList) {
        qDebug("File %s added", qUtf8Printable(file));

        BitTorrent::AddTorrentParams params;
        if (downloadInWatchFolder(file))
            params.savePath = QFileInfo(file).dir().path();
        else if (!downloadInDefaultFolder(file))
            params.savePath = downloadPathTorrentFolder(file);

        if (file.endsWith(".magnet")) {
            QFile f(file);
            if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QTextStream str(&f);
                while (!str.atEnd())
                    BitTorrent::Session::instance()->addTorrent(str.readLine(), params);

                f.close();
                Utils::Fs::forceRemove(file);
            }
            else {
                qDebug("Failed to open magnet file: %s", qUtf8Printable(f.errorString()));
            }
        }
        else {
            const BitTorrent::TorrentInfo torrentInfo = BitTorrent::TorrentInfo::loadFromFile(file);
            if (torrentInfo.isValid()) {
                BitTorrent::Session::instance()->addTorrent(torrentInfo, params);
                Utils::Fs::forceRemove(file);
            }
            else {
                qDebug("Ignoring incomplete torrent file: %s", qUtf8Printable(file));
            }
        }
    }
}
Example #17
0
void SearchWidget::fillCatCombobox()
{
    m_ui->comboCategory->clear();
    m_ui->comboCategory->addItem(SearchPluginManager::categoryFullName("all"), QVariant("all"));

    using QStrPair = QPair<QString, QString>;
    QList<QStrPair> tmpList;
    foreach (const QString &cat, SearchPluginManager::instance()->getPluginCategories(selectedPlugin()))
        tmpList << qMakePair(SearchPluginManager::categoryFullName(cat), cat);
    std::sort(tmpList.begin(), tmpList.end(), [](const QStrPair &l, const QStrPair &r) { return (QString::localeAwareCompare(l.first, r.first) < 0); });

    foreach (const QStrPair &p, tmpList) {
        qDebug("Supported category: %s", qUtf8Printable(p.second));
        m_ui->comboCategory->addItem(p.first, QVariant(p.second));
    }
Example #18
0
bool Preferences::isMagnetLinkAssocSet()
{
    QSettings settings("HKEY_CURRENT_USER\\Software\\Classes", QSettings::NativeFormat);

    // Check magnet link assoc
    QRegExp exe_reg("\"([^\"]+)\".*");
    QString shell_command = Utils::Fs::toNativePath(settings.value("magnet/shell/open/command/Default", "").toString());
    if (exe_reg.indexIn(shell_command) < 0)
        return false;
    QString assoc_exe = exe_reg.cap(1);
    qDebug("exe: %s", qUtf8Printable(assoc_exe));
    if (assoc_exe.compare(Utils::Fs::toNativePath(qApp->applicationFilePath()), Qt::CaseInsensitive) != 0)
        return false;

    return true;
}
Example #19
0
/*!
    \since 5.9

    Returns the path name of a file in the temporary directory.
    Does \e not check if the file actually exists in the directory.
    Redundant multiple separators or "." and ".." directories in
    \a fileName are not removed (see QDir::cleanPath()). Absolute
    paths are not allowed.
*/
QString QTemporaryDir::filePath(const QString &fileName) const
{
    if (QDir::isAbsolutePath(fileName)) {
        qWarning("QTemporaryDir::filePath: Absolute paths are not allowed: %s", qUtf8Printable(fileName));
        return QString();
    }

    if (!d_ptr->success)
        return QString();

    QString ret = d_ptr->pathOrError;
    if (!fileName.isEmpty()) {
        ret += QLatin1Char('/');
        ret += fileName;
    }
    return ret;
}
bool MeshDocumentFromBundler(MeshDocument &md, QString filename_out,QString image_list_filename, QString model_filename)
{
    md.addNewMesh(model_filename,QString("model"));
    std::vector<Shotm> shots;
    const QString path = QFileInfo(filename_out).absolutePath();
    const QString path_im = QFileInfo(image_list_filename).absolutePath()+QString("/");

    std::vector<std::string>   image_filenames;
    vcg::tri::io::ImporterOUT<CMeshO>::Open(md.mm()->cm,shots,image_filenames, qUtf8Printable(filename_out), qUtf8Printable(image_list_filename));
    md.mm()->updateDataMask(MeshModel::MM_VERTCOLOR);

    QString curr_path = QDir::currentPath();
    QFileInfo imi(image_list_filename);

    //
    QStringList image_filenames_q;
    for(unsigned int i  = 0; i < image_filenames.size(); ++i)
    {
        QImageReader sizeImg(QString::fromStdString(image_filenames[i]));
        if(sizeImg.size()==QSize(-1,-1))
            image_filenames_q.push_back(path_im+QString::fromStdString(image_filenames[i]));
        else
            image_filenames_q.push_back(QString::fromStdString(image_filenames[i]));
    }
    QDir::setCurrent(imi.absoluteDir().absolutePath());

    for(size_t i=0 ; i<shots.size() ; i++)
    {
        md.addNewRaster();
        const QString fullpath_image_filename = image_filenames_q[int(i)];
        md.rm()->addPlane(new Plane(fullpath_image_filename,Plane::RGBA));
        int count=fullpath_image_filename.count('\\');
        if (count==0)
        {
            count=fullpath_image_filename.count('/');
            md.rm()->setLabel(fullpath_image_filename.section('/',count,1));
        }
        else
            md.rm()->setLabel(fullpath_image_filename.section('\\',count,1));
        md.rm()->shot = shots[i];
    }
    QDir::setCurrent(curr_path);

    return true;
}
Example #21
0
bool Application::event(QEvent *ev)
{
    if (ev->type() == QEvent::FileOpen) {
        QString path = static_cast<QFileOpenEvent *>(ev)->file();
        if (path.isEmpty())
            // Get the url instead
            path = static_cast<QFileOpenEvent *>(ev)->url().toString();
        qDebug("Received a mac file open event: %s", qUtf8Printable(path));
        if (m_running)
            processParams(QStringList(path));
        else
            m_paramsQueue.append(path);
        return true;
    }
    else {
        return BaseApplication::event(ev);
    }
}
Example #22
0
void XmlParserTest::parseTestCourse()
{
	ParseResult result;
	QString message;

	try
	{
		auto course = parseCourse(QStringLiteral(":/testing/courses/testcourse.xml"), *validator, &result,
		                     &message);

		verifyTestCourse(*course);
	}
	catch (Exception& e)
	{
		QFAIL(qUtf8Printable(e.message()));
	}

}
Example #23
0
void Net::DownloadHandler::handleRedirection(QUrl newUrl)
{
    // Resolve relative urls
    if (newUrl.isRelative())
        newUrl = m_reply->url().resolved(newUrl);

    const QString newUrlString = newUrl.toString();
    qDebug("Redirecting from %s to %s...", qUtf8Printable(m_reply->url().toString()), qUtf8Printable(newUrlString));

    // Redirect to magnet workaround
    if (newUrlString.startsWith("magnet:", Qt::CaseInsensitive)) {
        qDebug("Magnet redirect detected.");
        m_reply->abort();
        if (m_downloadRequest.handleRedirectToMagnet())
            emit redirectedToMagnet(m_downloadRequest.url(), newUrlString);
        else
            emit downloadFailed(m_downloadRequest.url(), tr("Unexpected redirect to magnet URI."));

        this->deleteLater();
    }
    else {
        DownloadHandler *redirected = m_manager->download(DownloadRequest(m_downloadRequest).url(newUrlString));
        connect(redirected, &DownloadHandler::destroyed, this, &DownloadHandler::deleteLater);
        connect(redirected, &DownloadHandler::downloadFailed, this, [this](const QString &, const QString &reason)
        {
            emit downloadFailed(url(), reason);
        });
        connect(redirected, &DownloadHandler::redirectedToMagnet, this, [this](const QString &, const QString &magnetUri)
        {
            emit redirectedToMagnet(url(), magnetUri);
        });
        connect(redirected, static_cast<void (DownloadHandler::*)(const QString &, const QString &)>(&DownloadHandler::downloadFinished)
                , this, [this](const QString &, const QString &fileName)
        {
            emit downloadFinished(url(), fileName);
        });
        connect(redirected, static_cast<void (DownloadHandler::*)(const QString &, const QByteArray &)>(&DownloadHandler::downloadFinished)
                , this, [this](const QString &, const QByteArray &data)
        {
            emit downloadFinished(url(), data);
        });
    }
}
Example #24
0
//
// Function to get the capabilities of the server and write to a qstringlist data member
void NotifyClient::getCapabilities()
{
  // return if we don't have valid connection
  if (! b_validconnection) return;  
  
  // get the server capabilities
  QDBusReply<QStringList> reply = notifyclient->call(QLatin1String("GetCapabilities") );

  if (reply.isValid()) 
    sl_capabilities = reply.value();
  else
  #if QT_VERSION >= 0x050400 
		qCritical("CMST - Error reply received to GetCapabilities method: %s", qUtf8Printable(reply.error().message()) );
  #else
    qCritical("CMST - Error reply received to GetCapabilities method: %s", qPrintable(reply.error().message()) );
  #endif
  
  return;
}
Example #25
0
//
//  Function to force a close of a notification
void NotifyClient::closeNotification(quint32 id)
{
  // return if we don't have valid connection
  if (! b_validconnection) return; 
  
  QDBusMessage reply = notifyclient->call(QLatin1String("CloseNotification"), id);
  
  if (reply.type() == QDBusMessage::InvalidMessage)
    qCritical("CMST - Invalid reply received to CloseNotification method.");
  
  else if (reply.type() == QDBusMessage::ErrorMessage) 
  #if QT_VERSION >= 0x050400 
		qCritical("CMST - Error reply received to CloseNotification method: %s", qUtf8Printable(reply.errorMessage()) );
  #else
    qCritical("CMST - Error reply received to CloseNotification method: %s", qPrintable(reply.errorMessage()) );
  #endif
  
  return;
}
Example #26
0
/*!
 * \brief InitializeMeters -- Once per program execution actions.
 *
 * Opens a connection to the database.
 *
 * For each meter in the args list, check to see if there is a table in the
 * database for the response from the meter.  If not, create the table.
 *
 * Each meter has its time set to the local standard time.
 *
 * \param serialPort    Pointer to serial port for communication with meter.
 * \param args  List of meter ids from command line.
 * \return true if successful, false otherwise.
 */
bool InitializeMeters(QSerialPort *serialPort, const QStringList &args)
{
    qDebug("Begin");
    QSqlDatabase dbConn = QSqlDatabase::database(ConnectionName);

    if (!dbConn.isOpen())
    {
        qCritical() << "Unable to open database for meter data.";
        qInfo() << "Return false";
        return false;
    }
    QSqlQuery query(dbConn);

    /*! Do meter initialization tasks for each meter.  */
    foreach (QString meterId, args)
    {
        //! Expand meter id to all 12 characters.
        QString fullMeterId = meterId.rightJustified(sizeof(RequestMsgV4.meterId), '0', true);

        //! Check for the existence of database tables in which to store meter data.

        if (fullMeterId.toLongLong() >= 300000000)
        {
            // Is a v.4 meter.
            //!  Set the time in the meter to the computer's idea of the local standard time.
            if (!SetMeterTime(serialPort, fullMeterId))
            {
                qWarning("Unable to set meter time for meter %s.", qUtf8Printable(fullMeterId));
            }

            // Create the tables if they don't exist.
            VerifyDatabaseTable(query, fullMeterId, "_A");
            VerifyDatabaseTable(query, fullMeterId, "_B");
        }
        else
        {
            // Is a v.3 meter.
            // Don't try to set meter time for v.3 meter since I don't know how to do it.
            // Create the table if it doesn't exist.
            VerifyDatabaseTable(query, fullMeterId, "");
        }
    }
Example #27
0
int main(int argc, char *argv[])
{
	QGuiApplication a(argc, argv);

	COpenVROverlayController::SharedInstance()->Init();

	// Get the base path
	DWORD size = MAX_PATH;
	WCHAR path[MAX_PATH];
	HKEY oculusKey;
	RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Oculus VR, LLC\\Oculus", 0, KEY_READ | KEY_WOW64_32KEY, &oculusKey);
	RegQueryValueEx(oculusKey, L"Base", NULL, NULL, (PBYTE)path, &size);

	// Create a QML engine.
	QQmlEngine qmlEngine;
	qmlEngine.rootContext()->setContextProperty("ReviveManifest", CReviveManifestController::SharedInstance());

	// Set the properties.
	QString str = QString::fromWCharArray(path);
	QUrl url = QUrl::fromLocalFile(str);
	QString base = QDir::fromNativeSeparators(str);
	qmlEngine.rootContext()->setContextProperty("baseURL", url.url());
	qmlEngine.rootContext()->setContextProperty("basePath", base);

	QQmlComponent qmlComponent( &qmlEngine, QUrl("qrc:/Overlay.qml"));
	if (qmlComponent.isError())
	{
		qDebug(qUtf8Printable(qmlComponent.errorString()));
		return -1;
	}

	QObject *rootObject = qmlComponent.create();
	QQuickItem *rootItem = qobject_cast<QQuickItem*>( rootObject );

	COpenVROverlayController::SharedInstance()->SetQuickItem( rootItem );

	// don't show the window that you're going display in an overlay
	//view.show();

	return a.exec();
}
Example #28
0
void justice_cmd::cancel()
{

    if (!m_executor)
        return;

    redisContext *c = redisConnect("127.0.0.1", 6379);
    if (!c)
        return;
    if (c->err != 0) {
        redisFree(c);
        return;
    }

    void *reply  = redisCommand(c, "PUBLISH %s %s", qUtf8Printable(m_info_chnl), "end");
    if (reply)
        freeReplyObject(reply);
    redisFree(c);


}
Example #29
0
void XmlParserTest::parseCourses()
{
	QDir coursepath(QStringLiteral(":/courses"), "*.xml", QDir::Name | QDir::IgnoreCase, QDir::Files);

	QStringList coursefiles;
	foreach(QString const & s, coursepath.entryList())
	{
		coursefiles.append(coursepath.filePath(s));
	}

	qDebug() << coursefiles;

	QList<std::shared_ptr<Course>> courseList;

	QStringListIterator it(coursefiles);
	while (it.hasNext())
	{
		ParseResult result;
		QString message;

		try
		{
			auto course = parseCourse(it.next(), *validator, &result, &message);

			if (result != Ok)
			{
				qWarning() << "Result:" << result << " " << message;
			}

			courseList.append(course);
		}
		catch (Exception& e)
		{
			QFAIL(qUtf8Printable(e.message()));
		}
	}

	QCOMPARE(coursepath.entryList().size(), courseList.length());
}
Example #30
0
Net::DownloadHandler *Net::DownloadManager::download(const DownloadRequest &downloadRequest)
{
    // Process download request
    const QNetworkRequest request = createNetworkRequest(downloadRequest);
    const ServiceID id = ServiceID::fromURL(request.url());
    const bool isSequentialService = m_sequentialServices.contains(id);
    if (!isSequentialService || !m_busyServices.contains(id)) {
        qDebug("Downloading %s...", qUtf8Printable(downloadRequest.url()));
        if (isSequentialService)
            m_busyServices.insert(id);
        return new DownloadHandler {
            m_networkManager.get(request), this, downloadRequest};
    }

    auto *downloadHandler = new DownloadHandler {nullptr, this, downloadRequest};
    connect(downloadHandler, &DownloadHandler::destroyed, this, [this, id, downloadHandler]()
    {
        m_waitingJobs[id].removeOne(downloadHandler);
    });
    m_waitingJobs[id].enqueue(downloadHandler);
    return downloadHandler;
}