void MainSettingsDialog::openDeleteAutoProfileConfirmDialog()
{
    QMessageBox msgBox;
    msgBox.setText(tr("Are you sure you want to delete the profile?"));
    msgBox.setStandardButtons(QMessageBox::Discard | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Cancel);
    int ret = msgBox.exec();
    if (ret == QMessageBox::Discard)
    {
        int selectedRow = ui->autoProfileTableWidget->currentRow();
        if (selectedRow >= 0)
        {
            QTableWidgetItem *item = ui->autoProfileTableWidget->item(selectedRow, 5);
            //QTableWidgetItem *itemDefault = ui->autoProfileTableWidget->item(selectedRow, 4);
            AutoProfileInfo *info = item->data(Qt::UserRole).value<AutoProfileInfo*>();
            if (info->isCurrentDefault())
            {
                if (info->getGUID() == "all")
                {
                    delete allDefaultProfile;
                    allDefaultProfile = 0;
                }
                else if (defaultAutoProfiles.contains(info->getGUID()))
                {
                    defaultAutoProfiles.remove(info->getGUID());
                    defaultList.removeAll(info);
                    delete info;
                    info = 0;
                }
            }
            else
            {
                if (deviceAutoProfiles.contains(info->getGUID()))
                {
                    QList<AutoProfileInfo*> temp = deviceAutoProfiles.value(info->getGUID());
                    temp.removeAll(info);
                    deviceAutoProfiles.insert(info->getGUID(), temp);
                }

                if (exeAutoProfiles.contains(info->getExe()))
                {
                    QList<AutoProfileInfo*> temp = exeAutoProfiles.value(info->getExe());
                    temp.removeAll(info);
                    exeAutoProfiles.insert(info->getExe(), temp);
                }

                profileList.removeAll(info);

                delete info;
                info = 0;
            }
        }
        ui->autoProfileTableWidget->removeRow(selectedRow);
    }
}
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::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 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();
}
void MainSettingsDialog::addNewAutoProfile()
{
    AddEditAutoProfileDialog *dialog = static_cast<AddEditAutoProfileDialog*>(sender());
    AutoProfileInfo *info = dialog->getAutoProfile();

    bool found = false;
    if (info->isCurrentDefault())
    {
        if (defaultAutoProfiles.contains(info->getGUID()))
        {
            found = true;
        }
    }
    else
    {
        QList<AutoProfileInfo*> templist;
        if (exeAutoProfiles.contains(info->getExe()))
        {
            templist = exeAutoProfiles.value(info->getExe());
        }

        QListIterator<AutoProfileInfo*> iterProfiles(templist);
        while (iterProfiles.hasNext())
        {
            AutoProfileInfo *oldinfo = iterProfiles.next();
            if (info->getExe() == oldinfo->getExe() &&
                info->getGUID() == oldinfo->getGUID())
            {
                found = true;
                iterProfiles.toBack();
            }
        }
    }

    if (!found)
    {
        if (info->isCurrentDefault())
        {
            if (!info->getGUID().isEmpty() && !info->getProfileLocation().isEmpty())
            {
                defaultAutoProfiles.insert(info->getGUID(), info);
                defaultList.append(info);
            }
        }
        else
        {
            if (!info->getGUID().isEmpty() &&
                !info->getProfileLocation().isEmpty() &&
                !info->getExe().isEmpty())
            {
                QList<AutoProfileInfo*> templist;
                templist.append(info);
                exeAutoProfiles.insert(info->getExe(), templist);
                profileList.append(info);

                QList<AutoProfileInfo*> tempDevProfileList;
                if (deviceAutoProfiles.contains(info->getGUID()))
                {
                    tempDevProfileList = deviceAutoProfiles.value(info->getGUID());
                }

                tempDevProfileList.append(info);
                deviceAutoProfiles.insert(info->getGUID(), tempDevProfileList);
            }
        }

        fillGUIDComboBox();
        changeDeviceForProfileTable(ui->devicesComboBox->currentIndex());
    }
}
void MainSettingsDialog::transferEditsToCurrentTableRow()
{
    AddEditAutoProfileDialog *dialog = static_cast<AddEditAutoProfileDialog*>(sender());
    AutoProfileInfo *info = dialog->getAutoProfile();

    // Delete pointers to object that might be misplaced
    // due to an association change.
    QString oldGUID = dialog->getOriginalGUID();
    QString originalExe = dialog->getOriginalExe();
    if (oldGUID != info->getGUID())
    {
        if (defaultAutoProfiles.value(oldGUID) == info)
        {
            defaultAutoProfiles.remove(oldGUID);
        }

        if (info->isCurrentDefault())
        {
            defaultAutoProfiles.insert(info->getGUID(), info);
        }
    }

    if (oldGUID != info->getGUID() && deviceAutoProfiles.contains(oldGUID))
    {
        QList<AutoProfileInfo*> temp = deviceAutoProfiles.value(oldGUID);
        temp.removeAll(info);
        if (temp.count() > 0)
        {
            deviceAutoProfiles.insert(oldGUID, temp);
        }
        else
        {
            deviceAutoProfiles.remove(oldGUID);
        }

        if (deviceAutoProfiles.contains(info->getGUID()))
        {
            QList<AutoProfileInfo*> temp2 = deviceAutoProfiles.value(oldGUID);
            if (!temp2.contains(info))
            {
                temp2.append(info);
                deviceAutoProfiles.insert(info->getGUID(), temp2);
            }
        }
        else if (info->getGUID().toLower() != "all")
        {
            QList<AutoProfileInfo*> temp2;
            temp2.append(info);
            deviceAutoProfiles.insert(info->getGUID(), temp2);
        }
    }
    else if (oldGUID != info->getGUID() && info->getGUID().toLower() != "all")
    {
        QList<AutoProfileInfo*> temp;
        temp.append(info);
        deviceAutoProfiles.insert(info->getGUID(), temp);
    }

    if (!info->isCurrentDefault())
    {
        defaultList.removeAll(info);

        if (!profileList.contains(info))
        {
            profileList.append(info);
        }
    }
    else
    {
        profileList.removeAll(info);

        if (!defaultList.contains(info))
        {
            defaultList.append(info);
        }
    }


    if (originalExe != info->getExe() &&
        exeAutoProfiles.contains(originalExe))
    {
        QList<AutoProfileInfo*> temp = exeAutoProfiles.value(originalExe);
        temp.removeAll(info);
        exeAutoProfiles.insert(originalExe, temp);

        if (exeAutoProfiles.contains(info->getExe()))
        {
            QList<AutoProfileInfo*> temp2 = exeAutoProfiles.value(info->getExe());
            if (!temp2.contains(info))
            {
                temp2.append(info);
                exeAutoProfiles.insert(info->getExe(), temp2);
            }
        }
        else
        {
            QList<AutoProfileInfo*> temp2;
            temp2.append(info);
            exeAutoProfiles.insert(info->getExe(), temp2);
        }

        if (deviceAutoProfiles.contains(info->getGUID()))
        {
            QList<AutoProfileInfo*> temp2 = deviceAutoProfiles.value(info->getGUID());
            if (!temp2.contains(info))
            {
                temp2.append(info);
                deviceAutoProfiles.insert(info->getGUID(), temp2);
            }
        }
        else
        {
            QList<AutoProfileInfo*> temp2;
            temp2.append(info);
            deviceAutoProfiles.insert(info->getGUID(), temp2);
        }
    }

    fillGUIDComboBox();
    changeDeviceForProfileTable(ui->devicesComboBox->currentIndex());
}