bool DisplayManager::initialize()
{
  QLOG_INFO() << QString("DisplayManager found %1 Display(s).").arg(displays.size());

  // list video modes
  foreach(int displayid, displays.keys())
  {
    DMDisplayPtr display = displays[displayid];
    QLOG_INFO() << QString("Available modes for Display #%1 (%2)").arg(displayid).arg(display->name);
    for (int modeid = 0; modeid < display->videoModes.size(); modeid++)
    {
      DMVideoModePtr mode = display->videoModes[modeid];
      QLOG_INFO() << QString("Mode %1: %2").arg(modeid, 2).arg(mode->getPrettyName());
    }
  }

  // Log current display mode
  int mainDisplay = getMainDisplay();
  if (mainDisplay >= 0)
  {
    int currentMode = getCurrentDisplayMode(mainDisplay);
    if (currentMode >= 0)
      QLOG_INFO() << QString("DisplayManager : Current Display Mode on Display #%1 is %2")
                     .arg(mainDisplay)
                     .arg(displays[mainDisplay]->videoModes[currentMode]->getPrettyName());
    else
      QLOG_ERROR() << "DisplayManager : unable to retrieve current video mode";
  }
  else
    QLOG_ERROR() << "DisplayManager : unable to retrieve main display";

  return true;
}
Example #2
0
void OcNetwork::slotAuthenticationRequired(QNetworkReply* rep, QAuthenticator *authenticator)
{
    QVariantMap account = config.getAccount();

#ifdef QT_DEBUG
        qDebug() << "Account: " << account;
        qDebug() << "Current user: "******"Current password: "******"state"].toInt() == 0)
    {
        if (authenticator->user().isEmpty() && authenticator->password().isEmpty())
        {
            authenticator->setUser(account["uname"].toString());
            authenticator->setPassword(account["pword"].toString());
        } else {
            if ((authenticator->user() != account["uname"].toString()) || (authenticator->password() !=  account["pword"].toString() ))
            {
                authenticator->setUser(account["uname"].toString());
                authenticator->setPassword(account["pword"].toString());
            } else {
                rep->abort();
                QLOG_ERROR() << "Network: Abort authentication";
            }
        }
    } else {
        rep->abort();
        QLOG_ERROR() << "Network: Abort authentication, account state: " << account["state"].toInt();
    }
}
Example #3
0
//*******************************************************************
// Every time we add a new object, we call this to get its unique
// local ID.  This number never changes
//*******************************************************************
qint32 ConfigStore::incrementLidCounter() {
    QSqlQuery sql;
    // Prepare the SQL statement & fetch the row
    sql.prepare("Select value from ConfigStore where key=:key");
    sql.bindValue(":key", CONFIG_STORE_LID);
    if (!sql.exec()) {
        QLOG_ERROR() << "Fetch of ConfigStore LID counter statement failed: " << sql.lastError();
    }
    if (!sql.next()) {
        QLOG_ERROR() << "LID NOT FOUND!!!";
    } else {
        // Now that we have the next lid, increment the number & save it
        qint32 sequence = QVariant(sql.value(0)).toInt();
        sequence++;
        sql.prepare("Update ConfigStore set value=:lid where key=:key;");
        sql.bindValue(":lid",sequence);
        sql.bindValue(":key", CONFIG_STORE_LID);
        if (!sql.exec()) {
            QLOG_ERROR() << "Error updating sequence number: " << sql.lastError();
        }
        // Return the next lid to the caller
        return sequence;
    }
    return -1;
}
Example #4
0
void BuyoutManager::Deserialize(const std::string &data, std::map<std::string, Buyout> *buyouts) {
    buyouts->clear();

    // if data is empty (on first use) we shouldn't make user panic by showing ERROR messages
    if (data.empty())
        return;

    rapidjson::Document doc;
    if (doc.Parse(data.c_str()).HasParseError()) {
        QLOG_ERROR() << "Error while parsing buyouts.";
        QLOG_ERROR() << rapidjson::GetParseError_En(doc.GetParseError());
        return;
    }
    if (!doc.IsObject())
        return;
    for (auto itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr) {
        auto &object = itr->value;
        const std::string &name = itr->name.GetString();
        Buyout bo;

        bo.currency = Currency::FromTag(object["currency"].GetString());
        bo.type = Buyout::TagAsBuyoutType(object["type"].GetString());
        bo.value = object["value"].GetDouble();
        if (object.HasMember("last_update")){
            bo.last_update = QDateTime::fromTime_t(object["last_update"].GetInt());
        }
        if (object.HasMember("source")){
            bo.source = Buyout::TagAsBuyoutSource(object["source"].GetString());
        }
        bo.inherited = false;
        if (object.HasMember("inherited"))
            bo.inherited = object["inherited"].GetBool();
        (*buyouts)[name] = bo;
    }
}
Example #5
0
// Update the database's user record
void UserTable::updateSyncState(SyncState s) {
    NSqlQuery query(*db);
    query.prepare("Delete from UserTable where key=:key1 or key=:key2 or key=:key3;");
    query.bindValue(":key1", USER_SYNC_UPLOADED);
    query.bindValue(":key2", USER_SYNC_LAST_DATE);
    query.bindValue(":key3", USER_SYNC_LAST_NUMBER);
    query.exec();

    query.prepare("Insert into UserTable (key, data) values (:key, :data);");
    if (s.uploaded.isSet()) {
        query.bindValue(":key", USER_SYNC_UPLOADED);
        query.bindValue(":data",qlonglong(s.uploaded));
        if (!query.exec()) {
            QLOG_ERROR() << "Error updating USER_SYNC_UPLOADED : " << query.lastError();
        }
     }

     query.prepare("Insert into UserTable (key, data) values (:key, :data);");
     query.bindValue(":key", USER_SYNC_LAST_DATE);
     query.bindValue(":data", qlonglong(s.currentTime));
     if (!query.exec()) {
         QLOG_ERROR() << "Error updating USER_SYNC_LAST_DATE : " << query.lastError();
     }

     query.prepare("Insert into UserTable (key, data) values (:key, :data);");
     query.bindValue(":key", USER_SYNC_LAST_NUMBER);
     query.bindValue(":data", s.updateCount);
     if (!query.exec()) {
         QLOG_ERROR() << "Error updating USER_SYNC_LAST_NUMBER : " << query.lastError();
     }
     query.finish();
}
Example #6
0
QString MediaManager::getMediaHash(const QString &path)
{
    //Hashing
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly))
    {
        QLOG_ERROR() << "Unable to read file: " + path;
        return nullptr;
    }

    //Read first 50K of the file
    QByteArray arr(51200, 0);
    qint64 toRead = 51200;
    while(qint64 haveRead = file.read(arr.data(), toRead) < toRead)
    {
        if(haveRead < 0) {
            QLOG_ERROR() << "Unable to read file: " + path;
            return nullptr;
        }
        toRead -= haveRead;
    }
    //Hash them
    hasher->addData(arr);
    QString rez = hasher->result().toBase64();
    QLOG_TRACE() << file.fileName() + ": " + rez;
    //Reset hasher
    hasher->reset();

    return rez;
}
void LoginDialog::OnLeaguesRequestFinished() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(QObject::sender());
    QByteArray bytes = reply->readAll();
    rapidjson::Document doc;
    doc.Parse(bytes.constData());

    leagues_.clear();
    // ignore actual response completely since it's broken anyway (at the moment of writing!)
    if (true) {
        QLOG_ERROR() << "Failed to parse leagues. The output was:";
        QLOG_ERROR() << QString(bytes);

        // But let's do our best and try to add at least some leagues!
        // It's in case GGG's API is broken and suddenly starts returning empty pages,
        // which of course will never happen.
        leagues_ = { "Flashback Event (IC001)", "Flashback Event HC (IC002)", "Standard", "Hardcore" };
    } else {
        for (auto &league : doc)
            leagues_.push_back(league["id"].GetString());
    }
    ui->leagueComboBox->clear();
    for (auto &league : leagues_)
        ui->leagueComboBox->addItem(league.c_str());
    ui->leagueComboBox->setEnabled(true);

    if (saved_league_.size() > 0)
        ui->leagueComboBox->setCurrentText(saved_league_);
}
Example #8
0
void Shop::OnEditPageFinished() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(QObject::sender());
    QByteArray bytes = reply->readAll();
    std::string page(bytes.constData(), bytes.size());
    std::string hash = Util::GetCsrfToken(page, "forum_thread");
    if (hash.empty()) {
        QLOG_ERROR() << "Can't update shop -- cannot extract CSRF token from the page. Check if thread ID is valid.";
        submitting_ = false;
        return;
    }

    // now submit our edit

    // holy shit give me some html parser library please
    std::string title = Util::FindTextBetween(page, "<input type=\"text\" name=\"title\" id=\"title\" value=\"", "\" class=\"textInput\">");
    if (title.empty()) {
        QLOG_ERROR() << "Can't update shop -- title is empty. Check if thread ID is valid.";
        submitting_ = false;
        return;
    }

    QUrlQuery query;
    query.addQueryItem("forum_thread", hash.c_str());
    query.addQueryItem("title", title.c_str());
    query.addQueryItem("content", requests_completed_ < shop_data_.size() ? shop_data_[requests_completed_].c_str() : "Empty");
    query.addQueryItem("submit", "Submit");

    QByteArray data(query.query().toUtf8());
    QNetworkRequest request((QUrl(ShopEditUrl(requests_completed_).c_str())));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QNetworkReply *submitted = app_.logged_in_nm().post(request, data);
    new QReplyTimeout(submitted, kEditThreadTimeout);
    connect(submitted, SIGNAL(finished()), this, SLOT(OnShopSubmitted()));
}
void ItemsManagerWorker::Init() {
    items_.clear();
    std::string items = data_manager_.Get("items");
    if (items.size() != 0) {
        rapidjson::Document doc;
        doc.Parse(items.c_str());
        for (auto item = doc.Begin(); item != doc.End(); ++item)
            items_.push_back(std::make_shared<Item>(*item));
    }

    tabs_.clear();
    std::string tabs = data_manager_.Get("tabs");
    if (tabs.size() != 0) {
        rapidjson::Document doc;
        if (doc.Parse(tabs.c_str()).HasParseError()) {
            QLOG_ERROR() << "Malformed tabs data:" << tabs.c_str() << "The error was"
                << rapidjson::GetParseError_En(doc.GetParseError());
            return;
        }
        for (auto &tab : doc) {
            if (!tab.HasMember("n") || !tab["n"].IsString()) {
                QLOG_ERROR() << "Malformed tabs data:" << tabs.c_str() << "Tab doesn't contain its name (field 'n').";
                continue;
            }
            tabs_.push_back(tab["n"].GetString());
        }
    }
    emit ItemsRefreshed(items_, tabs_, true);
}
Example #10
0
void IQmolApplication::initOpenBabel()
{
   QDir dir(QApplication::applicationDirPath());
   dir.cdUp();  
   QString path(dir.absolutePath());

#ifdef Q_WS_MAC
   // Assumed directory structure: IQmol.app/Contents/MacOS/IQmol
   QApplication::addLibraryPath(path + "/Frameworks");
   QApplication::addLibraryPath(path + "/PlugIns");
#else
   // Assumed directory structure: IQmol-xx/bin/IQmol
   QApplication::addLibraryPath(path + "/lib");
   QApplication::addLibraryPath(path + "/lib/plugins");
#endif

#ifdef Q_OS_LINUX
   return;
#endif

   QString env(qgetenv("BABEL_LIBDIR"));
   if (env.isEmpty()) {
      env = path + "/lib/openbabel";
      qputenv("BABEL_LIBDIR", env.toAscii());
      QLOG_INFO() << "Setting BABEL_LIBDIR = " << env;
   }else {
      QLOG_INFO() << "BABEL_LIBDIR already set: " << env;
   }

   env = qgetenv("BABEL_DATADIR");
   if (env.isEmpty()) {
      env = path + "/share/openbabel";
      qputenv("BABEL_DATADIR", env.toAscii());
      QLOG_INFO() << "Setting BABEL_DATADIR = " << env;
   }else {
      QLOG_INFO() << "BABEL_DATADIR already set: " << env;
   }

#ifdef Q_WS_WIN
   QLibrary openBabel("libopenbabel.dll");
#else
   QLibrary openBabel("openbabel");
#endif

   if (!openBabel.load()) {
      QString msg("Could not load library ");
      msg += openBabel.fileName();

      QLOG_ERROR() << msg << " " << openBabel.errorString();
      QLOG_ERROR() << "Library Paths:";
      QLOG_ERROR() << libraryPaths();

      msg += "\n\nPlease ensure the OpenBabel libraries have been installed correctly";
      QMsgBox::critical(0, "IQmol", msg);
      QApplication::quit();
      return;
   }
}
Example #11
0
bool LegacyUpdate::MergeZipFiles(QuaZip *into, QFileInfo from, QSet<QString> &contained,
								 MetainfAction metainf)
{
	setStatus(tr("Installing mods: Adding ") + from.fileName() + " ...");

	QuaZip modZip(from.filePath());
	modZip.open(QuaZip::mdUnzip);

	QuaZipFile fileInsideMod(&modZip);
	QuaZipFile zipOutFile(into);
	for (bool more = modZip.goToFirstFile(); more; more = modZip.goToNextFile())
	{
		QString filename = modZip.getCurrentFileName();
		if (filename.contains("META-INF") && metainf == LegacyUpdate::IgnoreMetainf)
		{
			QLOG_INFO() << "Skipping META-INF " << filename << " from " << from.fileName();
			continue;
		}
		if (contained.contains(filename))
		{
			QLOG_INFO() << "Skipping already contained file " << filename << " from "
						<< from.fileName();
			continue;
		}
		contained.insert(filename);
		QLOG_INFO() << "Adding file " << filename << " from " << from.fileName();

		if (!fileInsideMod.open(QIODevice::ReadOnly))
		{
			QLOG_ERROR() << "Failed to open " << filename << " from " << from.fileName();
			return false;
		}
		/*
		QuaZipFileInfo old_info;
		fileInsideMod.getFileInfo(&old_info);
		*/
		QuaZipNewInfo info_out(fileInsideMod.getActualFileName());
		/*
		info_out.externalAttr = old_info.externalAttr;
		*/
		if (!zipOutFile.open(QIODevice::WriteOnly, info_out))
		{
			QLOG_ERROR() << "Failed to open " << filename << " in the jar";
			fileInsideMod.close();
			return false;
		}
		if (!JlCompress::copyData(fileInsideMod, zipOutFile))
		{
			zipOutFile.close();
			fileInsideMod.close();
			QLOG_ERROR() << "Failed to copy data of " << filename << " into the jar";
			return false;
		}
		zipOutFile.close();
		fileInsideMod.close();
	}
	return true;
}
void UpdaterComponent::downloadUpdate(const QVariantMap& updateInfo)
{
  if (isDownloading())
    return;

  QLOG_INFO() << updateInfo;

  if (!updateInfo.contains("version") ||
      !updateInfo.contains("manifestURL") || !updateInfo.contains("manifestHash") ||
      !updateInfo.contains("fileURL") || !updateInfo.contains("fileHash") || !updateInfo.contains("fileName"))
  {
    QLOG_ERROR() << "updateInfo was missing fields required to carry out this action.";
    return;
  }

  m_version = updateInfo["version"].toString();

  m_manifest = new Update(updateInfo["manifestURL"].toString(),
                          UpdateManager::GetPath("manifest.xml.bz2", m_version, false),
                          updateInfo["manifestHash"].toString(), this);

  // determine if we have a manifest (some distros don't like OE)
  m_hasManifest = ((!m_manifest->m_url.isEmpty()) && (!m_manifest->m_hash.isEmpty()));

  m_file = new Update(updateInfo["fileURL"].toString(),
                      UpdateManager::GetPath(updateInfo["fileName"].toString(), m_version, true),
                      updateInfo["fileHash"].toString(), this);


  if (m_hasManifest)
    connect(m_manifest, &Update::fileDone, this, &UpdaterComponent::fileComplete);

  connect(m_file, &Update::fileDone, this, &UpdaterComponent::fileComplete);

  // create directories we need
  QDir dr(QFileInfo(m_file->m_localPath).dir());
  if (!dr.exists())
  {
    if (!dr.mkpath("."))
    {
      QLOG_ERROR() << "Failed to create update directory:" << dr.absolutePath();
      emit downloadError("Failed to create download directory");
      return;
    }
  }

  // this will first check if the files are done
  // and in that case emit the done signal.
  if (fileComplete(NULL))
    return;

  if (!m_manifest->isReady() && m_hasManifest)
    downloadFile(m_manifest);

  if (!m_file->isReady())
    downloadFile(m_file);
}
Example #13
0
bool M64BirDevice::connectDevice()
{
    int err;
    char str[100];

    // At this point device should point to a valid usb_device if a M64Bir was attached
    if( mDevice == NULL )
    {
        QLOG_ERROR() << "No M64BIR device defined: " << usb_strerror();
        return false;
    }

    // Open the USB device
    usb_dev_handle *handle = usb_open( mDevice );

    err = usb_set_configuration( handle, 1 );
    if( err < 0 )
    {
        QLOG_ERROR() << "usb_set_configuration() returned " << usb_strerror();
        usb_close( handle );
        return false;
    }

    err = usb_claim_interface( handle, 0 );
    if( err < 0 )
    {
        QLOG_ERROR() << "usb_claim_interface() returned " << usb_strerror();
        usb_close( handle );
        return false;
    }

    mDeviceHandle = handle;

    // Print device information
    if( mDevice->descriptor.iManufacturer )
    {
        err = usb_get_string_simple( mDeviceHandle, mDevice->descriptor.iManufacturer, str, sizeof(str) );
        if( err > 0 )
        {
            mDeviceManufacturer = str;
            QLOG_INFO() << "Manufacturer is " << mDeviceManufacturer;
        }
    }
    if( mDevice->descriptor.iProduct )
    {
        err = usb_get_string_simple( mDeviceHandle, mDevice->descriptor.iProduct, str, sizeof(str) );
        if( err > 0 )
        {
            mDeviceProductName = str;
            QLOG_INFO() << "Product is " << mDeviceProductName;
        }
    }

    return true;
}
Example #14
0
void YggdrasilTask::sslErrors(QList<QSslError> errors)
{
	int i = 1;
	for (auto error : errors)
	{
		QLOG_ERROR() << "LOGIN SSL Error #" << i << " : " << error.errorString();
		auto cert = error.certificate();
		QLOG_ERROR() << "Certificate in question:\n" << cert.toText();
		i++;
	}
}
Example #15
0
void OcFeedsModelNew::init()
{
    QLOG_INFO() << "Initializing feeds model";

    if (!m_items.isEmpty())
        clear(false);

    QSqlQuery query;

    int length = 1;

    QString querystring(QString("SELECT COUNT(id) FROM feeds WHERE folderId = %1").arg(folderId()));

    if (!query.exec(querystring)) {
        QLOG_ERROR() << "Feeds mode: failed to select feeds count from database: " << query.lastError().text();
    }

    query.next();

    length += query.value(0).toInt();

    querystring = QString("SELECT %1 AS id, 1 AS type, '%2' AS title, (SELECT localUnreadCount FROM folders WHERE id = %1) AS unreadCount, '' AS iconSource, '' AS iconWidth, '' AS iconHeight ").arg(folderId()).arg(tr("All posts"));

    if (length > 1) {

        querystring.append("UNION ");

        querystring.append(QString("SELECT id, 0 AS type, title, localUnreadCount AS unreadCount, iconSource, iconWidth, iconHeight FROM feeds WHERE folderId = %1 ").arg(folderId()));

    }

    querystring.append("ORDER BY type DESC");

    if (!query.exec(querystring)) {
        QLOG_ERROR() << "Feeds mode: failed to select feeds from database: " << query.lastError().text();
    }

    beginInsertRows(QModelIndex(), 0, length-1);

    while(query.next())
    {
        OcFeedObject *fobj = new OcFeedObject(query.value(0).toInt(),
                                              query.value(1).toInt(),
                                              query.value(2).toString(),
                                              query.value(3).toInt(),
                                              query.value(4).toString(),
                                              query.value(5).toInt(),
                                              query.value(6).toInt());
        m_items.append(fobj);
    }

    endInsertRows();
}
Example #16
0
Process* Process::deserialize(QVariant const& qvariant)
{
   QList<QVariant> list(qvariant.toList());
   bool ok = (list.size() == 6)            &&
           //list[0] is the JobInfo which we test separately
             list[1].canConvert<int>()     &&
             list[2].canConvert<QString>() &&
             list[3].canConvert<QString>() &&
             list[4].canConvert<QString>() &&
             list[5].canConvert<QString>();

   if (!ok) {
      QLOG_ERROR() << "Process deserialization error: Invalid format";
      return 0;
   }

   JobInfo* jobInfo(JobInfo::deserialize(list[0]));
   if (!jobInfo) {
      QLOG_ERROR() << "Process deserialization error: Invalid JobInfo";
      return 0;
   }

   int s(list[1].toInt(&ok));
   Status status;
   if (0 <= s && s <= Unknown) {
      status = (Status)s; 
   }else {
      QLOG_ERROR() << "Process deserialization error: Invalid status";
      return 0;
   }

   // Now that the JobInfo has loaded, check we have a valid server
   QString serverName(jobInfo->get(JobInfo::ServerName));
   Server* server = ServerRegistry::instance().get(serverName);
   if (!server) {
      QLOG_ERROR() << "Process deserialization error: Server " << serverName << " not found ";
      return 0;
   }

   Process* process = new Process(jobInfo);
   process->m_comment    = list[2].toString();
   process->m_id         = list[3].toString();
   process->m_submitTime = list[4].toString();
   process->m_runTime    = list[5].toString();
   process->m_status     = status;

   process->m_timer.reset(Timer::toSeconds(process->m_runTime));

   return process;
}
Example #17
0
void RemoteSubscriber::timelineFinished(QNetworkReply* reply)
{
  if (reply->error() != QNetworkReply::NoError)
  {
    QLOG_ERROR() << "got error code when sending timeline:" << reply->errorString();
#if 0
    if (++m_errors > 10)
    {
      QLOG_ERROR() << "More than 10 errors received. Dropping this subscriber";
      RemoteComponent::Get()->subscriberRemove(clientIdentifier());
    }
#endif
  }
}
Example #18
0
// OLD format:
// https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/5bf6a2d05145ec79387acc0d45c958642fb049fc
void Mod::ReadMCModInfo(QByteArray contents)
{
	auto getInfoFromArray = [&](QJsonArray arr)->void
	{
		if (!arr.at(0).isObject())
			return;
		auto firstObj = arr.at(0).toObject();
		m_mod_id = firstObj.value("modid").toString();
		m_name = firstObj.value("name").toString();
		m_version = firstObj.value("version").toString();
		m_homeurl = firstObj.value("url").toString();
		m_description = firstObj.value("description").toString();
		QJsonArray authors = firstObj.value("authors").toArray();
		if (authors.size() == 0)
			m_authors = "";
		else if (authors.size() >= 1)
		{
			m_authors = authors.at(0).toString();
			for (int i = 1; i < authors.size(); i++)
			{
				m_authors += ", " + authors.at(i).toString();
			}
		}
		m_credits = firstObj.value("credits").toString();
		return;
	};
	QJsonParseError jsonError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
	// this is the very old format that had just the array
	if (jsonDoc.isArray())
	{
		getInfoFromArray(jsonDoc.array());
	}
	else if (jsonDoc.isObject())
	{
		auto val = jsonDoc.object().value("modinfoversion");
		int version = val.toDouble();
		if (version != 2)
		{
			QLOG_ERROR() << "BAD stuff happened to mod json:";
			QLOG_ERROR() << contents;
			return;
		}
		auto arrVal = jsonDoc.object().value("modlist");
		if (arrVal.isArray())
		{
			getInfoFromArray(arrVal.toArray());
		}
	}
}
Example #19
0
QSharedPointer<Tag> Tag::getOrCreate(TagType type, QString &name)
{
    QSqlQuery query;
    query.prepare("SELECT * FROM " TABLE_Tags " WHERE " KEY_Tag_Type " = ? AND " KEY_Tag_Name " = ?");
    query.addBindValue(QVariant((int)type));
    query.addBindValue(QVariant(name));
    query.exec();

    if(query.next())
        return QSharedPointer<Tag>(new Tag(query));
    else
    {
        Tag *tag = new Tag(type, name);
        query.prepare("INSERT INTO " TABLE_Tags " (" KEY_Tag_Type ", " KEY_Tag_Name ") VALUES(?, ?)");
        query.addBindValue(QVariant((int)type));
        query.addBindValue(QVariant(name));

        if(!query.exec())
        {
            QLOG_ERROR() << "Failed to insert tag: " + query.lastError().text();
            return QSharedPointer<Tag>();
        }
        else
        {
            tag->setId(query.lastInsertId().toInt());
        }

        return QSharedPointer<Tag>(tag);
    }
}
Example #20
0
int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);

   // init the logging mechanism
   QsLogging::Logger& logger = QsLogging::Logger::instance();
   logger.setLoggingLevel(QsLogging::TraceLevel);
   const QString sLogPath(QDir(a.applicationDirPath()).filePath("log.txt"));
   QsLogging::DestinationPtr fileDestination(
      QsLogging::DestinationFactory::MakeFileDestination(sLogPath) );
   QsLogging::DestinationPtr debugDestination(
      QsLogging::DestinationFactory::MakeDebugOutputDestination() );
   logger.addDestination(debugDestination.get());
   logger.addDestination(fileDestination.get());
   //logger.setLoggingLevel(QsLogging::InfoLevel);

   QLOG_INFO() << "Program started";
   QLOG_INFO() << "Built with Qt" << QT_VERSION_STR << "running on" << qVersion();

   QLOG_TRACE() << "Here's a" << QString("trace") << "message";
   QLOG_DEBUG() << "Here's a" << static_cast<int>(QsLogging::DebugLevel) << "message";
   QLOG_WARN()  << "Uh-oh!";
   qDebug() << "This message won't be picked up by the logger";
   QLOG_ERROR() << "An error has occurred";
   qWarning() << "Neither will this one";
   QLOG_FATAL() << "Fatal error!";

   const int ret = 0;
   std::cout << std::endl << "Press any key...";
   std::cin.get();
   QLOG_INFO() << "Program exited with return code" << ret;
   return ret;
}
Example #21
0
void ImageThread::errorHandler(QUrl url, int err) {
    switch (err) {
    case 202:
    case 404:
        if (isImage(url)) {
            _blackList->add(url.toString());
            setCompleted(url.toString(), "");
        }
        else {
            // If there are still images in the list, wait until they finished (maybe they still exist)
            // else close immediately
            if (isDownloadFinished()) {
                stop();

                emit errorMessage("404 - Page not found");
                emit closeRequest(this, 404);
            }
            else {
                _closeWhenFinished = true;
            }
        }
        break;

    case 999:
        emit errorMessage("You are banned");
        break;

    default:
        QLOG_ERROR() << "ImageOverview :: Unhandled error (" << url.toString() << "," << err << ")";
        break;
    }
}
void ByteArrayDownload::downloadError(QNetworkReply::NetworkError error)
{
	// error happened during download.
	QLOG_ERROR() << "Error getting URL:" << m_url.toString().toLocal8Bit()
				 << "Network error: " << error;
	m_status = Job_Failed;
}
Example #23
0
void BuildEfpFragment::addFragment(QMouseEvent* e)
{
qDebug() << "Adding EFP fragment with name" << m_name;
   Data::EfpFragment* data(new Data::EfpFragment(m_name));
   if (!data) {
      QLOG_ERROR() << "Failed to create EFP fragment data in builder:" << m_name;
      return;
   }
   Layer::EfpFragment* efp = new Layer::EfpFragment(*data);

qDebug() << "EfpData to go to molecule  Data::Bank?";

   Vec v(m_viewer->worldCoordinatesOf(e));
   Vec c(m_viewer->camera()->position());
   efp->setOrientation(Quaternion(Vec(0.0, 0.0, 1.0), c));
   efp->setPosition(v);

   QList<Layer::Primitive*> primitives; 
   primitives << efp;
   Command::EditPrimitives* cmd(new Command::EditPrimitives("Add EFP fragment", m_molecule));
   cmd->add(primitives);
   m_viewer->postCommand(cmd);

   m_viewer->addToSelection(efp);
   m_manipulateOnly = false;
}
Example #24
0
void OcFeedsModelNew::feedCreated(const QString &name, const int &id)
{
    QSqlQuery query;

    if (!query.exec(QString("SELECT id, localUnreadCount, iconSource, iconWidth, iconHeight, folderId FROM feeds WHERE id = %1").arg(id))) {
        QLOG_ERROR() << "Feeds model: failed to select data of newly created feed from database: " << query.lastError().text();
    }

    query.next();

    if (query.value(5).toInt() == folderId()) {

        QLOG_INFO() << "Feeds model: adding newly created feed";

        beginInsertRows(QModelIndex(), rowCount(), rowCount());

        OcFeedObject *fobj = new OcFeedObject(query.value(0).toInt(),
                                              0,
                                              name,
                                              query.value(1).toInt(),
                                              query.value(2).toString(),
                                              query.value(3).toInt(),
                                              query.value(4).toInt());

        m_items.append(fobj);

        endInsertRows();

        queryAndSetTotalUnread();
    }
}
Example #25
0
//***********************************************************
//* This is the main entry point for an import.  It is passed
//* the file which contains the export data.  It then
//* opens up the file, checks the validity of the data, and
//* then begins to parse through all of the crap.
//***********************************************************
void BatchImport::import(QString file) {
    fileName = file;
    errorMessage = "";

    lastError = 0;
    QFile xmlFile(fileName);
    QFile scanFile(fileName);
    if (!xmlFile.open(QIODevice::ReadOnly) || !scanFile.open(QIODevice::ReadOnly)) {
        lastError = 16;
        errorMessage = "Cannot open file.";
        return;
    }

    reader = new QXmlStreamReader(&xmlFile);
    while (!reader->atEnd()) {
        reader->readNext();
        QLOG_DEBUG() << reader->name().toString();
        if (reader->hasError()) {
            errorMessage = reader->errorString();
            QLOG_ERROR() << "************************* ERROR READING BACKUP " << errorMessage;
            lastError = 16;
            return;
        }
        if (reader->name().toString().toLower() == "noteadd" && reader->isStartElement()) {
            addNoteNode();
        }
    }
    xmlFile.close();
}
Example #26
0
bool InputCEC::openAdapter()
{
    bool ret = false;
    m_lock.lock();

    // try to find devices
    cec_adapter devices[10];
    int devicesCount = m_adapter->FindAdapters(devices, 10, NULL);
    if (devicesCount > 0)
    {
        // list devices
        QLOG_INFO() << "libCEC found" << devicesCount << "CEC adapters.";

        // open first adapter
        m_adapterPort = devices[0].comm;
        if (m_adapter->Open(m_adapterPort.toStdString().c_str()))
        {
            QLOG_INFO() << "Device " << devices[0].path << "was successfully openned";
            ret = true;
        }
        else
        {
            QLOG_ERROR() << "Opening device" << devices[0].path << "failed";
            ret = false;
        }
    }

    m_lock.unlock();
    return ret;
}
void DataSelectionScreen::disableItem(QString name)
{
    QString first = name.split(".")[0];
    QString second = name.split(".")[1];
    QList<QTreeWidgetItem*> items = ui.treeWidget->findItems(second,Qt::MatchExactly | Qt::MatchRecursive,0);
    if (items.size() == 0)
    {
        return;
    }
    for (int i=0;i<items.size();i++)
    {
        //If the item has no parent, it's a top level item and we ignore it anyway.
        if (items[i]->parent())
        {
            if (items[i]->parent()->text(0) == first)
            {
                if (items[i]->checkState(0) != Qt::Unchecked)
                {
                    items[i]->setCheckState(0,Qt::Unchecked);
                    m_enabledList.removeOne(name);
                    return;
                }
            }
        }
    }
    QLOG_ERROR() << "No item found in DataSelectionScreen:disableItem:" << name;
}
Example #28
0
int InputCEC::CecLogMessage(void* cbParam, const cec_log_message message)
{
    InputCEC *cec = (InputCEC*)cbParam;
    switch (message.level)
    {
    case CEC_LOG_ERROR:
        QLOG_ERROR() << "libCEC ERROR:" << message.message;
        break;

    case CEC_LOG_WARNING:
        QLOG_WARN() << "libCEC WARNING:" << message.message;
        break;

    case CEC_LOG_NOTICE:
        QLOG_INFO() << "libCEC NOTICE:" << message.message;
        break;

    case CEC_LOG_DEBUG:
        if (cec->m_verboseLogging)
        {
            QLOG_DEBUG() << "libCEC DEBUG:" << message.message;
        }
        break;

    case CEC_LOG_TRAFFIC:
        break;

    default:
        break;
    }

    return 0;
}
void ParamCompareDialog::populateParamListFromString(QString paramString, QMap<QString, UASParameter*>* list)
{
    QStringList paramSplit = paramString.split("\n");

    foreach (QString paramLine, paramSplit) {
        if (!paramLine.startsWith("#")) {
            QStringList lineSplit = paramLine.split(",");
            if (lineSplit.size() == 2)
            {
                bool ok;
                QLOG_DEBUG() << "load param: " << lineSplit[0] << "=" << lineSplit[1];
                UASParameter* param = new UASParameter();
                param->setName(lineSplit[0]);

                double value = lineSplit[1].toFloat(&ok);
                if (ok){
                    param->setValue(QVariant(value));
                } else {
                    QLOG_ERROR() << "Conversion Failure";
                    param->setValue(QVariant("NaN"));
                }

                list->insert(param->name(), param);

            }
        } else {
            QLOG_DEBUG() << "Comment: " << paramLine;
        }
    }
}
Example #30
0
void Shop::SubmitShopToForum(bool force) {
    if (submitting_) {
        QLOG_WARN() << "Already submitting your shop.";
        return;
    }
    if (threads_.empty()) {
        QLOG_ERROR() << "Asked to update a shop with no shop ID defined.";
        return;
    }

    if (shop_data_outdated_)
        Update();

    std::string previous_hash = app_.data().Get("shop_hash");
    // Don't update the shop if it hasn't changed
    if (previous_hash == shop_hash_ && !force)
        return;

    if (threads_.size() < shop_data_.size()) {
        QLOG_WARN() << "Need" << shop_data_.size() - threads_.size() << "more shops defined to fit all your items.";
    }

    requests_completed_ = 0;
    submitting_ = true;
    SubmitSingleShop();
}