427 lines
14 KiB
C++
427 lines
14 KiB
C++
#include "mainwindow.h"
|
||
#include "./ui_mainwindow.h"
|
||
#include "manager.h"
|
||
#include <iostream>
|
||
#include <QFileDialog>
|
||
#include <QString>
|
||
#include <QDateTime>
|
||
#include <QtSql>
|
||
#include <QFileDialog>
|
||
#include<QFile>
|
||
|
||
|
||
const QString MainWindow::fileDialogFilterString = tr("SQLite Database Files (*.sqlite3 *.sqlite *.db *.db3 *.sl3 *.s3db *.sdb *.sqlite2 *.db2 *.sl2 *.s2db)");
|
||
|
||
MainWindow::MainWindow(QWidget *parent)
|
||
: QMainWindow(parent)
|
||
, ui(new Ui::MainWindow)
|
||
{
|
||
ui->setupUi(this);
|
||
this->setFixedSize(800,600);
|
||
// manager = new Manager();
|
||
dial = new AddDialog();
|
||
del = new Del();
|
||
connect(dial,SIGNAL(sendText(Record*)),this,SLOT(addRecordSlot(Record*)));
|
||
connect(del, SIGNAL(trueDelete()), this, SLOT(acceptDelete()));
|
||
crypto = new SimpleCrypt(Q_UINT64_C(0x0c2ad4a4acb9f023));
|
||
// createModel();
|
||
ui->tableViewRecords->setEnabled(true);
|
||
ui->tableViewRecords->setVisible(true);
|
||
}
|
||
|
||
Ui::MainWindow* MainWindow::getUI()
|
||
{
|
||
return ui;
|
||
}
|
||
|
||
void MainWindow::createModel()
|
||
{
|
||
model = new QSqlTableModel(this, m_db); // создание редактируемой модели базы данных.
|
||
|
||
model->setTable("records"); // создание модели таблицы records.
|
||
model->select(); // заполнение модели данными.
|
||
|
||
// Выбор стратегии сохранения изменений в базе данных:
|
||
model->setEditStrategy(QSqlTableModel::OnFieldChange); // сохранение происходит при переходе к другому полю.
|
||
|
||
ui->tableViewRecords->setModel(model); // соединение модели и ее табличного представления в форме.
|
||
|
||
model->setHeaderData(0, Qt::Horizontal, tr("number"));
|
||
model->setHeaderData(1, Qt::Horizontal, tr("name"));
|
||
model->setHeaderData(2, Qt::Horizontal, tr("username"));
|
||
model->setHeaderData(3, Qt::Horizontal, tr("password"));
|
||
model->setHeaderData(4, Qt::Horizontal, tr("URL"));
|
||
model->setHeaderData(5, Qt::Horizontal, tr("note"));
|
||
model->setHeaderData(6, Qt::Horizontal, tr("time"));
|
||
|
||
}
|
||
bool MainWindow::initAppWithDatabaseFile(const QString &dbFileFullPath, const QString &password, bool isCreationNeed) {
|
||
qDebug() << "dbFileFullPath=" << dbFileFullPath;
|
||
if (dbFileFullPath.isEmpty())
|
||
{
|
||
return false;
|
||
}
|
||
connectToDatabase(dbFileFullPath);
|
||
if(isCreationNeed)
|
||
{
|
||
createDatabase(dbFileFullPath, password);
|
||
}
|
||
createModel();
|
||
return true;
|
||
// setUserInterfaceEnabled(true);
|
||
}
|
||
void MainWindow::putRecord(Record* record){
|
||
// query->clear();
|
||
// qDebug() << "query->clear();";
|
||
// query->prepare("SELECT MAX(r.id) AS 'number_of_records' FROM records AS 'r';");
|
||
// query->exec();
|
||
//// if (!query->isActive())
|
||
//// QMessageBox::warning(this, tr("Database Error"), query->lastError().text());
|
||
// query->next();
|
||
// QString count = QString::number(query->value(0).toInt() + 1);
|
||
//// if (id.isEmpty() || lastName.isEmpty() || firstName.isEmpty() || occupation.isEmpty() || yeaOfAdmission.isEmpty())
|
||
//// return;
|
||
|
||
query->clear();
|
||
|
||
QString password = crypto->encryptToString(record->getPassword());
|
||
qDebug() << "Добавление строки:" <<
|
||
query->prepare("INSERT INTO records(id, name, username, password, url, note, time)" \
|
||
"VALUES(:id, :name, :username, :password, :url, :note, :time)");
|
||
// query->prepare("INSERT INTO employees(id, last_name, first_name, occupation, year_of_admission) " \
|
||
// "VALUES(:id, :last_name, :first_name, :occupation, :year_of_admission)");
|
||
query->bindValue(":id", record->getId());
|
||
query->bindValue(":name", record->getName());
|
||
query->bindValue(":username", record->getUsername());
|
||
query->bindValue(":password", password);
|
||
query->bindValue(":url", record->getURL());
|
||
query->bindValue(":note", record->getNote());
|
||
query->bindValue(":time", record->getTime());
|
||
query->exec();
|
||
model->select();
|
||
}
|
||
|
||
Record* MainWindow::getRecord(int index)
|
||
{
|
||
QVariant x = model->record(index-1).value(0);
|
||
int id;
|
||
id = x.toInt();
|
||
query->prepare("SELECT * FROM records WHERE id = (:id)");
|
||
query->bindValue(":id", id);
|
||
query->exec();
|
||
// QSqlRecord rec = query->record();
|
||
//// query->next();
|
||
// std::cout << query->value(1).toString().toStdString();
|
||
// std::cout << rec.value(1).toString().toStdString();
|
||
// Record* r = new Record(query->value(0).toInt(), query->value(1).toString(), query->value(2).toString(), query->value(3).toString(), query->value(4).toString(), query->value(5).toString());
|
||
// qDebug() << "getRecord" ;
|
||
// qDebug() << r->toString();
|
||
// std::cout << r->toStdString();
|
||
QSqlRecord rec = query->record();
|
||
query->next();
|
||
Record *r = new Record();
|
||
r->setId(query->value(rec.indexOf("id")).toInt());
|
||
r->setName(query->value(rec.indexOf("name")).toString());
|
||
r->setUsername(query->value(rec.indexOf("username")).toString());
|
||
r->setPassword(query->value(rec.indexOf("password")).toString());
|
||
r->setURL(query->value(rec.indexOf("url")).toString());
|
||
r->setNote(query->value(rec.indexOf("note")).toString());
|
||
qDebug() << r->getName() << " << name";
|
||
|
||
qDebug() << r->toString();
|
||
|
||
|
||
return r;
|
||
}
|
||
void MainWindow::updateRecord(Record* r)
|
||
{
|
||
// query->prepare("UPDATE records SET name=:name WHERE id=:id");
|
||
// query->prepare("UPDATE records SET username=:username WHERE id=:id");
|
||
// query->prepare("UPDATE records SET password=:password WHERE id=:id");
|
||
// query->prepare("UPDATE records SET url=:url WHERE id=:id");
|
||
// query->prepare("UPDATE records SET note=:note WHERE id=:id");
|
||
// query->bindValue(":id", r->getId());
|
||
// query->bindValue(":name", r->getName());
|
||
// query->bindValue(":username", r->getUsername());
|
||
// query->bindValue(":password", r->getPassword());
|
||
// query->bindValue(":url", r->getURL());
|
||
// query->bindValue(":note", r->getNote());
|
||
}
|
||
void MainWindow::deleteRecord()
|
||
{
|
||
int num = ui->tableViewRecords->currentIndex().row();
|
||
QVariant x = model->record(num).value(0);
|
||
int id;
|
||
id = x.toInt();
|
||
qDebug() << "id = " << id;
|
||
query->clear();
|
||
|
||
qDebug() << "Удаление строки:" <<
|
||
query->exec(QString("DELETE FROM records WHERE id = %1;").arg(id));
|
||
model->select();
|
||
}
|
||
|
||
int MainWindow::getRecordsCount(){
|
||
query->clear();
|
||
qDebug() << "query->clear();";
|
||
query->prepare("SELECT * FROM records");
|
||
query->exec();
|
||
QSqlRecord rec = query->record();
|
||
query->next();
|
||
|
||
int max = query->value(rec.indexOf("id")).toInt();
|
||
int cur = max;
|
||
while(query->next())
|
||
{
|
||
cur = query->value(rec.indexOf("id")).toInt();
|
||
if(max < cur)
|
||
{
|
||
max = cur;
|
||
}
|
||
}
|
||
qDebug() << "max" << max;
|
||
return max;
|
||
}
|
||
void MainWindow::connectToDatabase(const QString &dbName)
|
||
{
|
||
m_db = QSqlDatabase::addDatabase("QSQLITE"); // соединение объекта базы данных с СУБД.
|
||
m_db.setDatabaseName(dbName); // определение имени базы данных.
|
||
|
||
if (!m_db.open()) // проверка на ошибку при открытии или создании базы данных.
|
||
throw "Can't open database!";
|
||
query = new QSqlQuery(m_db); // создание объекта для запроса.
|
||
}
|
||
|
||
void MainWindow::createDatabase(const QString &dbName, const QString &password)
|
||
{
|
||
qDebug() << "В базе не существует таблица records!";
|
||
|
||
query->clear(); // очистка запроса.
|
||
// id
|
||
// name
|
||
// username
|
||
// URL
|
||
// Note
|
||
// Time
|
||
qDebug() << "Создание таблицы records:" <<
|
||
query->exec("CREATE TABLE records(" \
|
||
" id TEXT PRIMARY KEY NOT NULL, /* идентификатор */" \
|
||
" name TEXT, /* имя */" \
|
||
" username TEXT, /* имя пользователя */" \
|
||
" password TEXT, /* пароль */" \
|
||
" url TEXT, /* web url */" \
|
||
" note TEXT, /* примечания */" \
|
||
" time INTEGER /* дата добавления */" \
|
||
");"); // исполнение запроса на добавление записи.
|
||
|
||
delete crypto;
|
||
crypto = new SimpleCrypt(convertPassword(password));
|
||
query->exec("CREATE TABLE keys(id TEXT PRIMARY KEY NOT NULL, word TEXT);");
|
||
query->prepare("INSERT INTO keys(id, word)" \
|
||
"VALUES(:id, :word)");
|
||
query->bindValue(":id", 0);
|
||
query->bindValue(":word", crypto->encryptToString(QString::fromStdString((checkpoint))));
|
||
query->exec();
|
||
}
|
||
|
||
bool MainWindow::checkPassoword(QString word)
|
||
{
|
||
query->prepare("SELECT * FROM keys WHERE id = (:id)");
|
||
query->bindValue(":id", 0);
|
||
query->exec();
|
||
QSqlRecord rec = query->record();
|
||
query->first();
|
||
qDebug() << "checkPassword";
|
||
QString check = query->value(rec.indexOf("word")).toString();
|
||
qDebug() << "check" << check;
|
||
|
||
quint64 value = convertPassword(word);
|
||
delete crypto;
|
||
crypto = new SimpleCrypt(value);
|
||
qDebug() << "QString::fromStdString(checkpoint) = " << QString::fromStdString(checkpoint);
|
||
qDebug() << "crypto->decryptToString(check) = " << crypto->decryptToString(check);
|
||
if(QString::compare(QString::fromStdString(checkpoint), crypto->decryptToString(check)) == 0)
|
||
{
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
// Метод показывающий диалоговое окно для выбора файла для новой базы данных:
|
||
void MainWindow::on_actionCreateNewDatabase_triggered()
|
||
{
|
||
// std::cout << "clicked" << std::endl;
|
||
// QString dbFileFullPath = QFileDialog::getSaveFileName(this, tr("Save SQLite Database File"), "", MainWindow::fileDialogFilterString);
|
||
// initAppWithDatabaseFile(dbFileFullPath);
|
||
// model->select();
|
||
}
|
||
|
||
// Метод показывающий диалоговое окно для выбора файла для открытия созданной ранее базы данных:
|
||
void MainWindow::on_actionOpenDatabase_triggered()
|
||
{
|
||
// QString dbFileFullPath = QFileDialog::getOpenFileName(this, tr("Open SQLite Database File"), "", MainWindow::fileDialogFilterString);
|
||
// initAppWithDatabaseFile(dbFileFullPath);
|
||
// model->select();
|
||
|
||
}
|
||
|
||
|
||
void MainWindow::on_addButton_clicked()
|
||
{
|
||
dial->show();
|
||
std::cout << "add" << std::endl;
|
||
}
|
||
|
||
MainWindow::~MainWindow()
|
||
{
|
||
delete ui;
|
||
}
|
||
|
||
|
||
|
||
void MainWindow::on_pushButton_clicked()
|
||
{
|
||
genpass.show();
|
||
}
|
||
|
||
|
||
void MainWindow::on_deleteButton_clicked()
|
||
{
|
||
del->show();
|
||
}
|
||
|
||
|
||
void MainWindow::on_pushButton_5_clicked()
|
||
{
|
||
ui->stackedWidget->setCurrentIndex(0);
|
||
}
|
||
|
||
|
||
//void MainWindow::on_editButton_clicked()
|
||
//{
|
||
// int num;
|
||
// num = ui->tableViewRecords->selectionModel()->selection().indexes().at(0).row();
|
||
// qDebug() << ++num;
|
||
// Record* r = getRecord(num);
|
||
// ui->lineEdit_name->setText(r->getName());
|
||
// ui->lineEdit_username->setText(r->getUsername());
|
||
// ui->lineEdit_password->setText(r->getPassword());
|
||
// ui->lineEdit_url->setText(r->getURL());
|
||
// ui->lineEdit_note->setText(r->getNote());
|
||
// ui->stackedWidget->setCurrentIndex(2);
|
||
//}
|
||
|
||
|
||
void MainWindow::on_pushButton_7_clicked()
|
||
{
|
||
ui->stackedWidget->setCurrentIndex(0);
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
void MainWindow::on_pushButton_9_clicked()
|
||
{
|
||
ui->stackedWidget->setCurrentIndex(3);
|
||
|
||
qApp->setStyleSheet("QWidget{background-color: #202020;color: #fff;selection-background-color: #ff732d; selection-color: #000;}");
|
||
|
||
|
||
}
|
||
|
||
|
||
void MainWindow::on_action_7_triggered()
|
||
{
|
||
std::cout << "about" << std::endl;
|
||
about.show();
|
||
|
||
|
||
}
|
||
|
||
|
||
//void MainWindow::on_pushButton_2_clicked()
|
||
//{
|
||
// ui->stackedWidget->setCurrentIndex(1);
|
||
//}
|
||
void MainWindow::on_actionExit_triggered()
|
||
{
|
||
QCoreApplication::quit();
|
||
|
||
}
|
||
void MainWindow::on_actionblakc_triggered()
|
||
{
|
||
|
||
}
|
||
|
||
void MainWindow::addRecordSlot(Record *r)
|
||
{
|
||
qDebug() << "id here:";
|
||
// qDebug() << "id: " << ui->tableViewRecords->selectionModel()->selection().indexes().at(0).row();
|
||
// qDebug() << "id: " << getRecordsCount();
|
||
|
||
qDebug() << "id here:";
|
||
// r->setId(ui->tableViewRecords->model()->rowCount() + 1);
|
||
// r->setId(ui->tableViewRecords->selectionModel()->selection().indexes().at(0).row());
|
||
qDebug() << "id here:";
|
||
r->setId(getRecordsCount()+1);
|
||
putRecord(r);
|
||
qDebug() << "id here:";
|
||
|
||
model->select();
|
||
QModelIndex index = ui->tableViewRecords->model()->index(0, 0);
|
||
ui->tableViewRecords->setCurrentIndex(index);
|
||
}
|
||
|
||
//void MainWindow::openDBSlot(QString path)
|
||
//{
|
||
// qDebug() << "opendbdialog";
|
||
// initAppWithDatabaseFile(path);
|
||
// model->select();
|
||
//}
|
||
|
||
void MainWindow::acceptDelete()
|
||
{
|
||
|
||
deleteRecord();
|
||
}
|
||
|
||
//void MainWindow::on_editSaveButton_clicked()
|
||
//{
|
||
// Record* r = new Record();
|
||
// r->setId(ui->tableViewRecords->selectionModel()->selection().indexes().at(0).row());
|
||
// r->setName(ui->lineEdit_name->text());
|
||
// r->setUsername(ui->lineEdit_username->text());
|
||
// r->setPassword(ui->lineEdit_password->text());
|
||
// r->setURL(ui->lineEdit_url->text());
|
||
// r->setNote(ui->lineEdit_note->text());
|
||
// updateRecord(r);
|
||
// model->select();
|
||
// ui->stackedWidget->setCurrentIndex(0);
|
||
// QModelIndex index = ui->tableViewRecords->model()->index(r->getId(), 0);
|
||
// ui->tableViewRecords->setCurrentIndex(index);
|
||
//}
|
||
|
||
|
||
void MainWindow::on_pushButton_4_clicked()
|
||
{
|
||
int num = ui->tableViewRecords->currentIndex().row();
|
||
qDebug() << ++num;
|
||
Record* r = getRecord(num);
|
||
QString password = crypto->decryptToString(r->getPassword());
|
||
ui->lineEdit_name->setText(r->getName());
|
||
ui->lineEdit_username->setText(r->getUsername());
|
||
ui->lineEdit_password->setText(password);
|
||
ui->lineEdit_url->setText(r->getURL());
|
||
ui->lineEdit_note->setText(r->getNote());
|
||
ui->stackedWidget->setCurrentIndex(2);
|
||
|
||
}
|
||
|
||
|
||
void MainWindow::on_pushButton_6_clicked()
|
||
{
|
||
ui->stackedWidget->setCurrentIndex(0);
|
||
}
|
||
|