void AutoProfileWatcher::runAppCheck()
{
    //qDebug() << qApp->applicationFilePath();
    QString appLocation = findAppLocation();
    if (!appLocation.isEmpty() && appLocation != currentApplication)
    {
        currentApplication = appLocation;

        if (appProfileAssignments.contains(appLocation))
        {
            QList<AutoProfileInfo*> autoentries = appProfileAssignments.value(appLocation);
            QListIterator<AutoProfileInfo*> iter(autoentries);
            while (iter.hasNext())
            {
                AutoProfileInfo *info = iter.next();
                if (info->isActive())
                {
                    QString guid = info->getGUID();
                    QString profileLocation = info->getProfileLocation();
                    emit foundApplicableProfile(guid, profileLocation);
                }
            }
        }
        else if ((!defaultProfileAssignments.isEmpty() || allDefaultInfo) &&
                 qApp->applicationFilePath() != appLocation)
        {
            if (allDefaultInfo)
            {
                QString guid = allDefaultInfo->getGUID();
                QString profileLocation = allDefaultInfo->getProfileLocation();
                emit foundApplicableProfile(guid, profileLocation);
            }

            QHashIterator<QString, AutoProfileInfo*> iter(defaultProfileAssignments);
            while (iter.hasNext())
            {
                iter.next();
                AutoProfileInfo *info = iter.value();
                if (info->isActive())
                {
                    QString guid = info->getGUID();
                    QString profileLocation = info->getProfileLocation();
                    emit foundApplicableProfile(guid, profileLocation);
                }
            }

            currentApplication = "";
        }
    }
}
void MainSettingsDialog::fillAllAutoProfilesTable()
{
    for (int i = ui->autoProfileTableWidget->rowCount()-1; i >= 0; i--)
    {
        ui->autoProfileTableWidget->removeRow(i);
    }

    //QStringList tableHeader;
    //tableHeader << tr("Active") << tr("GUID") << tr("Profile") << tr("Application") << tr("Default?")
    //            << tr("Instance");
    //ui->autoProfileTableWidget->setHorizontalHeaderLabels(tableHeader);

    ui->autoProfileTableWidget->horizontalHeader()->setVisible(true);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    ui->autoProfileTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else
    ui->autoProfileTableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif

    ui->autoProfileTableWidget->hideColumn(5);

    int i = 0;

    AutoProfileInfo *info = allDefaultProfile;

    ui->autoProfileTableWidget->insertRow(i);
    QTableWidgetItem *item = new QTableWidgetItem();
    item->setCheckState(info->isActive() ? Qt::Checked : Qt::Unchecked);
    ui->autoProfileTableWidget->setItem(i, 0, item);

    QString deviceName = info->getDeviceName();
    QString guidDisplay = info->getGUID();
    if (!deviceName.isEmpty())
    {
        guidDisplay = QString("%1 ").arg(info->getDeviceName());
        guidDisplay.append(QString("(%1)").arg(info->getGUID()));
    }
    item = new QTableWidgetItem(guidDisplay);
    item->setFlags(item->flags() & ~Qt::ItemIsEditable);
    item->setData(Qt::UserRole, info->getGUID());
    item->setToolTip(info->getGUID());
    ui->autoProfileTableWidget->setItem(i, 1, item);

    QFileInfo profilePath(info->getProfileLocation());
    item = new QTableWidgetItem(profilePath.fileName());
    item->setFlags(item->flags() & ~Qt::ItemIsEditable);
    item->setData(Qt::UserRole, info->getProfileLocation());
    item->setToolTip(info->getProfileLocation());
    ui->autoProfileTableWidget->setItem(i, 2, item);

    QFileInfo exeInfo(info->getExe());
    item = new QTableWidgetItem(exeInfo.fileName());
    item->setFlags(item->flags() & ~Qt::ItemIsEditable);
    item->setData(Qt::UserRole, info->getExe());
    item->setToolTip(info->getExe());
    ui->autoProfileTableWidget->setItem(i, 3, item);

    item = new QTableWidgetItem("Default");
    item->setData(Qt::UserRole, "default");
    ui->autoProfileTableWidget->setItem(i, 4, item);

    item = new QTableWidgetItem("Instance");
    item->setData(Qt::UserRole, QVariant::fromValue<AutoProfileInfo*>(info));
    ui->autoProfileTableWidget->setItem(i, 5, item);

    i++;

    QListIterator<AutoProfileInfo*> iterDefaults(defaultList);
    while (iterDefaults.hasNext())
    {
        AutoProfileInfo *info = iterDefaults.next();
        ui->autoProfileTableWidget->insertRow(i);

        QTableWidgetItem *item = new QTableWidgetItem();
        item->setCheckState(info->isActive() ? Qt::Checked : Qt::Unchecked);
        ui->autoProfileTableWidget->setItem(i, 0, item);

        QString deviceName = info->getDeviceName();
        QString guidDisplay = info->getGUID();
        if (!deviceName.isEmpty())
        {
            guidDisplay = QString("%1 ").arg(info->getDeviceName());
            guidDisplay.append(QString("(%1)").arg(info->getGUID()));
        }

        item = new QTableWidgetItem(guidDisplay);
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        item->setData(Qt::UserRole, info->getGUID());
        item->setToolTip(info->getGUID());
        ui->autoProfileTableWidget->setItem(i, 1, item);

        QFileInfo profilePath(info->getProfileLocation());
        item = new QTableWidgetItem(profilePath.fileName());
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        item->setData(Qt::UserRole, info->getProfileLocation());
        item->setToolTip(info->getProfileLocation());
        ui->autoProfileTableWidget->setItem(i, 2, item);

        QFileInfo exeInfo(info->getExe());
        item = new QTableWidgetItem(exeInfo.fileName());
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        item->setData(Qt::UserRole, info->getExe());
        item->setToolTip(info->getExe());
        ui->autoProfileTableWidget->setItem(i, 3, item);

        item = new QTableWidgetItem("Default");
        item->setData(Qt::UserRole, "default");
        ui->autoProfileTableWidget->setItem(i, 4, item);

        item = new QTableWidgetItem("Instance");
        item->setData(Qt::UserRole, QVariant::fromValue<AutoProfileInfo*>(info));
        ui->autoProfileTableWidget->setItem(i, 5, item);

        i++;
    }

    QListIterator<AutoProfileInfo*> iter(profileList);
    while (iter.hasNext())
    {
        AutoProfileInfo *info = iter.next();
        ui->autoProfileTableWidget->insertRow(i);

        QTableWidgetItem *item = new QTableWidgetItem();
        item->setCheckState(info->isActive() ? Qt::Checked : Qt::Unchecked);
        ui->autoProfileTableWidget->setItem(i, 0, item);

        QString deviceName = info->getDeviceName();
        QString guidDisplay = info->getGUID();
        if (!deviceName.isEmpty())
        {
            guidDisplay = QString("%1 ").arg(info->getDeviceName());
            guidDisplay.append(QString("(%1)").arg(info->getGUID()));
        }
        item = new QTableWidgetItem(guidDisplay);
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        item->setData(Qt::UserRole, info->getGUID());
        item->setToolTip(info->getGUID());
        ui->autoProfileTableWidget->setItem(i, 1, item);

        QFileInfo profilePath(info->getProfileLocation());
        item = new QTableWidgetItem(profilePath.fileName());
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        item->setData(Qt::UserRole, info->getProfileLocation());
        item->setToolTip(info->getProfileLocation());
        ui->autoProfileTableWidget->setItem(i, 2, item);

        QFileInfo exeInfo(info->getExe());
        item = new QTableWidgetItem(exeInfo.fileName());
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        item->setData(Qt::UserRole, info->getExe());
        item->setToolTip(info->getExe());
        ui->autoProfileTableWidget->setItem(i, 3, item);

        item = new QTableWidgetItem();
        item->setData(Qt::UserRole, "");
        ui->autoProfileTableWidget->setItem(i, 4, item);

        item = new QTableWidgetItem("Instance");
        item->setData(Qt::UserRole, QVariant::fromValue<AutoProfileInfo*>(info));
        ui->autoProfileTableWidget->setItem(i, 5, item);

        i++;
    }
}
void AutoProfileWatcher::runAppCheck()
{
    //qDebug() << qApp->applicationFilePath();
    QString appLocation;
    QString baseAppFileName;
    guidSet.clear();

    // Check whether program path needs to be parsed. Removes processing time
    // and need to run Linux specific code searching /proc.
#ifdef Q_OS_LINUX
    if (!appProfileAssignments.isEmpty())
    {
        appLocation = findAppLocation();
    }
#else
    // In Windows, get program location no matter what.
    appLocation = findAppLocation();
    if (!appLocation.isEmpty())
    {
        baseAppFileName = QFileInfo(appLocation).fileName();
    }
#endif

    // More portable check for whether antimicro is the current application
    // with focus.
    QWidget *focusedWidget = qApp->activeWindow();

    QString nowWindow;
    QString nowWindowClass;
    QString nowWindowName;

#ifdef Q_OS_WIN
    nowWindowName = WinExtras::getCurrentWindowText();
#else
    unsigned long currentWindow = X11Extras::getInstance()->getWindowInFocus();
    if (currentWindow > 0)
    {
        unsigned long tempWindow = X11Extras::getInstance()->findParentClient(currentWindow);
        if (tempWindow > 0)
        {
            currentWindow = tempWindow;
        }
        nowWindow = QString::number(currentWindow);
        nowWindowClass = X11Extras::getInstance()->getWindowClass(currentWindow);
        nowWindowName = X11Extras::getInstance()->getWindowTitle(currentWindow);
        //qDebug() << nowWindowClass;
        //qDebug() << nowWindowName;
    }
#endif

    bool checkForTitleChange = windowNameProfileAssignments.size() > 0;

#ifdef Q_OS_WIN
    if (!focusedWidget && ((!appLocation.isEmpty() && appLocation != currentApplication) ||
        (checkForTitleChange && nowWindowName != currentAppWindowTitle)))

#else
    if (!focusedWidget && ((!nowWindow.isEmpty() && nowWindow != currentApplication) ||
        (checkForTitleChange && nowWindowName != currentAppWindowTitle)))

#endif
    {

#ifdef Q_OS_WIN
        currentApplication = appLocation;
#else
        currentApplication = nowWindow;
#endif

        currentAppWindowTitle = nowWindowName;
        //currentApplication = appLocation;

        QSet<AutoProfileInfo*> fullSet;

        if (!appLocation.isEmpty() && appProfileAssignments.contains(appLocation))
        {
            QSet<AutoProfileInfo*> tempSet;
            tempSet = appProfileAssignments.value(appLocation).toSet();
            fullSet.unite(tempSet);
        }
        else if (!baseAppFileName.isEmpty() && appProfileAssignments.contains(baseAppFileName))
        {
            QSet<AutoProfileInfo*> tempSet;
            tempSet = appProfileAssignments.value(baseAppFileName).toSet();
            fullSet.unite(tempSet);
        }

        if (!nowWindowClass.isEmpty() && windowClassProfileAssignments.contains(nowWindowClass))
        {
            QSet<AutoProfileInfo*> tempSet;
            tempSet = windowClassProfileAssignments.value(nowWindowClass).toSet();
            fullSet.unite(tempSet);
        }

        if (!nowWindowName.isEmpty() && windowNameProfileAssignments.contains(nowWindowName))
        {
            QSet<AutoProfileInfo*> tempSet;
            tempSet = windowNameProfileAssignments.value(nowWindowName).toSet();
            fullSet = fullSet.unite(tempSet);
        }

        QHash<QString, int> highestMatchCount;
        QHash<QString, AutoProfileInfo*> highestMatches;

        QSetIterator<AutoProfileInfo*> fullSetIter(fullSet);
        while (fullSetIter.hasNext())
        {
            AutoProfileInfo *info = fullSetIter.next();
            if (info->isActive())
            {
                int numProps = 0;
                numProps += !info->getExe().isEmpty() ? 1 : 0;
                numProps += !info->getWindowClass().isEmpty() ? 1 : 0;
                numProps += !info->getWindowName().isEmpty() ? 1 : 0;

                int numMatched = 0;
                numMatched += info->getExe() == appLocation ? 1 : 0;
                numMatched += info->getWindowClass() == nowWindowClass ? 1 : 0;
                numMatched += info->getWindowName() == nowWindowName ? 1 : 0;

                if (numProps == numMatched)
                {
                    if (highestMatchCount.contains(info->getGUID()))
                    {
                        int currentHigh = highestMatchCount.value(info->getGUID());
                        if (numMatched > currentHigh)
                        {
                            highestMatchCount.insert(info->getGUID(), numMatched);
                            highestMatches.insert(info->getGUID(), info);
                        }
                    }
                    else
                    {
                        highestMatchCount.insert(info->getGUID(), numMatched);
                        highestMatches.insert(info->getGUID(), info);
                    }
                }
            }
        }

        QHashIterator<QString, AutoProfileInfo*> highIter(highestMatches);
        while (highIter.hasNext())
        {
            AutoProfileInfo *info = highIter.next().value();
            guidSet.insert(info->getGUID());
            emit foundApplicableProfile(info);
        }

        if ((!defaultProfileAssignments.isEmpty() || allDefaultInfo) && !focusedWidget)
             //antiProgramLocation != appLocation)
        {
            if (allDefaultInfo)
            {
                if (allDefaultInfo->isActive() && !guidSet.contains("all"))
                {
                    emit foundApplicableProfile(allDefaultInfo);
                }
            }

            QHashIterator<QString, AutoProfileInfo*> iter(defaultProfileAssignments);
            while (iter.hasNext())
            {
                iter.next();
                AutoProfileInfo *info = iter.value();
                if (info->isActive() && !guidSet.contains(info->getGUID()))
                {
                    emit foundApplicableProfile(info);
                }
            }
        }
    }
}
void MainSettingsDialog::saveAutoProfileSettings()
{

    settings->beginGroup("DefaultAutoProfiles");
    QStringList defaultkeys = settings->allKeys();
    settings->endGroup();

    QStringListIterator iterDefaults(defaultkeys);
    while (iterDefaults.hasNext())
    {
        QString tempkey = iterDefaults.next();
        QString guid = QString(tempkey).replace("GUID", "");
        QString testkey = QString("DefaultAutoProfile-%1").arg(guid);
        settings->beginGroup(testkey);
        settings->remove("");
        settings->endGroup();
    }

    settings->beginGroup("DefaultAutoProfiles");
    settings->remove("");
    settings->endGroup();

    settings->beginGroup("DefaultAutoProfileAll");
    settings->remove("");
    settings->endGroup();

    settings->beginGroup("AutoProfiles");
    settings->remove("");
    settings->endGroup();

    if (allDefaultProfile)
    {
        QString profile = allDefaultProfile->getProfileLocation();
        QString defaultActive = allDefaultProfile->isActive() ? "1" : "0";
        if (!profile.isEmpty())
        {
            settings->setValue(QString("DefaultAutoProfileAll/Profile"), profile);
            settings->setValue(QString("DefaultAutoProfileAll/Active"), defaultActive);
        }
    }

    QMapIterator<QString, AutoProfileInfo*> iter(defaultAutoProfiles);
    while (iter.hasNext())
    {
        iter.next();
        QString guid = iter.key();
        AutoProfileInfo *info = iter.value();
        QString profileActive = info->isActive() ? "1" : "0";
        QString deviceName = info->getDeviceName();
        settings->setValue(QString("DefaultAutoProfiles/GUID%1").arg(guid), guid);
        settings->setValue(QString("DefaultAutoProfile-%1/Profile").arg(guid), info->getProfileLocation());
        settings->setValue(QString("DefaultAutoProfile-%1/Active").arg(guid), profileActive);
        settings->setValue(QString("DefaultAutoProfile-%1/DeviceName").arg(guid), deviceName);
    }

    settings->beginGroup("AutoProfiles");
    QString autoActive = ui->activeCheckBox->isChecked() ? "1" : "0";
    settings->setValue("AutoProfilesActive", autoActive);

    QListIterator<AutoProfileInfo*> iterProfiles(profileList);
    int i = 1;
    while (iterProfiles.hasNext())
    {
        AutoProfileInfo *info = iterProfiles.next();
        QString defaultActive = info->isActive() ? "1" : "0";
        settings->setValue(QString("AutoProfile%1Exe").arg(i), info->getExe());
        settings->setValue(QString("AutoProfile%1GUID").arg(i), info->getGUID());
        settings->setValue(QString("AutoProfile%1Profile").arg(i), info->getProfileLocation());
        settings->setValue(QString("AutoProfile%1Active").arg(i), defaultActive);
        settings->setValue(QString("AutoProfile%1DeviceName").arg(i), info->getDeviceName());
    }
    settings->endGroup();
}