diff --git a/krusader/Dialogs/checksumdlg.cpp b/krusader/Dialogs/checksumdlg.cpp index c907df2f..aea2e655 100644 --- a/krusader/Dialogs/checksumdlg.cpp +++ b/krusader/Dialogs/checksumdlg.cpp @@ -1,754 +1,757 @@ /***************************************************************************** * Copyright (C) 2005 Shie Erlich * * Copyright (C) 2007-2008 Csaba Karai * * Copyright (C) 2008 Jonas Bähr * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "checksumdlg.h" #include "../krusader.h" #include "../krglobal.h" #include "../GUI/krlistwidget.h" #include "../GUI/krtreewidget.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +#include +#include +#include +#include +#include +// QtGui +#include +// QtWidgets +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include #include #include #include #include #include #include "../krservices.h" class CS_Tool; // forward typedef void PREPARE_PROC_FUNC(KProcess& proc, CS_Tool *self, const QStringList& files, const QString checksumFile, bool recursive, const QString& type); typedef QStringList GET_FAILED_FUNC(const QStringList& stdOut, const QStringList& stdErr); class CS_Tool { public: enum Type { MD5 = 0, SHA1, SHA256, TIGER, WHIRLPOOL, SFV, CRC, SHA224, SHA384, SHA512, NumOfTypes }; Type type; QString binary; bool recursive; bool standardFormat; PREPARE_PROC_FUNC *create, *verify; GET_FAILED_FUNC *failed; }; class CS_ToolByType { public: QList tools, r_tools; // normal and recursive tools }; // handles md5sum and sha1sum void sumCreateFunc(KProcess& proc, CS_Tool *self, const QStringList& files, const QString, bool recursive, const QString&) { Q_UNUSED(recursive) proc << KrServices::fullPathName(self->binary); Q_ASSERT(!recursive); proc << files; } void sumVerifyFunc(KProcess& proc, CS_Tool *self, const QStringList& /* files */, const QString checksumFile, bool recursive, const QString& /* type */) { Q_UNUSED(recursive) proc << KrServices::fullPathName(self->binary); Q_ASSERT(!recursive); proc << "-c" << checksumFile; } QStringList sumFailedFunc(const QStringList& stdOut, const QStringList& stdErr) { // md5sum and sha1sum print "...: FAILED" for failed files and display // the number of failures to stderr. so if stderr is empty, we'll assume all is ok QStringList result; if (stdErr.size() == 0) return result; result += stdErr; // grep for the ":FAILED" substring const QString tmp = QString(": FAILED").toLocal8Bit(); for (int i = 0; i < stdOut.size();++i) { if (stdOut[i].indexOf(tmp) != -1) result += stdOut[i]; } return result; } // handles *deep binaries void deepCreateFunc(KProcess& proc, CS_Tool *self, const QStringList& files, const QString, bool recursive, const QString&) { proc << KrServices::fullPathName(self->binary); if (recursive) proc << "-r"; proc << "-l" << files; } void deepVerifyFunc(KProcess& proc, CS_Tool *self, const QStringList& files, const QString checksumFile, bool recursive, const QString&) { proc << KrServices::fullPathName(self->binary); if (recursive) proc << "-r"; proc << "-x" << checksumFile << files; } QStringList deepFailedFunc(const QStringList& stdOut, const QStringList&/* stdErr */) { // *deep dumps (via -x) all failed hashes to stdout return stdOut; } // handles cfv binary void cfvCreateFunc(KProcess& proc, CS_Tool *self, const QStringList& files, const QString, bool recursive, const QString& type) { proc << KrServices::fullPathName(self->binary) << "-C" << "-VV"; if (recursive) proc << "-rr"; proc << "-t" << type << "-f-" << "-U" << files; } void cfvVerifyFunc(KProcess& proc, CS_Tool *self, const QStringList& /* files */, const QString checksumFile, bool recursive, const QString&type) { proc << KrServices::fullPathName(self->binary) << "-M"; if (recursive) proc << "-rr"; proc << "-U" << "-VV" << "-t" << type << "-f" << checksumFile;// << files; } QStringList cfvFailedFunc(const QStringList& /* stdOut */, const QStringList& stdErr) { // cfv dumps all failed hashes to stderr return stdErr; } // important: this table should be ordered like so that all md5 tools should be // one after another, and then all sha1 and so on and so forth. they tools must be grouped, // since the code in getTools() counts on it! CS_Tool cs_tools[] = { // type binary recursive stdFmt create_func verify_func failed_func {CS_Tool::MD5, "md5sum", false, true, sumCreateFunc, sumVerifyFunc, sumFailedFunc}, {CS_Tool::MD5, "md5deep", true, true, deepCreateFunc, deepVerifyFunc, deepFailedFunc}, {CS_Tool::MD5, "cfv", true, true, cfvCreateFunc, cfvVerifyFunc, cfvFailedFunc}, {CS_Tool::SHA1, "sha1sum", false, true, sumCreateFunc, sumVerifyFunc, sumFailedFunc}, {CS_Tool::SHA1, "sha1deep", true, true, deepCreateFunc, deepVerifyFunc, deepFailedFunc}, {CS_Tool::SHA1, "cfv", true, true, cfvCreateFunc, cfvVerifyFunc, cfvFailedFunc}, {CS_Tool::SHA224, "sha224sum", false, true, sumCreateFunc, sumVerifyFunc, sumFailedFunc}, {CS_Tool::SHA256, "sha256sum", false, true, sumCreateFunc, sumVerifyFunc, sumFailedFunc}, {CS_Tool::SHA256, "sha256deep", true, true, deepCreateFunc, deepVerifyFunc, deepFailedFunc}, {CS_Tool::SHA384, "sha384sum", false, true, sumCreateFunc, sumVerifyFunc, sumFailedFunc}, {CS_Tool::SHA512, "sha512sum", false, true, sumCreateFunc, sumVerifyFunc, sumFailedFunc}, {CS_Tool::TIGER, "tigerdeep", true, true, deepCreateFunc, deepVerifyFunc, deepFailedFunc}, {CS_Tool::WHIRLPOOL, "whirlpooldeep", true, true, deepCreateFunc, deepVerifyFunc, deepFailedFunc}, {CS_Tool::SFV, "cfv", true, false, cfvCreateFunc, cfvVerifyFunc, cfvFailedFunc}, {CS_Tool::CRC, "cfv", true, false, cfvCreateFunc, cfvVerifyFunc, cfvFailedFunc}, }; QMap cs_textToType; QMap cs_typeToText; void initChecksumModule() { // prepare the dictionaries - pity it has to be manually cs_textToType["md5"] = CS_Tool::MD5; cs_textToType["sha1"] = CS_Tool::SHA1; cs_textToType["sha256"] = CS_Tool::SHA256; cs_textToType["sha224"] = CS_Tool::SHA224; cs_textToType["sha384"] = CS_Tool::SHA384; cs_textToType["sha512"] = CS_Tool::SHA512; cs_textToType["tiger"] = CS_Tool::TIGER; cs_textToType["whirlpool"] = CS_Tool::WHIRLPOOL; cs_textToType["sfv"] = CS_Tool::SFV; cs_textToType["crc"] = CS_Tool::CRC; cs_typeToText[CS_Tool::MD5] = "md5"; cs_typeToText[CS_Tool::SHA1] = "sha1"; cs_typeToText[CS_Tool::SHA256] = "sha256"; cs_typeToText[CS_Tool::SHA224] = "sha224"; cs_typeToText[CS_Tool::SHA384] = "sha384"; cs_typeToText[CS_Tool::SHA512] = "sha512"; cs_typeToText[CS_Tool::TIGER] = "tiger"; cs_typeToText[CS_Tool::WHIRLPOOL] = "whirlpool"; cs_typeToText[CS_Tool::SFV] = "sfv"; cs_typeToText[CS_Tool::CRC] = "crc"; // build the checksumFilter (for usage in KRQuery) QMap::Iterator it; for (it = cs_textToType.begin(); it != cs_textToType.end(); ++it) MatchChecksumDlg::checksumTypesFilter += ("*." + it.key() + ' '); } // -------------------------------------------------- // returns a list of tools which can work with recursive or non-recursive mode and are installed // note: only 1 tool from each type is suggested static QList getTools(bool folders) { QList result; uint i; for (i = 0; i < sizeof(cs_tools) / sizeof(CS_Tool); ++i) { if (!result.isEmpty() && result.last()->type == cs_tools[i].type) continue; // 1 from each type please if (folders && !cs_tools[i].recursive) continue; if (KrServices::cmdExist(cs_tools[i].binary)) result.append(&cs_tools[i]); } return result; } // ------------- CreateChecksumDlg CreateChecksumDlg::CreateChecksumDlg(const QStringList& files, bool containFolders, const QString& path) : QDialog(krApp) { setWindowModality(Qt::WindowModal); setWindowTitle(i18n("Create Checksum")); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); QList tools = getTools(containFolders); if (tools.count() == 0) { // nothing was suggested?! QString error = i18n("Cannot calculate checksum since no supported tool was found. " "Please check the Dependencies page in Krusader's settings."); if (containFolders) error += i18n("Note: you have selected folders, and probably have no recursive checksum tool installed." " Krusader currently supports md5deep, sha1deep, sha256deep, tigerdeep and cfv"); KMessageBox::error(0, error); return; } QWidget * widget = new QWidget(this); QGridLayout *layout = new QGridLayout(widget); int row = 0; // title (icon+text) QHBoxLayout *hlayout = new QHBoxLayout; QLabel *p = new QLabel(widget); p->setPixmap(krLoader->loadIcon("document-edit-sign", KIconLoader::Desktop, 32)); hlayout->addWidget(p); QLabel *l1 = new QLabel(widget); if (containFolders) l1->setText(i18n("About to calculate checksum for the following files and folders:")); else l1->setText(i18n("About to calculate checksum for the following files:")); hlayout->addWidget(l1); layout->addLayout(hlayout, row, 0, 1, 2, Qt::AlignLeft); ++row; // file list KrListWidget *lb = new KrListWidget(widget); lb->addItems(files); layout->addWidget(lb, row, 0, 1, 2); ++row; // checksum method QHBoxLayout *hlayout2 = new QHBoxLayout; QLabel *l2 = new QLabel(i18n("Select the checksum method:"), widget); hlayout2->addWidget(l2); KComboBox *method = new KComboBox(widget); // -- fill the combo with available methods int i; for (i = 0; i < tools.count(); ++i) method->addItem(cs_typeToText[tools.at(i)->type], i); method->setFocus(); hlayout2->addWidget(method); layout->addLayout(hlayout2, row, 0, 1, 2, Qt::AlignLeft); ++row; mainLayout->addWidget(widget); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); mainLayout->addWidget(buttonBox); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); if (exec() != Accepted) return; // else implied: run the process QTemporaryFile tmpOut(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stdout")); tmpOut.open(); // necessary to create the filename QTemporaryFile tmpErr(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stderr")); tmpErr.open(); // necessary to create the filename KProcess proc; CS_Tool *mytool = tools.at(method->currentIndex()); mytool->create(proc, mytool, files, QString(), containFolders, method->currentText()); proc.setOutputChannelMode(KProcess::SeparateChannels); // without this the next 2 lines have no effect! proc.setStandardOutputFile(tmpOut.fileName()); proc.setStandardErrorFile(tmpErr.fileName()); proc.setWorkingDirectory(path); krApp->startWaiting(i18n("Calculating checksums..."), 0, true); QApplication::setOverrideCursor(Qt::WaitCursor); proc.start(); // TODO make use of asynchronous process starting. waitForStarted(int msec = 30000) is blocking // it would be better to connect to started(), error() and finished() if (proc.waitForStarted()) while (proc.state() == QProcess::Running) { usleep(500); qApp->processEvents(); if (krApp->wasWaitingCancelled()) { // user cancelled proc.kill(); QApplication::restoreOverrideCursor(); return; } }; krApp->stopWait(); QApplication::restoreOverrideCursor(); if (proc.exitStatus() != QProcess::NormalExit) { KMessageBox::error(0, i18n("There was an error while running %1.", mytool->binary)); return; } // suggest a filename QString suggestedFilename = path + '/'; if (files.count() > 1) suggestedFilename += ("checksum." + cs_typeToText[mytool->type]); else suggestedFilename += (files[0] + '.' + cs_typeToText[mytool->type]); // send both stdout and stderr QStringList stdOut, stdErr; if (!KrServices::fileToStringList(&tmpOut, stdOut) || !KrServices::fileToStringList(&tmpErr, stdErr)) { KMessageBox::error(krApp, i18n("Error reading stdout or stderr")); return; } ChecksumResultsDlg dlg(stdOut, stdErr, suggestedFilename, mytool->standardFormat); } // ------------- MatchChecksumDlg QString MatchChecksumDlg::checksumTypesFilter; MatchChecksumDlg::MatchChecksumDlg(const QStringList& files, bool containFolders, const QString& path, const QString& checksumFile) : QDialog(krApp) { setWindowTitle(i18n("Verify Checksum")); setWindowModality(Qt::WindowModal); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); QList tools = getTools(containFolders); if (tools.count() == 0) { // nothing was suggested?! QString error = i18n("Cannot verify checksum since no supported tool was found. " "Please check the Dependencies page in Krusader's settings."); if (containFolders) error += i18n("Note: you have selected folders, and probably have no recursive checksum tool installed." " Krusader currently supports md5deep, sha1deep, sha256deep, tigerdeep and cfv"); KMessageBox::error(0, error); return; } QWidget * widget = new QWidget(this); QGridLayout *layout = new QGridLayout(widget); int row = 0; // title (icon+text) QHBoxLayout *hlayout = new QHBoxLayout; QLabel *p = new QLabel(widget); p->setPixmap(krLoader->loadIcon("document-edit-decrypt-verify", KIconLoader::Desktop, 32)); hlayout->addWidget(p); QLabel *l1 = new QLabel(widget); if (containFolders) l1->setText(i18n("About to verify checksum for the following files and folders:")); else l1->setText(i18n("About to verify checksum for the following files:")); hlayout->addWidget(l1); layout->addLayout(hlayout, row, 0, 1, 2, Qt::AlignLeft); ++row; // file list KrListWidget *lb = new KrListWidget(widget); lb->addItems(files); layout->addWidget(lb, row, 0, 1, 2); ++row; // checksum file QHBoxLayout *hlayout2 = new QHBoxLayout; QLabel *l2 = new QLabel(i18n("Checksum file:"), widget); hlayout2->addWidget(l2); KUrlRequester *checksumFileReq = new KUrlRequester(widget); checksumFileReq->setUrl(QUrl::fromLocalFile(path)); if (!checksumFile.isEmpty()) checksumFileReq->setUrl(QUrl::fromLocalFile(checksumFile)); checksumFileReq->setFocus(); hlayout2->addWidget(checksumFileReq); layout->addLayout(hlayout2, row, 0, 1, 2, Qt::AlignLeft); mainLayout->addWidget(widget); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); mainLayout->addWidget(buttonBox); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); if (exec() != Accepted) return; QString file = checksumFileReq->url().toDisplayString(QUrl::PreferLocalFile); QString extension; if (!verifyChecksumFile(file, extension)) { KMessageBox::error(0, i18n("Error reading checksum file %1.
Please specify a valid checksum file.
", file)); return; } // do we have a tool for that extension? int i; CS_Tool *mytool = 0; for (i = 0; i < tools.count(); ++i) if (cs_typeToText[tools.at(i)->type] == extension.toLower()) { mytool = tools.at(i); break; } if (!mytool) { KMessageBox::error(0, i18n("Krusader cannot find a checksum tool that handles %1 on your system. Please check the Dependencies page in Krusader's settings.", extension)); return; } // else implied: run the process QTemporaryFile tmpOut(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stdout")); tmpOut.open(); // necessary to create the filename QTemporaryFile tmpErr(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stderr")); tmpErr.open(); // necessary to create the filename KProcess proc; mytool->verify(proc, mytool, files, file, containFolders, extension); proc.setOutputChannelMode(KProcess::SeparateChannels); // without this the next 2 lines have no effect! proc.setStandardOutputFile(tmpOut.fileName()); proc.setStandardErrorFile(tmpErr.fileName()); proc.setWorkingDirectory(path); krApp->startWaiting(i18n("Verifying checksums..."), 0, true); QApplication::setOverrideCursor(Qt::WaitCursor); proc.start(); // TODO make use of asynchronous process starting. waitForStarted(int msec = 30000) is blocking // it would be better to connect to started(), error() and finished() if (proc.waitForStarted()) while (proc.state() == QProcess::Running) { usleep(500); qApp->processEvents(); if (krApp->wasWaitingCancelled()) { // user cancelled proc.kill(); QApplication::restoreOverrideCursor(); return; } }; if (proc.exitStatus() != QProcess::NormalExit) { KMessageBox::error(0, i18n("There was an error while running %1.", mytool->binary)); return; } QApplication::restoreOverrideCursor(); krApp->stopWait(); // send both stdout and stderr QStringList stdOut, stdErr; if (!KrServices::fileToStringList(&tmpOut, stdOut) || !KrServices::fileToStringList(&tmpErr, stdErr)) { KMessageBox::error(krApp, i18n("Error reading stdout or stderr")); return; } VerifyResultDlg dlg(mytool->failed(stdOut, stdErr)); } bool MatchChecksumDlg::verifyChecksumFile(QString path, QString& extension) { QFileInfo f(path); if (!f.exists() || f.isDir()) return false; // find the extension extension = path.mid(path.lastIndexOf(".") + 1); // TODO: do we know the extension? if not, ask the user for one return true; } // ------------- VerifyResultDlg VerifyResultDlg::VerifyResultDlg(const QStringList& failed) : QDialog(krApp) { setWindowTitle(i18n("Verify Checksum")); setWindowModality(Qt::WindowModal); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); QWidget * widget = new QWidget(this); QGridLayout *layout = new QGridLayout(widget); bool errors = failed.size() > 0; int row = 0; // create the icon and title QHBoxLayout *hlayout = new QHBoxLayout; QLabel p(widget); p.setPixmap(krLoader->loadIcon(errors ? "dialog-error" : "dialog-information", KIconLoader::Desktop, 32)); hlayout->addWidget(&p); QLabel *l1 = new QLabel((errors ? i18n("Errors were detected while verifying the checksums") : i18n("Checksums were verified successfully")), widget); hlayout->addWidget(l1); layout->addLayout(hlayout, row, 0, 1, 2, Qt::AlignLeft); ++row; if (errors) { QLabel *l3 = new QLabel(i18n("The following files have failed:"), widget); layout->addWidget(l3, row, 0, 1, 2); ++row; KrListWidget *lb2 = new KrListWidget(widget); lb2->addItems(failed); layout->addWidget(lb2, row, 0, 1, 2); ++row; } mainLayout->addWidget(widget); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); mainLayout->addWidget(buttonBox); buttonBox->button(QDialogButtonBox::Close)->setDefault(true); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); exec(); } // ------------- ChecksumResultsDlg ChecksumResultsDlg::ChecksumResultsDlg(const QStringList &stdOut, const QStringList &stdErr, const QString& suggestedFilename, bool standardFormat) : QDialog(krApp), _onePerFile(0), _checksumFileSelector(0), _data(stdOut), _suggestedFilename(suggestedFilename) { // md5 tools display errors into stderr, so we'll use that to determine the result of the job bool errors = stdErr.size() > 0; bool successes = stdOut.size() > 0; setWindowTitle(i18n("Create Checksum")); setWindowModality(Qt::WindowModal); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); QWidget * widget = new QWidget(this); QGridLayout *layout = new QGridLayout(widget); int row = 0; // create the icon and title QHBoxLayout *hlayout = new QHBoxLayout; QLabel p(widget); p.setPixmap(krLoader->loadIcon(errors || !successes ? "dialog-error" : "dialog-information", KIconLoader::Desktop, 32)); hlayout->addWidget(&p); QLabel *l1 = new QLabel((errors || !successes ? i18n("Errors were detected while creating the checksums") : i18n("Checksums were created successfully")), widget); hlayout->addWidget(l1); layout->addLayout(hlayout, row, 0, 1, 2, Qt::AlignLeft); ++row; if (successes) { if (errors) { QLabel *l2 = new QLabel(i18n("Here are the calculated checksums:"), widget); layout->addWidget(l2, row, 0, 1, 2); ++row; } KrTreeWidget *lv = new KrTreeWidget(widget); QStringList columns; if (standardFormat) { columns << i18n("Hash"); columns << i18n("File"); lv->setAllColumnsShowFocus(true); } else { columns << i18n("File and hash"); } lv->setHeaderLabels(columns); for (QStringList::ConstIterator it = stdOut.begin(); it != stdOut.end(); ++it) { QString line = (*it); if (standardFormat) { int space = line.indexOf(' '); QTreeWidgetItem * item = new QTreeWidgetItem(lv); item->setText(0, line.left(space)); item->setText(1, line.mid(space + 2)); } else { QTreeWidgetItem * item = new QTreeWidgetItem(lv); item->setText(0, line); } } lv->sortItems(standardFormat ? 1 : 0, Qt::AscendingOrder); layout->addWidget(lv, row, 0, 1, 2); ++row; } if (errors) { QFrame *line1 = new QFrame(widget); line1->setGeometry(QRect(60, 210, 501, 20)); line1->setFrameShape(QFrame::HLine); line1->setFrameShadow(QFrame::Sunken); layout->addWidget(line1, row, 0, 1, 2); ++row; QLabel *l3 = new QLabel(i18n("Here are the errors received:"), widget); layout->addWidget(l3, row, 0, 1, 2); ++row; KrListWidget *lb = new KrListWidget(widget); lb->addItems(stdErr); layout->addWidget(lb, row, 0, 1, 2); ++row; } // save checksum to disk, if any hashes are found if (successes) { QHBoxLayout *hlayout2 = new QHBoxLayout; QLabel *label = new QLabel(i18n("Save checksum to file:"), widget); hlayout2->addWidget(label); _checksumFileSelector = new KUrlRequester(QUrl::fromLocalFile(suggestedFilename), widget); hlayout2->addWidget(_checksumFileSelector, Qt::AlignLeft); layout->addLayout(hlayout2, row, 0, 1, 2, Qt::AlignLeft); ++row; _checksumFileSelector->setFocus(); } if (stdOut.size() > 1 && standardFormat) { _onePerFile = new QCheckBox(i18n("Checksum file for each source file"), widget); _onePerFile->setChecked(false); connect(_onePerFile, SIGNAL(toggled(bool)), _checksumFileSelector, SLOT(setDisabled(bool))); layout->addWidget(_onePerFile, row, 0, 1, 2, Qt::AlignLeft); ++row; } mainLayout->addWidget(widget); QDialogButtonBox *buttonBox; if (successes) { buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); } else { buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); buttonBox->button(QDialogButtonBox::Close)->setDefault(true); } mainLayout->addWidget(buttonBox); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); exec(); } void ChecksumResultsDlg::accept() { if (_onePerFile && _onePerFile->isChecked()) { Q_ASSERT(_data.size() > 1); if (savePerFile()) QDialog::accept(); } else if (!_checksumFileSelector->url().isEmpty()) { if (saveChecksum(_data, _checksumFileSelector->url().toDisplayString(QUrl::PreferLocalFile))) QDialog::accept(); } } bool ChecksumResultsDlg::saveChecksum(const QStringList& data, QString filename) { if (QFile::exists(filename) && KMessageBox::warningContinueCancel(this, i18n("File %1 already exists.\nAre you sure you want to overwrite it?", filename), i18n("Warning"), KGuiItem(i18n("Overwrite"))) != KMessageBox::Continue) { // find a better name to save to filename = QFileDialog::getSaveFileName(0, i18n("Select a file to save to"), QString(), QStringLiteral("*")); if (filename.simplified().isEmpty()) return false; } QFile file(filename); if (file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); for (QStringList::ConstIterator it = data.constBegin(); it != data.constEnd(); ++it) stream << *it << "\n"; file.close(); } if (file.error() != QFile::NoError) { KMessageBox::detailedError(this, i18n("Error saving file %1", filename), file.errorString()); return false; } else return true; } bool ChecksumResultsDlg::savePerFile() { QString type = _suggestedFilename.mid(_suggestedFilename.lastIndexOf('.')); krApp->startWaiting(i18n("Saving checksum files..."), 0); for (QStringList::ConstIterator it = _data.constBegin(); it != _data.constEnd(); ++it) { QString line = (*it); QString filename = line.mid(line.indexOf(' ') + 2) + type; QStringList l; l << line; if (!saveChecksum(l, filename)) { KMessageBox::error(this, i18n("Errors occurred while saving multiple checksums. Stopping")); krApp->stopWait(); return false; } } krApp->stopWait(); return true; } diff --git a/krusader/Dialogs/checksumdlg.h b/krusader/Dialogs/checksumdlg.h index ea42f90f..c2a6888b 100644 --- a/krusader/Dialogs/checksumdlg.h +++ b/krusader/Dialogs/checksumdlg.h @@ -1,78 +1,79 @@ /***************************************************************************** * Copyright (C) 2005 Shie Erlich * * Copyright (C) 2007-2008 Csaba Karai * * Copyright (C) 2008 Jonas Bähr * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef CHECKSUMDLG_H #define CHECKSUMDLG_H -#include +// QtWidgets +#include class KUrlRequester; class QCheckBox; extern void initChecksumModule(); class CreateChecksumDlg: public QDialog { public: CreateChecksumDlg(const QStringList& files, bool containFolders, const QString& path); }; class MatchChecksumDlg: public QDialog { public: MatchChecksumDlg(const QStringList& files, bool containFolders, const QString& path, const QString& checksumFile = QString()); static QString checksumTypesFilter; protected: bool verifyChecksumFile(QString path, QString& extension); }; class ChecksumResultsDlg: public QDialog { public: ChecksumResultsDlg(const QStringList &stdOut, const QStringList &stdErr, const QString& suggestedFilename, bool standardFormat); public slots: virtual void accept() Q_DECL_OVERRIDE; protected: bool saveChecksum(const QStringList& data, QString filename); bool savePerFile(); private: QCheckBox *_onePerFile; KUrlRequester *_checksumFileSelector; QStringList _data; QString _suggestedFilename; }; class VerifyResultDlg: public QDialog { public: VerifyResultDlg(const QStringList& failed); }; #endif // CHECKSUMDLG_H diff --git a/krusader/Dialogs/krdialogs.cpp b/krusader/Dialogs/krdialogs.cpp index 5a8989f6..5d7620b8 100644 --- a/krusader/Dialogs/krdialogs.cpp +++ b/krusader/Dialogs/krdialogs.cpp @@ -1,297 +1,300 @@ /***************************************************************************** * Copyright (C) 2000 Shie Erlich * * Copyright (C) 2000 Rafi Yanai * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "krdialogs.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtGui +#include +#include +// QtWidgets +#include +#include +#include +#include +#include +#include +#include #include #include #include #include #include #include #include "../krglobal.h" #include "../VFS/vfs.h" #include "../defaults.h" QUrl KChooseDir::getFile(QString text, const QUrl& url, const QUrl& cwd) { QScopedPointer dlg(new KUrlRequesterDialog(vfs::ensureTrailingSlash(url), text, krMainWindow)); dlg->urlRequester()->setStartDir(cwd); dlg->urlRequester()->setMode(KFile::File); dlg->exec(); QUrl u = dlg->selectedUrl(); // empty if cancelled if (u.scheme() == "zip" || u.scheme() == "krarc" || u.scheme() == "tar" || u.scheme() == "iso") { if (QDir(u.path()).exists()) { u.setScheme("file"); } } return u; } QUrl KChooseDir::getDir(QString text, const QUrl& url, const QUrl& cwd) { QScopedPointer dlg(new KUrlRequesterDialog(vfs::ensureTrailingSlash(url), text, krMainWindow)); dlg->urlRequester()->setStartDir(cwd); dlg->urlRequester()->setMode(KFile::Directory); dlg->exec(); QUrl u = dlg->selectedUrl(); if (u.scheme() == "zip" || u.scheme() == "krarc" || u.scheme() == "tar" || u.scheme() == "iso") { if (QDir(u.path()).exists()) { u.setScheme("file"); } } return u; } QUrl KChooseDir::getDir(QString text, const QUrl& url, const QUrl& cwd, bool &queue) { QScopedPointer dlg(new KUrlRequesterDlgForCopy(vfs::ensureTrailingSlash(url), text, false, krMainWindow)); dlg->hidePreserveAttrs(); dlg->urlRequester()->setStartDir(cwd); dlg->urlRequester()->setMode(KFile::Directory); dlg->exec(); QUrl u = dlg->selectedURL(); if (u.scheme() == "zip" || u.scheme() == "krarc" || u.scheme() == "tar" || u.scheme() == "iso") { if (QDir(u.path()).exists()) { u.setScheme("file"); } } queue = dlg->enqueue(); return u; } QUrl KChooseDir::getDir(QString text, const QUrl& url, const QUrl& cwd, bool &queue, bool &preserveAttrs) { QScopedPointer dlg(new KUrlRequesterDlgForCopy(vfs::ensureTrailingSlash(url), text, preserveAttrs, krMainWindow)); dlg->urlRequester()->setStartDir(cwd); dlg->urlRequester()->setMode(KFile::Directory); dlg->exec(); QUrl u = dlg->selectedURL(); if (u.scheme() == "zip" || u.scheme() == "krarc" || u.scheme() == "tar" || u.scheme() == "iso") { if (QDir(u.path()).exists()) { u.setScheme("file"); } } preserveAttrs = dlg->preserveAttrs(); queue = dlg->enqueue(); return u; } QUrl KChooseDir::getDir(QString text, const QUrl& url, const QUrl& cwd, bool &queue, bool &preserveAttrs, QUrl &baseURL) { QScopedPointer dlg(new KUrlRequesterDlgForCopy(vfs::ensureTrailingSlash(url), text, preserveAttrs, krMainWindow, true, baseURL)); dlg->urlRequester()->setStartDir(cwd); dlg->urlRequester()->setMode(KFile::Directory); dlg->exec(); QUrl u = dlg->selectedURL(); if (u.scheme() == "zip" || u.scheme() == "krarc" || u.scheme() == "tar" || u.scheme() == "iso") { if (QDir(u.path()).exists()) { u.setScheme("file"); } } if (dlg->copyDirStructure()) { baseURL = dlg->baseURL(); } else { baseURL = QUrl(); } preserveAttrs = dlg->preserveAttrs(); queue = dlg->enqueue(); return u; } KUrlRequesterDlgForCopy::KUrlRequesterDlgForCopy(const QUrl &urlName, const QString& _text, bool /*presAttrs*/, QWidget *parent, bool modal, QUrl baseURL) : QDialog(parent), baseUrlCombo(0), copyDirStructureCB(0), queue(false) { setWindowModality(modal ? Qt::WindowModal : Qt::NonModal); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); mainLayout->addWidget(new QLabel(_text)); urlRequester_ = new KUrlRequester(urlName, this); urlRequester_->setMinimumWidth(urlRequester_->sizeHint().width() * 3); mainLayout->addWidget(urlRequester_); // preserveAttrsCB = new QCheckBox(i18n("Preserve attributes (only for local targets)"), widget); // preserveAttrsCB->setChecked(presAttrs); // topLayout->addWidget(preserveAttrsCB); if (!baseURL.isEmpty()) { QFrame *line = new QFrame(this); line->setFrameStyle(QFrame::HLine | QFrame::Sunken); mainLayout->addWidget(line); copyDirStructureCB = new QCheckBox(i18n("Keep virtual folder structure"), this); connect(copyDirStructureCB, SIGNAL(toggled(bool)), this, SLOT(slotDirStructCBChanged())); copyDirStructureCB->setChecked(false); mainLayout->addWidget(copyDirStructureCB); QWidget *hboxWidget = new QWidget(this); QHBoxLayout * hbox = new QHBoxLayout(hboxWidget); QLabel * lbl = new QLabel(i18n("Base URL:"), hboxWidget); hbox->addWidget(lbl); baseUrlCombo = new QComboBox(hboxWidget); baseUrlCombo->setMinimumWidth(baseUrlCombo->sizeHint().width() * 3); baseUrlCombo->setEnabled(copyDirStructureCB->isChecked()); hbox->addWidget(baseUrlCombo); QUrl temp = baseURL, tempOld; do { QString baseURLText = temp.toDisplayString(QUrl::PreferLocalFile); baseUrlCombo->addItem(baseURLText); tempOld = temp; temp = KIO::upUrl(temp); } while (!tempOld.matches(temp, QUrl::StripTrailingSlash)); baseUrlCombo->setCurrentIndex(0); mainLayout->addWidget(hboxWidget); } QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); mainLayout->addWidget(buttonBox); okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); QPushButton *queueButton = new QPushButton(i18n("F2 Queue"), this); buttonBox->addButton(queueButton, QDialogButtonBox::ActionRole); connect(buttonBox, SIGNAL(accepted()), SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), SLOT(reject())); connect(queueButton, SIGNAL(clicked()), SLOT(slotQueue())); connect(urlRequester_, SIGNAL(textChanged(QString)), SLOT(slotTextChanged(QString))); urlRequester_->setFocus(); bool state = !urlName.isEmpty(); okButton->setEnabled(state); } KUrlRequesterDlgForCopy::KUrlRequesterDlgForCopy() { } void KUrlRequesterDlgForCopy::keyPressEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_F2: slotQueue(); return; default: QDialog::keyPressEvent(e); } } bool KUrlRequesterDlgForCopy::preserveAttrs() { // return preserveAttrsCB->isChecked(); return true; } bool KUrlRequesterDlgForCopy::copyDirStructure() { if (copyDirStructureCB == 0) return false; return copyDirStructureCB->isChecked(); } void KUrlRequesterDlgForCopy::slotTextChanged(const QString & text) { bool state = !text.trimmed().isEmpty(); okButton->setEnabled(state); } void KUrlRequesterDlgForCopy::slotQueue() { queue = true; accept(); } void KUrlRequesterDlgForCopy::slotDirStructCBChanged() { baseUrlCombo->setEnabled(copyDirStructureCB->isChecked()); } QUrl KUrlRequesterDlgForCopy::selectedURL() const { if (result() == QDialog::Accepted) { QUrl url = urlRequester_->url(); if (url.isValid()) KRecentDocument::add(url); return url; } else return QUrl(); } KUrlRequester * KUrlRequesterDlgForCopy::urlRequester() { return urlRequester_; } QUrl KUrlRequesterDlgForCopy::baseURL() const { if (baseUrlCombo == 0) return QUrl(); return QUrl::fromUserInput(baseUrlCombo->currentText(), QString(), QUrl::AssumeLocalFile); } KRGetDate::KRGetDate(QDate date, QWidget *parent) : QDialog(parent, Qt::MSWindowsFixedSizeDialogHint) { setWindowModality(Qt::WindowModal); dateWidget = new KDatePicker(this); dateWidget->setDate(date); dateWidget->resize(dateWidget->sizeHint()); setMinimumSize(dateWidget->sizeHint()); setMaximumSize(dateWidget->sizeHint()); resize(minimumSize()); connect(dateWidget, SIGNAL(dateSelected(QDate)), this, SLOT(setDate(QDate))); connect(dateWidget, SIGNAL(dateEntered(QDate)), this, SLOT(setDate(QDate))); // keep the original date - incase ESC is pressed originalDate = date; } QDate KRGetDate::getDate() { if (exec() == QDialog::Rejected) chosenDate = QDate(); hide(); return chosenDate; } void KRGetDate::setDate(QDate date) { chosenDate = date; accept(); } diff --git a/krusader/Dialogs/krdialogs.h b/krusader/Dialogs/krdialogs.h index a0507112..77375079 100644 --- a/krusader/Dialogs/krdialogs.h +++ b/krusader/Dialogs/krdialogs.h @@ -1,118 +1,121 @@ /***************************************************************************** * Copyright (C) 2000 Shie Erlich * * Copyright (C) 2000 Rafi Yanai * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef KRDIALOGS_H #define KRDIALOGS_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +#include +// QtWidgets +#include +#include +#include +#include +#include +#include +#include +// QtGui +#include #include #include #include /** \class KChooseDir * Used for asking the user for a folder. * example: * \code * QUrl u = KChooseDir::getDir("target folder", "/suggested/path", ACTIVE_PANEL->virtualPath()); * if (u.isEmpty()) { * // user canceled (either by pressing cancel, or esc * } else { * // do you thing here: you've got a safe url to use * } * \endcode */ class KChooseDir { public: /** * \param text - description of the info requested from the user * \param url - a suggested url to appear in the box as a default choice * \param cwd - a path which is the current working directory (usually ACTIVE_PANEL->virtualPath()). * this is used for completion of partial urls */ static QUrl getFile(QString text, const QUrl& url, const QUrl& cwd); static QUrl getDir(QString text, const QUrl& url, const QUrl& cwd); static QUrl getDir(QString text, const QUrl& url, const QUrl& cwd, bool & queue); static QUrl getDir(QString text, const QUrl& url, const QUrl& cwd, bool & queue, bool & preserveAttrs); static QUrl getDir(QString text, const QUrl& url, const QUrl& cwd, bool & queue, bool & preserveAttrs, QUrl &baseURL); }; class KUrlRequesterDlgForCopy : public QDialog { Q_OBJECT public: KUrlRequesterDlgForCopy(const QUrl& url, const QString& text, bool presAttrs, QWidget *parent, bool modal = true, QUrl baseURL = QUrl()); KUrlRequesterDlgForCopy(); QUrl selectedURL() const; QUrl baseURL() const; bool preserveAttrs(); bool enqueue() { return queue; } bool copyDirStructure(); void hidePreserveAttrs() { // preserveAttrsCB->hide(); } KUrlRequester *urlRequester(); protected: virtual void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE; private slots: void slotQueue(); void slotTextChanged(const QString &); void slotDirStructCBChanged(); private: KUrlRequester *urlRequester_; QComboBox *baseUrlCombo; // QCheckBox *preserveAttrsCB; QCheckBox *copyDirStructureCB; QPushButton *okButton; bool queue; }; class KRGetDate : public QDialog { Q_OBJECT public: KRGetDate(QDate date = QDate::currentDate(), QWidget *parent = 0); QDate getDate(); private slots: void setDate(QDate); private: KDatePicker *dateWidget; QDate chosenDate, originalDate; }; #endif diff --git a/krusader/Dialogs/krmaskchoice.cpp b/krusader/Dialogs/krmaskchoice.cpp index 53b2b45a..1763f093 100644 --- a/krusader/Dialogs/krmaskchoice.cpp +++ b/krusader/Dialogs/krmaskchoice.cpp @@ -1,186 +1,188 @@ /*************************************************************************** krmaskchoice.cpp ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "krmaskchoice.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtWidgets +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include "../GUI/krlistwidget.h" /** * Constructs a KRMaskChoice which is a child of 'parent', with the * name 'name' and widget flags set to 'f' * * The dialog will by default be modeless, unless you set 'modal' to * TRUE to construct a modal dialog. */ KRMaskChoice::KRMaskChoice(QWidget* parent) : QDialog(parent) { setModal(true); resize(401, 314); setWindowTitle(i18n("Choose Files")); setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred)); selection = new KComboBox(this); int height = QFontMetrics(selection->font()).height(); height = height + 5 * (height > 14) + 6; selection->setGeometry(QRect(12, 48, 377, height)); selection->setEditable(true); selection->setInsertPolicy(QComboBox::InsertAtTop); selection->setAutoCompletion(true); QWidget* Layout7 = new QWidget(this); Layout7->setGeometry(QRect(10, 10, 380, 30)); hbox = new QHBoxLayout(Layout7); hbox->setSpacing(6); hbox->setContentsMargins(0, 0, 0, 0); PixmapLabel1 = new QLabel(Layout7); PixmapLabel1->setScaledContents(true); PixmapLabel1->setMaximumSize(QSize(31, 31)); // now, add space for the pixmap hbox->addWidget(PixmapLabel1); label = new QLabel(Layout7); label->setText(i18n("Select the following files:")); hbox->addWidget(label); GroupBox1 = new QGroupBox(this); GroupBox1->setGeometry(QRect(11, 77, 379, 190)); GroupBox1->setTitle(i18n("Predefined Selections")); QHBoxLayout * gbLayout = new QHBoxLayout(GroupBox1); QWidget* Layout6 = new QWidget(GroupBox1); gbLayout->addWidget(Layout6); Layout6->setGeometry(QRect(10, 20, 360, 160)); hbox_2 = new QHBoxLayout(Layout6); hbox_2->setSpacing(6); hbox_2->setContentsMargins(0, 0, 0, 0); preSelections = new KrListWidget(Layout6); preSelections->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); preSelections->setWhatsThis(i18n("A predefined selection is a file-mask which you often use.\nSome examples are: \"*.c, *.h\", \"*.c, *.o\", etc.\nYou can add these masks to the list by typing them and pressing the Add button.\nDelete removes a predefined selection and Clear removes all of them.\nNotice that the line in which you edit the mask has its own history, you can scroll it, if needed.")); hbox_2->addWidget(preSelections); vbox = new QVBoxLayout; vbox->setSpacing(6); vbox->setContentsMargins(0, 0, 0, 0); PushButton7 = new QPushButton(Layout6); PushButton7->setText(i18n("Add")); PushButton7->setToolTip(i18n("Adds the selection in the line-edit to the list")); vbox->addWidget(PushButton7); PushButton7_2 = new QPushButton(Layout6); PushButton7_2->setText(i18n("Delete")); PushButton7_2->setToolTip(i18n("Delete the marked selection from the list")); vbox->addWidget(PushButton7_2); PushButton7_3 = new QPushButton(Layout6); PushButton7_3->setText(i18n("Clear")); PushButton7_3->setToolTip(i18n("Clears the entire list of selections")); vbox->addWidget(PushButton7_3); QSpacerItem* spacer = new QSpacerItem(20, 54, QSizePolicy::Fixed, QSizePolicy::Expanding); vbox->addItem(spacer); hbox_2->addLayout(vbox); QWidget* Layout18 = new QWidget(this); Layout18->setGeometry(QRect(10, 280, 379, 30)); hbox_3 = new QHBoxLayout(Layout18); hbox_3->setSpacing(6); hbox_3->setContentsMargins(0, 0, 0, 0); QSpacerItem* spacer_2 = new QSpacerItem(205, 20, QSizePolicy::Expanding, QSizePolicy::Fixed); hbox_3->addItem(spacer_2); PushButton3 = new QPushButton(Layout18); PushButton3->setText(i18n("OK")); hbox_3->addWidget(PushButton3); PushButton3_2 = new QPushButton(Layout18); PushButton3_2->setText(i18n("Cancel")); hbox_3->addWidget(PushButton3_2); // signals and slots connections connect(PushButton3_2, SIGNAL(clicked()), this, SLOT(reject())); connect(PushButton3, SIGNAL(clicked()), this, SLOT(accept())); connect(PushButton7, SIGNAL(clicked()), this, SLOT(addSelection())); connect(PushButton7_2, SIGNAL(clicked()), this, SLOT(deleteSelection())); connect(PushButton7_3, SIGNAL(clicked()), this, SLOT(clearSelections())); connect(selection, SIGNAL(activated(const QString&)), selection, SLOT(setEditText(const QString &))); connect(selection->lineEdit(), SIGNAL(returnPressed()), this, SLOT(accept())); connect(preSelections, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(currentItemChanged(QListWidgetItem *))); connect(preSelections, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(acceptFromList(QListWidgetItem *))); } /* * Destroys the object and frees any allocated resources */ KRMaskChoice::~KRMaskChoice() { // no need to delete child widgets, Qt does it all for us } void KRMaskChoice::addSelection() { qWarning("KRMaskChoice::addSelection(): Not implemented yet!"); } void KRMaskChoice::clearSelections() { qWarning("KRMaskChoice::clearSelections(): Not implemented yet!"); } void KRMaskChoice::deleteSelection() { qWarning("KRMaskChoice::deleteSelection(): Not implemented yet!"); } void KRMaskChoice::acceptFromList(QListWidgetItem *) { qWarning("KRMaskChoice::acceptFromList(QListWidgetItem *): Not implemented yet!"); } void KRMaskChoice::currentItemChanged(QListWidgetItem *) { qWarning("KRMaskChoice::currentItemChanged(QListWidgetItem *): Not implemented yet!"); } diff --git a/krusader/Dialogs/krmaskchoice.h b/krusader/Dialogs/krmaskchoice.h index 97cd474e..e286a623 100644 --- a/krusader/Dialogs/krmaskchoice.h +++ b/krusader/Dialogs/krmaskchoice.h @@ -1,77 +1,78 @@ /*************************************************************************** krmaskchoice.h ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai email : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD H e a d e r F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef KRMASKCHOICE_H #define KRMASKCHOICE_H -#include +// QtWidgets +#include class QVBoxLayout; class QHBoxLayout; class QGroupBox; class QLabel; class QListWidgetItem; class QPushButton; class KComboBox; class KrListWidget; class KRMaskChoice : public QDialog { Q_OBJECT public: KRMaskChoice(QWidget* parent = 0); ~KRMaskChoice(); KComboBox* selection; QLabel* PixmapLabel1; QLabel* label; QGroupBox* GroupBox1; KrListWidget* preSelections; QPushButton* PushButton7; QPushButton* PushButton7_2; QPushButton* PushButton7_3; QPushButton* PushButton3; QPushButton* PushButton3_2; public slots: virtual void addSelection(); virtual void clearSelections(); virtual void deleteSelection(); virtual void acceptFromList(QListWidgetItem *); virtual void currentItemChanged(QListWidgetItem *); protected: QHBoxLayout* hbox; QHBoxLayout* hbox_2; QHBoxLayout* hbox_3; QVBoxLayout* vbox; }; #endif // KRMASKCHOICE_H diff --git a/krusader/Dialogs/krpleasewait.cpp b/krusader/Dialogs/krpleasewait.cpp index 0028522a..915a33c2 100644 --- a/krusader/Dialogs/krpleasewait.cpp +++ b/krusader/Dialogs/krpleasewait.cpp @@ -1,162 +1,165 @@ /*************************************************************************** krpleasewait.cpp ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "krpleasewait.h" -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +#include +// QtGui +#include +// QtWidgets +#include +#include +#include +#include #include #include #include "../krglobal.h" KRPleaseWait::KRPleaseWait(QString msg, QWidget *parent, int count, bool cancel): QProgressDialog(cancel ? 0 : parent) , inc(true) { setModal(!cancel); timer = new QTimer(this); setWindowTitle(i18n("Krusader::Wait")); setMinimumDuration(500); setAutoClose(false); setAutoReset(false); connect(timer, SIGNAL(timeout()), this, SLOT(cycleProgress())); QProgressBar* progress = new QProgressBar(this); progress->setMaximum(count); progress->setMinimum(0); setBar(progress); QLabel* label = new QLabel(this); setLabel(label); QPushButton* btn = new QPushButton(i18n("&Cancel"), this); setCancelButton(btn); btn->setEnabled(canClose = cancel); setLabelText(msg); show(); } void KRPleaseWait::closeEvent(QCloseEvent * e) { if (canClose) { emit canceled(); e->accept(); } else /* if cancel is not allowed, we disable */ e->ignore(); /* the window closing [x] also */ } void KRPleaseWait::incProgress(int howMuch) { setValue(value() + howMuch); } void KRPleaseWait::cycleProgress() { if (inc) setValue(value() + 1); else setValue(value() - 1); if (value() >= 9) inc = false; if (value() <= 0) inc = true; } KRPleaseWaitHandler::KRPleaseWaitHandler(QWidget *parentWindow) : QObject(parentWindow), _parentWindow(parentWindow), job(), dlg(0) { } void KRPleaseWaitHandler::stopWait() { if (dlg != 0) delete dlg; dlg = 0; cycleMutex = incMutex = false; // return cursor to normal arrow _parentWindow->setCursor(Qt::ArrowCursor); } void KRPleaseWaitHandler::startWaiting(QString msg, int count , bool cancel) { if (dlg == 0) { dlg = new KRPleaseWait(msg , _parentWindow, count, cancel); connect(dlg, SIGNAL(canceled()), this, SLOT(killJob())); } incMutex = cycleMutex = _wasCancelled = false; dlg->setValue(0); dlg->setLabelText(msg); if (count == 0) { dlg->setMaximum(10); cycle = true ; cycleProgress(); } else { dlg->setMaximum(count); cycle = false; } } void KRPleaseWaitHandler::cycleProgress() { if (cycleMutex) return; cycleMutex = true; if (dlg) dlg->cycleProgress(); if (cycle) QTimer::singleShot(2000, this, SLOT(cycleProgress())); cycleMutex = false; } void KRPleaseWaitHandler::killJob() { if (!job.isNull()) job->kill(KJob::EmitResult); stopWait(); _wasCancelled = true; } void KRPleaseWaitHandler::setJob(KIO::Job* j) { job = j; } void KRPleaseWaitHandler::incProgress(int i) { if (incMutex) return; incMutex = true; if (dlg) dlg->incProgress(i); incMutex = false; } diff --git a/krusader/Dialogs/krpleasewait.h b/krusader/Dialogs/krpleasewait.h index a1c52984..2cf19146 100644 --- a/krusader/Dialogs/krpleasewait.h +++ b/krusader/Dialogs/krpleasewait.h @@ -1,87 +1,90 @@ /*************************************************************************** krpleasewait.h ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD H e a d e r F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef KRPLEASEWAIT_H #define KRPLEASEWAIT_H -#include -#include -#include -#include +// QtCore +#include +#include +// QtGui +#include +// QtWidgets +#include #include class KRPleaseWait; class KRPleaseWaitHandler : public QObject { Q_OBJECT public: KRPleaseWaitHandler(QWidget *parentWindow); public slots: void startWaiting(QString msg, int count = 0, bool cancel = false); void stopWait(); void cycleProgress(); void incProgress(int i); void killJob(); void setJob(KIO::Job* j); bool wasCancelled() const { return _wasCancelled; } private: QWidget *_parentWindow; QPointer job; KRPleaseWait * dlg; bool cycle, cycleMutex, incMutex, _wasCancelled; }; class KRPleaseWait : public QProgressDialog { Q_OBJECT public: KRPleaseWait(QString msg, QWidget *parent, int count = 0 , bool cancel = false); public slots: void incProgress(int howMuch); void cycleProgress(); protected: bool inc; QTimer* timer; virtual void closeEvent(QCloseEvent * e) Q_DECL_OVERRIDE; bool canClose; }; #endif diff --git a/krusader/Dialogs/krspecialwidgets.cpp b/krusader/Dialogs/krspecialwidgets.cpp index 53f396d8..edf85695 100644 --- a/krusader/Dialogs/krspecialwidgets.cpp +++ b/krusader/Dialogs/krspecialwidgets.cpp @@ -1,323 +1,324 @@ /*************************************************************************** krspecialwidgets.cpp ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "krspecialwidgets.h" #include "krmaskchoice.h" #include "newftpgui.h" #include "../krglobal.h" -#include -#include -#include +// QtGui +#include +#include +#include #include #include #include #include ///////////////////////////////////////////////////////////////////////////// /////////////////////// Pie related widgets ///////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // The pie-related widgets use hard-coded coordinates to create the look. // This is ok since the whole widget is fitted into an existing view and thus // no re-alignments are needed. #define LEFT 10 #define BOTTOM 150 #define WIDTH 120 #define HEIGHT 40 #define Z_HEIGHT 10 #define STARTANGLE 0 #define DEG(x) (16*(x)) QColor KRPie::colors[ 12 ] = {Qt::red, Qt::blue, Qt::green, Qt::cyan, Qt::magenta, Qt::gray, Qt::black, Qt::white, Qt::darkRed, Qt::darkBlue, Qt::darkMagenta, Qt::darkCyan }; ////////////////////////////////////////////////////////////////////////////// /////////////// KRFSDisplay - Filesystem / Freespace Display ///////////////// ////////////////////////////////////////////////////////////////////////////// // This is the full constructor: use it for a mounted filesystem KRFSDisplay::KRFSDisplay(QWidget *parent, QString _alias, QString _realName, KIO::filesize_t _total, KIO::filesize_t _free) : QWidget(parent), totalSpace(_total), freeSpace(_free), alias(_alias), realName(_realName), mounted(true), empty(false), supermount(false) { int leftMargin, topMargin, rightMargin, bottomMargin; getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin); resize(150 + leftMargin + rightMargin, 200 + topMargin + bottomMargin); setMinimumSize(150 + leftMargin + rightMargin, 200 + topMargin + bottomMargin); show(); } // Use this one for an unmounted filesystem KRFSDisplay::KRFSDisplay(QWidget *parent, QString _alias, QString _realName, bool sm) : QWidget(parent), alias(_alias), realName(_realName), mounted(false), empty(false), supermount(sm) { int leftMargin, topMargin, rightMargin, bottomMargin; getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin); resize(150 + leftMargin + rightMargin, 200 + topMargin + bottomMargin); setMinimumSize(150 + leftMargin + rightMargin, 200 + topMargin + bottomMargin); show(); } // This is used only when an empty widget needs to be displayed (for example: // when filesystem statistics haven't been calculated yet) KRFSDisplay::KRFSDisplay(QWidget *parent) : QWidget(parent), empty(true) { int leftMargin, topMargin, rightMargin, bottomMargin; getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin); resize(150 + leftMargin + rightMargin, 200 + topMargin + bottomMargin); setMinimumSize(150 + leftMargin + rightMargin, 200 + topMargin + bottomMargin); show(); } // The main painter! void KRFSDisplay::paintEvent(QPaintEvent *) { QPainter paint(this); if (!empty) { int leftMargin, topMargin, rightMargin, bottomMargin; getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin); // create the text // first, name and location QFont font = paint.font(); font.setWeight(QFont::Bold); paint.setFont(font); paint.drawText(leftMargin + 10, topMargin + 20, alias); font.setWeight(QFont::Normal); paint.setFont(font); paint.drawText(leftMargin + 10, topMargin + 37, '(' + realName + ')'); if (mounted) { // incase the filesystem is already mounted // second, the capacity paint.drawText(leftMargin + 10, topMargin + 70, i18n("Capacity: %1", KIO::convertSizeFromKiB(totalSpace))); // third, the 2 boxes (used, free) QPen systemPen = paint.pen(); paint.setPen(Qt::black); paint.drawRect(leftMargin + 10, topMargin + 90, 10, 10); paint.fillRect(leftMargin + 11, topMargin + 91, 8, 8, QBrush(Qt::gray)); paint.drawRect(leftMargin + 10, topMargin + 110, 10, 10); paint.fillRect(leftMargin + 11, topMargin + 111, 8, 8, QBrush(Qt::white)); // now, the text for the boxes paint.setPen(systemPen); paint.drawText(leftMargin + 25, topMargin + 100, i18n("Used: %1", KIO::convertSizeFromKiB(totalSpace - freeSpace))); paint.drawText(leftMargin + 25, topMargin + 120, i18n("Free: %1", KIO::convertSizeFromKiB(freeSpace))); // first, create the empty pie // bottom... paint.setPen(Qt::black); paint.setBrush(Qt::white); paint.drawPie(leftMargin + LEFT, topMargin + BOTTOM, WIDTH, HEIGHT, STARTANGLE, DEG(360)); // body... paint.setPen(Qt::lightGray); for (int i = 1; i < Z_HEIGHT; ++i) paint.drawPie(leftMargin + LEFT, topMargin + BOTTOM - i, WIDTH, HEIGHT, STARTANGLE, DEG(360)); // side lines... paint.setPen(Qt::black); paint.drawLine(leftMargin + LEFT, topMargin + BOTTOM + HEIGHT / 2, LEFT, BOTTOM + HEIGHT / 2 - Z_HEIGHT); paint.drawLine(leftMargin + LEFT + WIDTH, topMargin + BOTTOM + HEIGHT / 2, LEFT + WIDTH, BOTTOM + HEIGHT / 2 - Z_HEIGHT); // top of the pie paint.drawPie(leftMargin + LEFT, topMargin + BOTTOM - Z_HEIGHT, WIDTH, HEIGHT, STARTANGLE, DEG(360)); // the "used space" slice float i = ((float)(totalSpace - freeSpace) / (totalSpace)) * 360.0; paint.setBrush(Qt::gray); paint.drawPie(leftMargin + LEFT, topMargin + BOTTOM - Z_HEIGHT, WIDTH, HEIGHT, STARTANGLE, (int) DEG(i)); // if we need to draw a 3d stripe ... if (i > 180.0) { for (int j = 1; j < Z_HEIGHT; ++j) paint.drawArc(leftMargin + LEFT, topMargin + BOTTOM - j, WIDTH, HEIGHT, STARTANGLE - 16 * 180, (int)(DEG(i - 180.0))); } } else { // if the filesystem is unmounted... font.setWeight(QFont::Bold); paint.setFont(font); paint.drawText(leftMargin + 10, topMargin + 60, i18n("Not mounted.")); } } else { // if the widget is in empty situation... } } //////////////////////////////////////////////////////////////////////////////// KRPie::KRPie(KIO::filesize_t _totalSize, QWidget *parent) : QWidget(parent), totalSize(_totalSize) { slices.push_back(KRPieSlice(100, Qt::yellow, "DEFAULT")); sizeLeft = totalSize; resize(300, 300); } void KRPie::paintEvent(QPaintEvent *) { QPainter paint(this); // now create the slices float sAngle = STARTANGLE; for (int ndx = 0; ndx != slices.count(); ndx++) { paint.setBrush(slices[ndx].getColor()); paint.setPen(slices[ndx].getColor()); // angles are negative to create a clock-wise drawing of slices float angle = -(slices[ndx].getPerct() / 100 * 360) * 16; for (int i = 1; i < Z_HEIGHT; ++i) paint.drawPie(LEFT, BOTTOM + i, WIDTH, HEIGHT, (int) sAngle, (int) angle); sAngle += angle; } paint.setPen(Qt::yellow); // pen paint.setBrush(Qt::yellow); // fill // for (int i=1; ikey() == Qt::Key_Escape || e->key() == Qt::Key_Backspace) { e->accept(); return true; } return false; } void KrQuickSearch::myKeyPressEvent(QKeyEvent *e) { KConfigGroup gc(krConfig, "Look&Feel"); bool updownCancel = gc.readEntry("Up/Down Cancels Quicksearch", false); switch (e->key()) { case Qt::Key_Escape: emit stop(0); break; case Qt::Key_Return: case Qt::Key_Enter: case Qt::Key_Tab: case Qt::Key_Right: case Qt::Key_Left: emit stop(e); break; case Qt::Key_Down: if(updownCancel) emit stop(e); else otherMatching(text(), 1); break; case Qt::Key_Up: if(updownCancel) emit stop(e); else otherMatching(text(), -1); break; case Qt::Key_Insert: case Qt::Key_Home: case Qt::Key_End: process(e); break; default: keyPressEvent(e); } } void KrQuickSearch::setMatch(bool match) { KConfigGroup gc(krConfig, "Colors"); QString foreground, background; QColor fore, back; QPalette p = QGuiApplication::palette(); if (match) { foreground = "Quicksearch Match Foreground"; background = "Quicksearch Match Background"; fore = Qt::black; back = QColor(192, 255, 192); } else { foreground = "Quicksearch Non-match Foreground"; background = "Quicksearch Non-match Background"; fore = Qt::black; back = QColor(255, 192, 192); } if (gc.readEntry(foreground, QString()) == "KDE default") fore = p.color(QPalette::Active, QPalette::Text); else if (!gc.readEntry(foreground, QString()).isEmpty()) fore = gc.readEntry(foreground, fore); if (gc.readEntry(background, QString()) == "KDE default") back = p.color(QPalette::Active, QPalette::Base); else if (!gc.readEntry(background, QString()).isEmpty()) back = gc.readEntry(background, back); QPalette pal = palette(); pal.setColor(QPalette::Base, back); pal.setColor(QPalette::Text, fore); setPalette(pal); } diff --git a/krusader/Dialogs/krspecialwidgets.h b/krusader/Dialogs/krspecialwidgets.h index 64a57a1c..0d4adaeb 100644 --- a/krusader/Dialogs/krspecialwidgets.h +++ b/krusader/Dialogs/krspecialwidgets.h @@ -1,153 +1,156 @@ /*************************************************************************** krspecialwidgets.h ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD H e a d e r F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef KRSPECIALWIDGETS_H #define KRSPECIALWIDGETS_H -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtGui +#include +#include +#include +#include +// QtWidgets +#include #include #include class KRPieSlice; class KRPie : public QWidget { Q_OBJECT public: KRPie(KIO::filesize_t _totalSize, QWidget *parent = 0); void addSlice(KIO::filesize_t size, QString label); protected: void paintEvent(QPaintEvent *); private: QList slices; KIO::filesize_t totalSize, sizeLeft; static QColor colors[ 12 ]; }; class KRFSDisplay : public QWidget { Q_OBJECT public: // this constructor is used for a mounted filesystem KRFSDisplay(QWidget *parent, QString _alias, QString _realName, KIO::filesize_t _total, KIO::filesize_t _free); // this one is for an unmounted/supermount file system KRFSDisplay(QWidget *parent, QString _alias, QString _realName, bool sm = false); // the last one is used inside MountMan(R), when no filesystem is selected KRFSDisplay(QWidget *parent); inline void setTotalSpace(KIO::filesize_t t) { totalSpace = t; } inline void setFreeSpace(KIO::filesize_t t) { freeSpace = t; } inline void setAlias(QString a) { alias = a; } inline void setRealName(QString r) { realName = r; } inline void setMounted(bool m) { mounted = m; } inline void setEmpty(bool e) { empty = e; } inline void setSupermount(bool s) { supermount = s; } protected: void paintEvent(QPaintEvent *); private: KIO::filesize_t totalSpace, freeSpace; QString alias, realName; bool mounted, empty, supermount; }; class KRPieSlice { public: KRPieSlice(float _perct, QColor _color, QString _label) : perct(_perct), color(_color), label(_label) {} inline QColor getColor() { return color; } inline float getPerct() { return perct; } inline QString getLabel() { return label; } inline void setPerct(float _perct) { perct = _perct; } inline void setLabel(QString _label) { label = _label; } private: float perct; QColor color; QString label; }; class KrQuickSearch: public KLineEdit { Q_OBJECT public: KrQuickSearch(QWidget *parent); void addText(const QString &str) { setText(text() + str); } bool shortcutOverride(QKeyEvent *e); void myKeyPressEvent(QKeyEvent *e); void setMatch(bool match); void myInputMethodEvent(QInputMethodEvent* e) { inputMethodEvent(e); } signals: void stop(QKeyEvent *e); void process(QKeyEvent *e); void otherMatching(const QString &, int); }; #endif diff --git a/krusader/Dialogs/krspwidgets.cpp b/krusader/Dialogs/krspwidgets.cpp index c6d0a81b..8d451e2b 100644 --- a/krusader/Dialogs/krspwidgets.cpp +++ b/krusader/Dialogs/krspwidgets.cpp @@ -1,362 +1,365 @@ /*************************************************************************** krspwidgets.cpp ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "krspwidgets.h" #include "../krglobal.h" #include "../kicons.h" #include "../Filter/filtertabs.h" #include "../GUI/krlistwidget.h" -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtGui +#include +// QtWidgets +#include +#include +#include +#include +#include #include // missing ? #include #include #include #include #include #include ///////////////////// initiation of the static members //////////////////////// QStringList KRSpWidgets::maskList; /////////////////////////////////////////////////////////////////////////////// KRSpWidgets::KRSpWidgets() { } KRQuery KRSpWidgets::getMask(QString caption, bool nameOnly, QWidget * parent) { if (!nameOnly) { return FilterTabs::getQuery(parent); } else { QPointer p = new KRMaskChoiceSub(parent); p->setWindowTitle(caption); p->exec(); QString selection = p->selection->currentText(); delete p; if (selection.isEmpty()) { return KRQuery(); } else { return KRQuery(selection); } } } /////////////////////////// newFTP //////////////////////////////////////// QUrl KRSpWidgets::newFTP() { QPointer p = new newFTPSub(); p->exec(); QString uri = p->url->currentText(); if (uri.isEmpty()) { delete p; return QUrl(); // empty url } QString protocol = p->prefix->currentText(); protocol.truncate(protocol.length() - 3); // remove the trailing :// QString username = p->username->text().simplified(); QString password = p->password->text().simplified(); int uriStart = uri.lastIndexOf('@'); /* lets the user enter user and password in the URI field */ if (uriStart != -1) { QString uriUser = uri.left(uriStart); QString uriPsw; uri = uri.mid(uriStart + 1); int pswStart = uriUser.indexOf(':'); /* getting the password name from the URL */ if (pswStart != -1) { uriPsw = uriUser.mid(pswStart + 1); uriUser = uriUser.left(pswStart); } if (!uriUser.isEmpty()) { /* handling the ftp proxy username and password also */ username = username.isEmpty() ? uriUser : username + '@' + uriUser; } if (!uriPsw.isEmpty()) { /* handling the ftp proxy username and password also */ password = password.isEmpty() ? uriPsw : password + '@' + uriPsw; } } QString host = uri; /* separating the hostname and path from the uri */ QString path; int pathStart = uri.indexOf("/"); if (pathStart != -1) { path = host.mid(pathStart); host = host.left(pathStart); } /* setting the parameters of the URL */ QUrl url; url.setScheme(protocol); url.setHost(host); url.setPath(path); if (protocol == "ftp" || protocol == "fish" || protocol == "sftp") { url.setPort(p->port->cleanText().toInt()); } if (!username.isEmpty()) { url.setUserName(username); } if (!password.isEmpty()) { url.setPassword(password); } delete p; return url; } newFTPSub::newFTPSub() : newFTPGUI(0) { url->setFocus(); setGeometry(krMainWindow->x() + krMainWindow->width() / 2 - width() / 2, krMainWindow->y() + krMainWindow->height() / 2 - height() / 2, width(), height()); } void newFTPSub::accept() { url->addToHistory(url->currentText()); // save the history and completion list when the history combo is // destroyed KConfigGroup group(krConfig, "Private"); QStringList list = url->completionObject()->items(); group.writeEntry("newFTP Completion list", list); list = url->historyItems(); group.writeEntry("newFTP History list", list); QString protocol = prefix->currentText(); group.writeEntry("newFTP Protocol", protocol); newFTPGUI::accept(); } void newFTPSub::reject() { url->lineEdit()->setText(""); newFTPGUI::reject(); } /////////////////////////// KRMaskChoiceSub /////////////////////////////// KRMaskChoiceSub::KRMaskChoiceSub(QWidget * parent) : KRMaskChoice(parent) { PixmapLabel1->setPixmap(krLoader->loadIcon("edit-select", KIconLoader::Desktop, 32)); label->setText(i18n("Enter a selection:")); // the predefined selections list KConfigGroup group(krConfig, "Private"); QStringList lst = group.readEntry("Predefined Selections", QStringList()); if (lst.size() > 0) preSelections->addItems(lst); // the combo-box tweaks selection->setDuplicatesEnabled(false); selection->addItems(KRSpWidgets::maskList); selection->lineEdit()->setText("*"); selection->lineEdit()->selectAll(); selection->setFocus(); } void KRMaskChoiceSub::reject() { selection->clear(); KRMaskChoice::reject(); } void KRMaskChoiceSub::accept() { bool add = true; // make sure we don't have that already for (int i = 0; i != KRSpWidgets::maskList.count(); i++) if (KRSpWidgets::maskList[ i ].simplified() == selection->currentText().simplified()) { // break if we found one such as this add = false; break; } if (add) KRSpWidgets::maskList.insert(0, selection->currentText().toLocal8Bit()); // write down the predefined selections list QStringList list; for (int j = 0; j != preSelections->count(); j++) { QListWidgetItem *i = preSelections->item(j); list.append(i->text()); } KConfigGroup group(krConfig, "Private"); group.writeEntry("Predefined Selections", list); KRMaskChoice::accept(); } void KRMaskChoiceSub::addSelection() { QString temp = selection->currentText(); bool itemExists = false; // check if the selection already exists for (int j = 0; j != preSelections->count(); j++) { QListWidgetItem *i = preSelections->item(j); if (i->text() == temp) { itemExists = true; break; } } if (!temp.isEmpty() && !itemExists) { preSelections->addItem(selection->currentText()); preSelections->update(); } } void KRMaskChoiceSub::deleteSelection() { delete preSelections->currentItem(); preSelections->update(); } void KRMaskChoiceSub::clearSelections() { preSelections->clear(); preSelections->update(); } void KRMaskChoiceSub::acceptFromList(QListWidgetItem *i) { selection->addItem(i->text(), 0); accept(); } void KRMaskChoiceSub::currentItemChanged(QListWidgetItem *i) { if (i) selection->setEditText(i->text()); } ////////////////////////// QuickNavLineEdit //////////////////// QuickNavLineEdit::QuickNavLineEdit(const QString &string, QWidget *parent): KLineEdit(string, parent) { init(); } QuickNavLineEdit::QuickNavLineEdit(QWidget *parent): KLineEdit(parent) { init(); } int QuickNavLineEdit::findCharFromPos(const QString & str, const QFontMetrics & metrics, int pos) { if (pos < 0) return -1; for (int i = 1; i <= (int)str.length(); ++i) if (metrics.width(str, i) > pos) return i; return str.length(); } void QuickNavLineEdit::init() { _numOfSelectedChars = 0; _dummyDisplayed = false; _pop = 0; } void QuickNavLineEdit::leaveEvent(QEvent *) { clearAll(); } void QuickNavLineEdit::mousePressEvent(QMouseEvent *m) { if (m->modifiers() != Qt::ControlModifier) clearAll(); else { if (!_numOfSelectedChars) { _numOfSelectedChars = charCount(m); if (_numOfSelectedChars < 0) _numOfSelectedChars = 0; } if (_numOfSelectedChars) emit returnPressed(text().left(_numOfSelectedChars)); } KLineEdit::mousePressEvent(m); } int QuickNavLineEdit::charCount(const QMouseEvent * const m, QString * const str) { // find how much of the string we've selected (approx) // and select from from the start to the closet slash (on the right) const QString tx = text().simplified(); if (tx.isEmpty()) { clearAll(); return -1; } int numOfChars = findCharFromPos(tx, fontMetrics(), m->x() - 5); if (str) *str = tx; return tx.indexOf('/', numOfChars); } void QuickNavLineEdit::mouseMoveEvent(QMouseEvent *m) { if (m->modifiers() != Qt::ControlModifier) { // works only with ctrl pressed clearAll(); KLineEdit::mouseMoveEvent(m); return; } QString tx; int idx = charCount(m, &tx); QPixmap pm = krLoader->loadIcon("help-hint", KIconLoader::Desktop, 32); if (idx == -1 && !_dummyDisplayed) { // pointing on or after the current directory if (_pop) delete _pop; _pop = KPassivePopup::message(i18n("Quick Navigation"), "" + i18n("Already at %1", tx.left(idx)) + "", pm, this); _dummyDisplayed = true; _numOfSelectedChars = 0; } else if (idx > 0 && idx != _numOfSelectedChars) { _numOfSelectedChars = idx; if (_pop) delete _pop; _dummyDisplayed = false; _pop = KPassivePopup::message(i18n("Quick Navigation"), "" + i18n("Click to go to %1", tx.left(idx)) + "", pm, this); } KLineEdit::mouseMoveEvent(m); } diff --git a/krusader/Dialogs/krspwidgets.h b/krusader/Dialogs/krspwidgets.h index 2451d7ad..b9b8cd3c 100644 --- a/krusader/Dialogs/krspwidgets.h +++ b/krusader/Dialogs/krspwidgets.h @@ -1,119 +1,121 @@ /*************************************************************************** krspwidgets.h ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD H e a d e r F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef KRSPWIDGETS_H #define KRSPWIDGETS_H -#include -#include +// QtCore +#include +// QtGui +#include #include #include #include "krmaskchoice.h" #include "newftpgui.h" #include "../VFS/krquery.h" class newFTPGUI; class KRMaskChoiceSub; class KRSpWidgets { friend class KRMaskChoiceSub; public: KRSpWidgets(); static KRQuery getMask(QString caption, bool nameOnly = false, QWidget * parent = 0); // get file-mask for (un)selecting files static QUrl newFTP(); private: static QStringList maskList; // used by KRMaskChoiceSub }; /////////////////////////// newFTPSub /////////////////////////////////////// class newFTPSub : public newFTPGUI { public: newFTPSub(); protected: void reject(); void accept(); }; /////////////////////////// KRMaskChoiceSub ///////////////////////////////// // Inherits KRMaskChoice's generated code to fully implement the functions // ///////////////////////////////////////////////////////////////////////////// class KRMaskChoiceSub : public KRMaskChoice { public: KRMaskChoiceSub(QWidget * parent = 0); public slots: void addSelection(); void deleteSelection(); void clearSelections(); void acceptFromList(QListWidgetItem *i); void currentItemChanged(QListWidgetItem *i); protected: void reject(); void accept(); }; /////////////////////////// QuickNavLineEdit ////////////////////////// // same as line edit, but hold ctrl while pointing to it... and see! // /////////////////////////////////////////////////////////////////////// class QuickNavLineEdit: public KLineEdit { public: QuickNavLineEdit(const QString &string, QWidget *parent); QuickNavLineEdit(QWidget *parent = 0); virtual ~QuickNavLineEdit() {} static int findCharFromPos(const QString &, const QFontMetrics &, int pos); protected: void mouseMoveEvent(QMouseEvent *m); void leaveEvent(QEvent *); void mousePressEvent(QMouseEvent *m); inline void clearAll() { _numOfSelectedChars = 0; if (_pop) _pop->deleteLater(); _pop = 0; _dummyDisplayed = false; } void init(); private: int charCount(const QMouseEvent * const , QString* const = 0) ; int _numOfSelectedChars; bool _dummyDisplayed; QPointer _pop; }; #endif diff --git a/krusader/Dialogs/krsqueezedtextlabel.cpp b/krusader/Dialogs/krsqueezedtextlabel.cpp index b1f978e4..d8612c96 100644 --- a/krusader/Dialogs/krsqueezedtextlabel.cpp +++ b/krusader/Dialogs/krsqueezedtextlabel.cpp @@ -1,119 +1,121 @@ /***************************************************************************** * Copyright (C) 2002 Shie Erlich * * Copyright (C) 2002 Rafi Yanai * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "krsqueezedtextlabel.h" -#include -#include -#include -#include -#include +// QtGui +#include +#include +#include +// QtWidgets +#include +#include #include #include KrSqueezedTextLabel::KrSqueezedTextLabel(QWidget *parent): KSqueezedTextLabel(parent), acceptDrops(false), _index(-1), _length(-1) { setAutoFillBackground(true); } KrSqueezedTextLabel::~KrSqueezedTextLabel() { } void KrSqueezedTextLabel::mousePressEvent(QMouseEvent *e) { e->ignore(); emit clicked(e); } void KrSqueezedTextLabel::enableDrops(bool flag) { setAcceptDrops(acceptDrops = flag); } void KrSqueezedTextLabel::dropEvent(QDropEvent *e) { emit dropped(e); } void KrSqueezedTextLabel::dragEnterEvent(QDragEnterEvent *e) { if (acceptDrops) { QList URLs = KUrlMimeData::urlsFromMimeData(e->mimeData()); e->setAccepted(!URLs.isEmpty()); } else KSqueezedTextLabel::dragEnterEvent(e); } void KrSqueezedTextLabel::squeezeTextToLabel(int index, int length) { if (index == -1 || length == -1) KSqueezedTextLabel::squeezeTextToLabel(); else { QString sqtext = fullText; QFontMetrics fm(fontMetrics()); int labelWidth = size().width(); int textWidth = fm.width(sqtext); if (textWidth > labelWidth) { int avgCharSize = textWidth / sqtext.length(); int numOfExtraChars = (textWidth - labelWidth) / avgCharSize; int delta; // remove as much as possible from the left, and then from the right if (index > 3) { delta = qMin(index, numOfExtraChars); numOfExtraChars -= delta; sqtext.replace(0, delta, "..."); } if (numOfExtraChars > 0 && ((int)sqtext.length() > length + 3)) { delta = qMin(numOfExtraChars, (int)sqtext.length() - (length + 3)); sqtext.replace(sqtext.length() - delta, delta, "..."); } QLabel::setText(sqtext); setToolTip(QString()); setToolTip(fullText); } else { QLabel::setText(fullText); setToolTip(QString()); QToolTip::hideText(); } } } void KrSqueezedTextLabel::setText(const QString &text, int index, int length) { _index = index; _length = length; fullText = text; KSqueezedTextLabel::setText(fullText); squeezeTextToLabel(_index, _length); } void KrSqueezedTextLabel::paintEvent(QPaintEvent * e) { KSqueezedTextLabel::paintEvent(e); } diff --git a/krusader/Dialogs/krsqueezedtextlabel.h b/krusader/Dialogs/krsqueezedtextlabel.h index bdeba722..7cf78cb4 100644 --- a/krusader/Dialogs/krsqueezedtextlabel.h +++ b/krusader/Dialogs/krsqueezedtextlabel.h @@ -1,75 +1,76 @@ /***************************************************************************** * Copyright (C) 2002 Shie Erlich * * Copyright (C) 2002 Rafi Yanai * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef KRSQUEEZEDTEXTLABEL_H #define KRSQUEEZEDTEXTLABEL_H -#include -#include -#include -#include +// QtGui +#include +#include +#include +#include #include class QMouseEvent; class QDropEvent; class QDragEnterEvent; class QPaintEvent; /** This class overloads KSqueezedTextLabel and simply adds a clicked signal, so that users will be able to click the label and switch focus between panels. NEW: a special setText() method allows to choose which part of the string should be displayed (example: make sure that search results won't be cut out) */ class KrSqueezedTextLabel : public KSqueezedTextLabel { Q_OBJECT public: KrSqueezedTextLabel(QWidget *parent = 0); ~KrSqueezedTextLabel(); void enableDrops(bool flag); public slots: void setText(const QString &text, int index = -1, int length = -1); signals: void clicked(QMouseEvent *); /**< emitted when someone clicks on the label */ void dropped(QDropEvent *); /**< emitted when someone drops URL onto the label */ protected: void resizeEvent(QResizeEvent *) { squeezeTextToLabel(_index, _length); } virtual void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE; virtual void dropEvent(QDropEvent *e) Q_DECL_OVERRIDE; virtual void dragEnterEvent(QDragEnterEvent *e) Q_DECL_OVERRIDE; virtual void paintEvent(QPaintEvent * e) Q_DECL_OVERRIDE; void squeezeTextToLabel(int index = -1, int length = -1); QString fullText; private: bool acceptDrops; int _index, _length; }; #endif diff --git a/krusader/Dialogs/kurllistrequester.cpp b/krusader/Dialogs/kurllistrequester.cpp index 7d2fef1f..b7d61157 100644 --- a/krusader/Dialogs/kurllistrequester.cpp +++ b/krusader/Dialogs/kurllistrequester.cpp @@ -1,198 +1,200 @@ /*************************************************************************** kurllistrequester.cpp - description ------------------- copyright : (C) 2005 by Csaba Karai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "kurllistrequester.h" #include "../VFS/vfs.h" -#include -#include -#include -#include -#include -#include -#include +// QtGui +#include +#include +#include +// QtWidgets +#include +#include +#include +#include #include #include #include #define DELETE_ITEM_ID 100 KURLListRequester::KURLListRequester(Mode requestMode, QWidget *parent) : QWidget(parent), mode(requestMode) { // Creating the widget QGridLayout *urlListRequesterGrid = new QGridLayout(this); urlListRequesterGrid->setSpacing(0); urlListRequesterGrid->setContentsMargins(0, 0, 0, 0); urlLineEdit = new KLineEdit(this); urlListRequesterGrid->addWidget(urlLineEdit, 0, 0); urlListBox = new KrListWidget(this); urlListBox->setSelectionMode(QAbstractItemView::ExtendedSelection); urlListRequesterGrid->addWidget(urlListBox, 1, 0, 1, 3); urlAddBtn = new QToolButton(this); urlAddBtn->setText(""); urlAddBtn->setIcon(QIcon::fromTheme("arrow-down")); urlListRequesterGrid->addWidget(urlAddBtn, 0, 1); urlBrowseBtn = new QToolButton(this); urlBrowseBtn->setText(""); urlBrowseBtn->setIcon(QIcon::fromTheme("folder")); urlListRequesterGrid->addWidget(urlBrowseBtn, 0, 2); // add shell completion completion.setMode(KUrlCompletion::FileCompletion); urlLineEdit->setCompletionObject(&completion); // connection table connect(urlAddBtn, SIGNAL(clicked()), this, SLOT(slotAdd())); connect(urlBrowseBtn, SIGNAL(clicked()), this, SLOT(slotBrowse())); connect(urlLineEdit, SIGNAL(returnPressed(const QString&)), this, SLOT(slotAdd())); connect(urlListBox, SIGNAL(itemRightClicked(QListWidgetItem *, const QPoint &)), this, SLOT(slotRightClicked(QListWidgetItem *, const QPoint &))); connect(urlLineEdit, SIGNAL(textChanged(const QString &)), this, SIGNAL(changed())); } void KURLListRequester::slotAdd() { QString text = urlLineEdit->text().simplified(); if (text.length()) { QString error; emit checkValidity(text, error); if (!error.isNull()) KMessageBox::error(this, error); else { urlListBox->addItem(text); urlLineEdit->clear(); emit changed(); } } } void KURLListRequester::slotBrowse() { QUrl url; switch (mode) { case RequestFiles: url = QFileDialog::getOpenFileUrl(this); break; case RequestDirs: url = QFileDialog::getExistingDirectoryUrl(this); break; } if (!url.isEmpty()) urlLineEdit->setText(url.toDisplayString(QUrl::PreferLocalFile)); urlLineEdit->setFocus(); } void KURLListRequester::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Delete) { if (urlListBox->hasFocus()) { deleteSelectedItems(); return; } } QWidget::keyPressEvent(e); } void KURLListRequester::deleteSelectedItems() { QList delList = urlListBox->selectedItems(); for (int i = 0; i != delList.count(); i++) delete delList[ i ]; emit changed(); } void KURLListRequester::slotRightClicked(QListWidgetItem *item, const QPoint &pos) { if (item == 0) return; QMenu popupMenu(this); QAction * menuAction = popupMenu.addAction(i18n("Delete")); if (menuAction == popupMenu.exec(pos)) { if (item->isSelected()) deleteSelectedItems(); else { delete item; emit changed(); } } } QList KURLListRequester::urlList() { QList urls; QString text = urlLineEdit->text().simplified(); if (!text.isEmpty()) { QString error; emit checkValidity(text, error); if (error.isNull()) urls.append(QUrl::fromUserInput(text, QString(), QUrl::AssumeLocalFile)); } for (int i = 0; i != urlListBox->count(); i++) { QListWidgetItem *item = urlListBox->item(i); QString text = item->text().simplified(); QString error; emit checkValidity(text, error); if (error.isNull()) urls.append(QUrl::fromUserInput(text, QString(), QUrl::AssumeLocalFile)); } return urls; } void KURLListRequester::setUrlList(QList urlList) { urlLineEdit->clear(); urlListBox->clear(); QList::iterator it; for (it = urlList.begin(); it != urlList.end(); ++it) urlListBox->addItem(it->toDisplayString(QUrl::PreferLocalFile)); emit changed(); } diff --git a/krusader/Dialogs/kurllistrequester.h b/krusader/Dialogs/kurllistrequester.h index 748f8a49..7c5f5446 100644 --- a/krusader/Dialogs/kurllistrequester.h +++ b/krusader/Dialogs/kurllistrequester.h @@ -1,89 +1,91 @@ /*************************************************************************** kurllistrequester.h - description ------------------- copyright : (C) 2005 by Csaba Karai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD H e a d e r F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef KURLLISTREQUESTER_H #define KURLLISTREQUESTER_H -#include -#include -#include +// QtGui +#include +// QtWidgets +#include +#include #include #include #include "../GUI/krlistwidget.h" class KURLListRequester : public QWidget { Q_OBJECT public: enum Mode { RequestFiles, RequestDirs }; KURLListRequester(Mode requestMode, QWidget *parent = 0); QList urlList(); void setUrlList(QList); KLineEdit *lineEdit() { return urlLineEdit; } KrListWidget *listBox() { return urlListBox; } void setCompletionDir(const QUrl &dir) { completion.setDir(dir); } signals: void checkValidity(QString &text, QString &error); void changed(); protected slots: void slotAdd(); void slotBrowse(); void slotRightClicked(QListWidgetItem *, const QPoint &); protected: virtual void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE; void deleteSelectedItems(); Mode mode; KLineEdit *urlLineEdit; KrListWidget *urlListBox; QToolButton *urlAddBtn; QToolButton *urlBrowseBtn; KUrlCompletion completion; }; #endif /* __KURLLISTREQUESTER_H__ */ diff --git a/krusader/Dialogs/newftpgui.cpp b/krusader/Dialogs/newftpgui.cpp index 62c2a2b2..e9e40466 100644 --- a/krusader/Dialogs/newftpgui.cpp +++ b/krusader/Dialogs/newftpgui.cpp @@ -1,196 +1,199 @@ /***************************************************************************** * Copyright (C) 2002 Shie Erlich * * Copyright (C) 2002 Rafi Yanai * * Copyright (C) 2009 Fathi Boudra * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "newftpgui.h" -#include -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +#include +// QtGui +#include +// QtWidgets +#include +#include +#include +#include +#include #include #include #include #include #include #include "../krglobal.h" #define SIZE_MINIMUM QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed) /** * Constructs a newFTPGUI which is a child of 'parent', * with the name 'name' and widget flags set to 'f' */ newFTPGUI::newFTPGUI(QWidget* parent) : QDialog(parent) { setModal(true); setWindowTitle(i18n("New Network Connection")); resize(400, 240); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Preferred); policy.setHeightForWidth(sizePolicy().hasHeightForWidth()); setSizePolicy(policy); iconLabel = new QLabel(this); iconLabel->setPixmap(krLoader->loadIcon("network-wired", KIconLoader::Desktop, 32)); iconLabel->setSizePolicy(SIZE_MINIMUM); aboutLabel = new QLabel(i18n("About to connect to..."), this); QFont font(aboutLabel->font()); font.setBold(true); aboutLabel->setFont(font); protocolLabel = new QLabel(i18n("Protocol:"), this); hostLabel = new QLabel(i18n("Host:"), this); portLabel = new QLabel(i18n("Port:"), this); prefix = new KComboBox(this); prefix->setObjectName(QString::fromUtf8("protocol")); prefix->setSizePolicy(SIZE_MINIMUM); url = new KHistoryComboBox(this); url->setMaxCount(50); url->setMinimumContentsLength(10); QStringList protocols = KProtocolInfo::protocols(); if (protocols.contains("ftp")) prefix->addItem(i18n("ftp://")); if (protocols.contains("smb")) prefix->addItem(i18n("smb://")); if (protocols.contains("fish")) prefix->addItem(i18n("fish://")); if (protocols.contains("sftp")) prefix->addItem(i18n("sftp://")); // load the history and completion list after creating the history combo KConfigGroup group(krConfig, "Private"); QStringList list = group.readEntry("newFTP Completion list", QStringList()); url->completionObject()->setItems(list); list = group.readEntry("newFTP History list", QStringList()); url->setHistoryItems(list); // Select last used protocol QString lastUsedProtocol = group.readEntry("newFTP Protocol", QString()); if(!lastUsedProtocol.isEmpty()) { prefix->setCurrentItem(lastUsedProtocol); } port = new QSpinBox(this); port->setMaximum(65535); port->setValue(21); port->setSizePolicy(SIZE_MINIMUM); usernameLabel = new QLabel(i18n("Username:"), this); username = new KLineEdit(this); passwordLabel = new QLabel(i18n("Password:"), this); password = new KLineEdit(this); password->setEchoMode(QLineEdit::Password); QHBoxLayout *horizontalLayout = new QHBoxLayout(); horizontalLayout->addWidget(iconLabel); horizontalLayout->addWidget(aboutLabel); QGridLayout *gridLayout = new QGridLayout(); gridLayout->addWidget(protocolLabel, 0, 0, 1, 1); gridLayout->addWidget(hostLabel, 0, 1, 1, 1); gridLayout->addWidget(portLabel, 0, 2, 1, 1); gridLayout->addWidget(prefix, 1, 0, 1, 1); gridLayout->addWidget(url, 1, 1, 1, 1); gridLayout->addWidget(port, 1, 2, 1, 1); gridLayout->addWidget(usernameLabel, 2, 0, 1, 1); gridLayout->addWidget(username, 3, 0, 1, 3); gridLayout->addWidget(passwordLabel, 4, 0, 1, 1); gridLayout->addWidget(password, 5, 0, 1, 3); QGridLayout *widgetLayout = new QGridLayout(); widgetLayout->addLayout(horizontalLayout, 0, 0, 1, 1); widgetLayout->addLayout(gridLayout, 1, 0, 1, 1); mainLayout->addLayout(widgetLayout); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); mainLayout->addWidget(buttonBox); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setText(i18n("&Connect")); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(prefix, SIGNAL(activated(const QString &)), this, SLOT(slotTextChanged(const QString &))); connect(url, SIGNAL(activated(const QString &)), url, SLOT(addToHistory(const QString &))); if(!lastUsedProtocol.isEmpty()) { // update the port field slotTextChanged(lastUsedProtocol); } setTabOrder(url, username); setTabOrder(username, password); setTabOrder(password, prefix); } /** * Destroys the object and frees any allocated resources */ newFTPGUI::~newFTPGUI() { // no need to delete child widgets, Qt does it all for us } void newFTPGUI::slotTextChanged(const QString &string) { if (string.startsWith(QLatin1String("ftp")) || string.startsWith(QLatin1String("sftp")) || string.startsWith(QLatin1String("fish"))) { if (port->value() == 21 || port->value() == 22) { port->setValue(string.startsWith(QLatin1String("ftp")) ? 21 : 22); } port->setEnabled(true); } else { port->setEnabled(false); } } /** * Main event handler. Reimplemented to handle application font changes */ bool newFTPGUI::event(QEvent *ev) { bool ret = QDialog::event(ev); if (ev->type() == QEvent::ApplicationFontChange) { QFont font(aboutLabel->font()); font.setBold(true); aboutLabel->setFont(font); } return ret; } diff --git a/krusader/Dialogs/newftpgui.h b/krusader/Dialogs/newftpgui.h index a5a8f641..2ed921eb 100644 --- a/krusader/Dialogs/newftpgui.h +++ b/krusader/Dialogs/newftpgui.h @@ -1,64 +1,65 @@ /***************************************************************************** * Copyright (C) 2002 Shie Erlich * * Copyright (C) 2002 Rafi Yanai * * Copyright (C) 2009 Fathi Boudra * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef NEWFTPGUI_H #define NEWFTPGUI_H -#include -#include -#include +// QtWidgets +#include +#include +#include #include #include #include class QEvent; class QString; class QWidget; class newFTPGUI : public QDialog { Q_OBJECT public: newFTPGUI(QWidget *parent = 0); ~newFTPGUI(); QLabel* iconLabel; QLabel* aboutLabel; QLabel* protocolLabel; QLabel* passwordLabel; QLabel* hostLabel; QLabel* usernameLabel; QLabel* portLabel; QSpinBox* port; KComboBox* prefix; KHistoryComboBox* url; KLineEdit* username; KLineEdit* password; public slots: void slotTextChanged(const QString &); protected: bool event(QEvent *); }; #endif diff --git a/krusader/Dialogs/packgui.cpp b/krusader/Dialogs/packgui.cpp index 2e1c759e..36012980 100644 --- a/krusader/Dialogs/packgui.cpp +++ b/krusader/Dialogs/packgui.cpp @@ -1,144 +1,146 @@ /*************************************************************************** packgui.cpp ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "packgui.h" #include "../krglobal.h" #include "../defaults.h" -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtWidgets +#include +#include +#include +#include +#include +#include #include #include #include #define PS(x) lst.contains(x)>0 // clear the statics first QString PackGUI::filename = 0; QString PackGUI::destination = 0; QString PackGUI::type = 0; QMap PackGUI::extraProps; bool PackGUI::queue = false; PackGUI::PackGUI(QString defaultName, QString defaultPath, int noOfFiles, QString filename) : PackGUIBase(0) { // first, fill the WhatToPack textfield with information if (noOfFiles == 1) TextLabel1->setText(i18n("Pack %1", filename)); else TextLabel1->setText(i18np("Pack %1 file", "Pack %1 files", noOfFiles)); // now, according to the Konfigurator, fill the combobox with the information // about what kind of packing we can do KConfigGroup group(krConfig, "Archives"); QStringList lst = group.readEntry("Supported Packers", QStringList()); // now, clear the type combo and begin... typeData->clear(); if (PS("tar")) typeData->addItem("tar"); if (PS("tar") && PS("gzip")) typeData->addItem("tar.gz"); if (PS("tar") && PS("bzip2")) typeData->addItem("tar.bz2"); if (PS("tar") && PS("lzma")) typeData->addItem("tar.lzma"); if (PS("tar") && PS("xz")) typeData->addItem("tar.xz"); if (PS("zip")) typeData->addItem("zip"); if (PS("zip")) typeData->addItem("cbz"); if (PS("rar")) typeData->addItem("rar"); if (PS("rar")) typeData->addItem("cbr"); if (PS("lha")) typeData->addItem("lha"); if (PS("arj")) typeData->addItem("arj"); if (PS("7z")) typeData->addItem("7z"); // set the last used packer as the top one QString tmp = group.readEntry("lastUsedPacker", QString()); if (!tmp.isEmpty()) { for (int i = 0; i < typeData->count(); ++i) if (typeData->itemText(i) == tmp) { typeData->removeItem(i); typeData->insertItem(0, tmp); typeData->setCurrentIndex(0); break; } } checkConsistency(); queue = false; // and go on with the normal stuff dirData->setText(defaultPath); nameData->setText(defaultName); nameData->setFocus(); if (typeData->count() == 0) // if no packers are available okButton->setEnabled(false); setGeometry(krMainWindow->x() + krMainWindow->width() / 2 - width() / 2, krMainWindow->y() + krMainWindow->height() / 2 - height() / 2, width(), height()); exec(); } void PackGUI::browse() { QString temp = QFileDialog::getExistingDirectory(0, i18n("Please select a folder"), dirData->text()); if (!temp.isEmpty()) { dirData->setText(temp); } } void PackGUI::accept() { if (!extraProperties(extraProps)) return; filename = nameData->text(); destination = dirData->text(); type = typeData->currentText(); // write down the packer chosen, to be lastUsedPacker KConfigGroup group(krConfig, "Archives"); group.writeEntry("lastUsedPacker", type); krConfig->sync(); PackGUIBase::accept(); } void PackGUI::reject() { filename.clear(); destination.clear(); type.clear(); PackGUIBase::reject(); } void PackGUI::slotQueue() { queue = true; PackGUIBase::slotQueue(); } diff --git a/krusader/Dialogs/packguibase.cpp b/krusader/Dialogs/packguibase.cpp index c95231b9..e08b5855 100644 --- a/krusader/Dialogs/packguibase.cpp +++ b/krusader/Dialogs/packguibase.cpp @@ -1,520 +1,523 @@ /*************************************************************************** packguibase.cpp ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "packguibase.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtGui +#include +#include +#include +#include +// QtWidgets +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include #include #include #include #include #include "../defaults.h" #include "../krglobal.h" /* * Constructs a PackGUIBase which is a child of 'parent', with the * name 'name' and widget flags set to 'f' * * The dialog will by default be modeless, unless you set 'modal' to * TRUE to construct a modal dialog. */ PackGUIBase::PackGUIBase(QWidget* parent) : QDialog(parent), expanded(false) { KConfigGroup group(krConfig, "Archives"); setModal(true); resize(430, 140); setWindowTitle(i18n("Pack")); grid = new QGridLayout(this); grid->setSpacing(6); grid->setContentsMargins(11, 11, 11, 11); hbox = new QHBoxLayout; hbox->setSpacing(6); hbox->setContentsMargins(0, 0, 0, 0); TextLabel3 = new QLabel(this); TextLabel3->setText(i18n("To archive")); hbox->addWidget(TextLabel3); nameData = new QLineEdit(this); hbox->addWidget(nameData); typeData = new QComboBox(this); typeData->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed)); connect(typeData, SIGNAL(activated(const QString &)), this, SLOT(checkConsistency())); connect(typeData, SIGNAL(highlighted(const QString &)), this, SLOT(checkConsistency())); hbox->addWidget(typeData); grid->addLayout(hbox, 1, 0); hbox_2 = new QHBoxLayout; hbox_2->setSpacing(6); hbox_2->setContentsMargins(0, 0, 0, 0); TextLabel5 = new QLabel(this); TextLabel5->setText(i18n("In folder")); hbox_2->addWidget(TextLabel5); dirData = new QLineEdit(this); hbox_2->addWidget(dirData); browseButton = new QToolButton(this); browseButton->setIcon(SmallIcon("document-open")); hbox_2->addWidget(browseButton); QSpacerItem* spacer = new QSpacerItem(48, 20, QSizePolicy::Fixed, QSizePolicy::Fixed); hbox_2->addItem(spacer); grid->addLayout(hbox_2, 2, 0); hbox_3 = new QHBoxLayout; hbox_3->setSpacing(6); hbox_3->setContentsMargins(0, 0, 0, 0); PixmapLabel1 = new QLabel(this); PixmapLabel1->setPixmap(krLoader->loadIcon("package-x-generic", KIconLoader::Desktop, 32)); PixmapLabel1->setScaledContents(true); PixmapLabel1->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); hbox_3->addWidget(PixmapLabel1); TextLabel1 = new QLabel(this); TextLabel1->setText(i18n("Pack")); hbox_3->addWidget(TextLabel1); grid->addLayout(hbox_3, 0, 0); hbox_4 = new QHBoxLayout; hbox_4->setSpacing(6); hbox_4->setContentsMargins(0, 0, 0, 0); QSpacerItem* spacer_3 = new QSpacerItem(20, 26, QSizePolicy::Fixed, QSizePolicy::Expanding); hbox_4->addItem(spacer_3); grid->addLayout(hbox_4, 3, 0); advancedWidget = new QWidget(this); hbox_5 = new QGridLayout(advancedWidget); hbox_5->setSpacing(6); hbox_5->setContentsMargins(0, 0, 0, 0); QVBoxLayout *compressLayout = new QVBoxLayout; compressLayout->setSpacing(6); compressLayout->setContentsMargins(0, 0, 0, 0); multipleVolume = new QCheckBox(i18n("Multiple volume archive"), advancedWidget); connect(multipleVolume, SIGNAL(toggled(bool)), this, SLOT(checkConsistency())); compressLayout->addWidget(multipleVolume, 0, 0); QHBoxLayout * volumeHbox = new QHBoxLayout; QSpacerItem* spacer_5 = new QSpacerItem(20, 26, QSizePolicy::Fixed, QSizePolicy::Fixed); volumeHbox->addItem(spacer_5); TextLabel7 = new QLabel(i18n("Size:"), advancedWidget); volumeHbox->addWidget(TextLabel7); volumeSpinBox = new QSpinBox(advancedWidget); volumeSpinBox->setMinimum(1); volumeSpinBox->setMaximum(9999); volumeSpinBox->setValue(1440); volumeHbox->addWidget(volumeSpinBox); volumeUnitCombo = new QComboBox(advancedWidget); volumeUnitCombo->addItem("B"); volumeUnitCombo->addItem("KB"); volumeUnitCombo->addItem("MB"); volumeUnitCombo->setCurrentIndex(1); volumeHbox->addWidget(volumeUnitCombo); compressLayout->addLayout(volumeHbox); int level = group.readEntry("Compression level", _defaultCompressionLevel); setCompressionLevel = new QCheckBox(i18n("Set compression level"), advancedWidget); if (level != _defaultCompressionLevel) setCompressionLevel->setChecked(true); connect(setCompressionLevel, SIGNAL(toggled(bool)), this, SLOT(checkConsistency())); compressLayout->addWidget(setCompressionLevel, 0, 0); QHBoxLayout * sliderHbox = new QHBoxLayout; QSpacerItem* spacer_6 = new QSpacerItem(20, 26, QSizePolicy::Fixed, QSizePolicy::Fixed); sliderHbox->addItem(spacer_6); QWidget * sliderVBoxWidget = new QWidget(advancedWidget); QVBoxLayout *sliderVBox = new QVBoxLayout(sliderVBoxWidget); compressionSlider = new QSlider(Qt::Horizontal, sliderVBoxWidget); compressionSlider->setMinimum(1); compressionSlider->setMaximum(9); compressionSlider->setPageStep(1); compressionSlider->setValue(level); compressionSlider->setTickPosition(QSlider::TicksBelow); sliderVBox->addWidget(compressionSlider); QWidget * minmaxWidget = new QWidget(sliderVBoxWidget); sliderVBox->addWidget(minmaxWidget); QHBoxLayout * minmaxHbox = new QHBoxLayout(minmaxWidget); minLabel = new QLabel(i18n("MIN"), minmaxWidget); maxLabel = new QLabel(i18n("MAX"), minmaxWidget); maxLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); minmaxHbox->addWidget(minLabel); minmaxHbox->addWidget(maxLabel); sliderHbox->addWidget(sliderVBoxWidget); compressLayout->addLayout(sliderHbox); compressLayout->addStretch(0); hbox_5->addLayout(compressLayout, 0, 0); QFrame *vline = new QFrame(advancedWidget); vline->setFrameStyle(QFrame::VLine | QFrame::Sunken); vline->setMinimumWidth(20); hbox_5->addWidget(vline, 0, 1); QGridLayout * passwordGrid = new QGridLayout; passwordGrid->setSpacing(6); passwordGrid->setContentsMargins(0, 0, 0, 0); TextLabel4 = new QLabel(advancedWidget); TextLabel4->setText(i18n("Password")); passwordGrid->addWidget(TextLabel4, 0, 0); password = new QLineEdit(advancedWidget); password->setEchoMode(QLineEdit::Password); connect(password, SIGNAL(textChanged(const QString &)), this, SLOT(checkConsistency())); passwordGrid->addWidget(password, 0, 1); TextLabel6 = new QLabel(advancedWidget); TextLabel6->setText(i18n("Again")); passwordGrid->addWidget(TextLabel6, 1, 0); passwordAgain = new QLineEdit(advancedWidget); passwordAgain->setEchoMode(QLineEdit::Password); connect(passwordAgain, SIGNAL(textChanged(const QString &)), this, SLOT(checkConsistency())); passwordGrid->addWidget(passwordAgain, 1, 1); QHBoxLayout *consistencyHbox = new QHBoxLayout; QSpacerItem* spacer_cons = new QSpacerItem(48, 20, QSizePolicy::Expanding, QSizePolicy::Fixed); consistencyHbox->addItem(spacer_cons); passwordConsistencyLabel = new QLabel(advancedWidget); consistencyHbox->addWidget(passwordConsistencyLabel); passwordGrid->addLayout(consistencyHbox, 2, 0, 1, 2); encryptHeaders = new QCheckBox(i18n("Encrypt headers"), advancedWidget); passwordGrid->addWidget(encryptHeaders, 3, 0, 1, 2); QSpacerItem* spacer_psw = new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Expanding); passwordGrid->addItem(spacer_psw, 4, 0); hbox_5->addLayout(passwordGrid, 0, 2); hbox_7 = new QHBoxLayout; hbox_7->setSpacing(6); hbox_7->setContentsMargins(0, 0, 0, 0); TextLabel8 = new QLabel(i18n("Command line switches:"), advancedWidget); TextLabel8->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); hbox_7->addWidget(TextLabel8); commandLineSwitches = new KHistoryComboBox(advancedWidget); commandLineSwitches->setMaxCount(25); // remember 25 items commandLineSwitches->setDuplicatesEnabled(false); commandLineSwitches->setMinimumContentsLength(10); QStringList list = group.readEntry("Command Line Switches", QStringList()); commandLineSwitches->setHistoryItems(list); hbox_7->addWidget(commandLineSwitches); hbox_5->addLayout(hbox_7, 1, 0, 1, 3); advancedWidget->hide(); checkConsistency(); grid->addWidget(advancedWidget, 4, 0); hbox_6 = new QHBoxLayout; hbox_6->setSpacing(6); hbox_6->setContentsMargins(0, 0, 0, 0); advancedButton = new QPushButton(this); advancedButton->setText(i18n("&Advanced >>")); hbox_6->addWidget(advancedButton); QSpacerItem* spacer_2 = new QSpacerItem(140, 20, QSizePolicy::Expanding, QSizePolicy::Fixed); hbox_6->addItem(spacer_2); queueButton = new QPushButton(this); queueButton->setText(i18n("F2 Queue")); hbox_6->addWidget(queueButton); okButton = new QPushButton(this); okButton->setText(i18n("OK")); okButton->setDefault(true); hbox_6->addWidget(okButton); cancelButton = new QPushButton(this); cancelButton->setText(i18n("Cancel")); hbox_6->addWidget(cancelButton); grid->addLayout(hbox_6, 6, 0); // signals and slots connections connect(queueButton, SIGNAL(clicked()), this, SLOT(slotQueue())); connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); connect(advancedButton, SIGNAL(clicked()), this, SLOT(expand())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(browseButton, SIGNAL(clicked()), this, SLOT(browse())); } /* * Destroys the object and frees any allocated resources */ PackGUIBase::~PackGUIBase() { // no need to delete child widgets, Qt does it all for us } void PackGUIBase::browse() { qWarning("PackGUIBase::browse(): Not implemented yet!"); } void PackGUIBase::expand() { expanded = !expanded; advancedButton->setText(expanded ? i18n("&Advanced <<") : i18n("&Advanced >>")); if (expanded) advancedWidget->show(); else { advancedWidget->hide(); layout()->activate(); QSize minSize = minimumSize(); resize(width(), minSize.height()); } show(); } void PackGUIBase::checkConsistency() { QPalette p = QGuiApplication::palette(); QPalette pal = passwordConsistencyLabel->palette(); if (password->text().isEmpty() && passwordAgain->text().isEmpty()) { pal.setColor(passwordConsistencyLabel->foregroundRole(), p.color(QPalette::Active, QPalette::Text)); passwordConsistencyLabel->setText(i18n("No password specified")); } else if (password->text() == passwordAgain->text()) { pal.setColor(passwordConsistencyLabel->foregroundRole(), p.color(QPalette::Active, QPalette::Text)); passwordConsistencyLabel->setText(i18n("The passwords are equal")); } else { pal.setColor(passwordConsistencyLabel->foregroundRole(), Qt::red); passwordConsistencyLabel->setText(i18n("The passwords are different")); } passwordConsistencyLabel->setPalette(pal); QString packer = typeData->currentText(); bool passworded = false; if (packer == "7z" || packer == "rar" || packer == "zip" || packer == "arj") passworded = true; passwordConsistencyLabel->setEnabled(passworded); password->setEnabled(passworded); passwordAgain->setEnabled(passworded); TextLabel4->setEnabled(passworded); TextLabel6->setEnabled(passworded); encryptHeaders->setEnabled(packer == "rar"); multipleVolume->setEnabled(packer == "rar" || packer == "arj"); bool volumeEnabled = multipleVolume->isEnabled() && multipleVolume->isChecked(); volumeSpinBox->setEnabled(volumeEnabled); volumeUnitCombo->setEnabled(volumeEnabled); TextLabel7->setEnabled(volumeEnabled); /* TODO */ setCompressionLevel->setEnabled(packer == "rar" || packer == "arj" || packer == "zip" || packer == "7z"); bool sliderEnabled = setCompressionLevel->isEnabled() && setCompressionLevel->isChecked(); compressionSlider->setEnabled(sliderEnabled); minLabel->setEnabled(sliderEnabled); maxLabel->setEnabled(sliderEnabled); } bool PackGUIBase::extraProperties(QMap & inMap) { inMap.clear(); KConfigGroup group(krConfig, "Archives"); if (password->isEnabled() && passwordAgain->isEnabled()) { if (password->text() != passwordAgain->text()) { KMessageBox::error(this, i18n("Cannot pack, the passwords are different.")); return false; } if (!password->text().isEmpty()) { inMap[ "Password" ] = password->text(); if (encryptHeaders->isEnabled() && encryptHeaders->isChecked()) inMap[ "EncryptHeaders" ] = '1'; } } if (multipleVolume->isEnabled() && multipleVolume->isChecked()) { KIO::filesize_t size = volumeSpinBox->value(); switch (volumeUnitCombo->currentIndex()) { case 2: size *= 1000; case 1: size *= 1000; default: break; } if (size < 10000) { KMessageBox::error(this, i18n("Invalid volume size.")); return false; } QString sbuffer; sbuffer.sprintf("%llu", size); inMap[ "VolumeSize" ] = sbuffer; } if (setCompressionLevel->isEnabled() && setCompressionLevel->isChecked()) { inMap[ "CompressionLevel" ] = QString("%1").arg(compressionSlider->value()); int level = compressionSlider->value(); group.writeEntry("Compression level", level); } QString cmdArgs = commandLineSwitches->currentText().trimmed(); if (!cmdArgs.isEmpty()) { bool firstChar = true; QChar quote = '\0'; for (int i = 0; i < cmdArgs.length(); i++) { QChar ch(cmdArgs[ i ]); if (ch.isSpace()) continue; if (ch == quote) { quote = '\0'; continue; } if (firstChar && ch != '-') { KMessageBox::error(this, i18n("Invalid command line switch.\nA switch must start with '-'.")); return false; } firstChar = false; if (quote == '"') continue; if (quote == '\0' && (ch == '\'' || ch == '"')) quote = ch; if (ch == '\\') { if (i == cmdArgs.length() - 1) { KMessageBox::error(this, i18n("Invalid command line switch.\nBackslashes cannot be the last character.")); return false; } i++; } } if (quote != '\0') { KMessageBox::error(this, i18n("Invalid command line switch.\nUnclosed quotation mark.")); return false; } commandLineSwitches->addToHistory(cmdArgs); QStringList list = commandLineSwitches->historyItems(); group.writeEntry("Command Line Switches", list); inMap[ "CommandLineSwitches" ] = cmdArgs; } return true; } void PackGUIBase::slotQueue() { accept(); } void PackGUIBase::keyPressEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_F2: slotQueue(); return; default: QDialog::keyPressEvent(e); } } diff --git a/krusader/Dialogs/packguibase.h b/krusader/Dialogs/packguibase.h index 007c6265..80d284e9 100644 --- a/krusader/Dialogs/packguibase.h +++ b/krusader/Dialogs/packguibase.h @@ -1,117 +1,119 @@ /*************************************************************************** packguibase.h ------------------- copyright : (C) 2000 by Shie Erlich & Rafi Yanai email : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD H e a d e r F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef PACKGUIBASE_H #define PACKGUIBASE_H -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtWidgets +#include +#include +#include +#include +#include class QVBoxLayout; class QHBoxLayout; class QGridLayout; class QCheckBox; class QComboBox; class QLabel; class QLineEdit; class QPushButton; class QToolButton; class QSpinBox; class QSlider; class KHistoryComboBox; class PackGUIBase : public QDialog { Q_OBJECT public: PackGUIBase(QWidget* parent = 0); ~PackGUIBase(); QLabel* TextLabel3; QLineEdit* nameData; QComboBox* typeData; QLabel* TextLabel5; QLineEdit* dirData; QToolButton* browseButton; QWidget* advancedWidget; QLabel* PixmapLabel1; QLabel* TextLabel1; QLabel* TextLabel4; QLabel* TextLabel6; QLabel* TextLabel7; QLabel* TextLabel8; QLabel* minLabel; QLabel* maxLabel; QLineEdit* password; QLineEdit* passwordAgain; QLabel* passwordConsistencyLabel; QPushButton* queueButton; QPushButton* okButton; QPushButton* cancelButton; QPushButton* advancedButton; QCheckBox* encryptHeaders; QCheckBox* multipleVolume; QSpinBox* volumeSpinBox; QComboBox* volumeUnitCombo; QCheckBox* setCompressionLevel; QSlider* compressionSlider; KHistoryComboBox *commandLineSwitches; public slots: virtual void browse(); virtual bool extraProperties(QMap &); void expand(); void checkConsistency(); protected slots: virtual void slotQueue(); protected: virtual void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE; QHBoxLayout* hbox; QHBoxLayout* hbox_2; QHBoxLayout* hbox_3; QHBoxLayout* hbox_4; QGridLayout* hbox_5; QHBoxLayout* hbox_6; QHBoxLayout* hbox_7; QGridLayout* grid; private: bool expanded; }; #endif // PACKGUIBASE_H diff --git a/krusader/Dialogs/percentalsplitter.cpp b/krusader/Dialogs/percentalsplitter.cpp index 0b86c2f2..08d82648 100644 --- a/krusader/Dialogs/percentalsplitter.cpp +++ b/krusader/Dialogs/percentalsplitter.cpp @@ -1,90 +1,93 @@ /*************************************************************************** percentalsplitter.h - description ------------------- copyright : (C) 2006 + by Csaba Karai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD H e a d e r F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "percentalsplitter.h" -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtGui +#include +#include +// QtWidgets +#include +#include +#include +#include PercentalSplitter::PercentalSplitter(QWidget * parent) : QSplitter(parent), label(0), opaqueOldPos(-1) { connect(this, SIGNAL(splitterMoved(int, int)), SLOT(slotSplitterMoved(int, int))); } PercentalSplitter::~PercentalSplitter() { } QString PercentalSplitter::toolTipString(int p) { QList values = sizes(); if (values.count() != 0) { int sum = 0; QListIterator it(values); while (it.hasNext()) sum += it.next(); if (sum == 0) sum++; int percent = (int)(((double)p / (double)(sum)) * 10000. + 0.5); return QString("%1.%2%3").arg(percent / 100).arg((percent / 10) % 10).arg(percent % 10) + '%'; } return QString(); } void PercentalSplitter::slotSplitterMoved(int p, int index) { handle(index) -> setToolTip(toolTipString(p)); QToolTip::showText(QCursor::pos(), toolTipString(p) , this); } void PercentalSplitter::showEvent(QShowEvent * event) { QList values = sizes(); for (int i = 0; i != count(); i++) { int p = 0; for (int j = 0; j < i; j++) p += values[ j ]; handle(i) -> setToolTip(toolTipString(p)); } QSplitter::showEvent(event); } diff --git a/krusader/Dialogs/percentalsplitter.h b/krusader/Dialogs/percentalsplitter.h index 99137299..b418a0a8 100644 --- a/krusader/Dialogs/percentalsplitter.h +++ b/krusader/Dialogs/percentalsplitter.h @@ -1,59 +1,60 @@ /*************************************************************************** percentalsplitter.h - description ------------------- copyright : (C) 2006 + by Csaba Karai e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD H e a d e r F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef PERCENTALSPLITTER_H #define PERCENTALSPLITTER_H -#include -#include +// QtWidgets +#include +#include class PercentalSplitter : public QSplitter { Q_OBJECT public: PercentalSplitter(QWidget * parent = 0); virtual ~PercentalSplitter(); QString toolTipString(int p); protected: virtual void showEvent(QShowEvent * event) Q_DECL_OVERRIDE; protected slots: void slotSplitterMoved(int pos, int index); private: QLabel * label; int opaqueOldPos; QPoint labelLocation; }; #endif /* __PERCENTAL_SPLITTER__ */ diff --git a/krusader/Dialogs/popularurls.cpp b/krusader/Dialogs/popularurls.cpp index 60c7bbcd..e19c036e 100644 --- a/krusader/Dialogs/popularurls.cpp +++ b/krusader/Dialogs/popularurls.cpp @@ -1,371 +1,373 @@ /***************************************************************************** * Copyright (C) 2002 Shie Erlich * * Copyright (C) 2002 Rafi Yanai * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "popularurls.h" #include -#include -#include -#include -#include -#include -#include -#include -#include +// QtCore +#include +// QtWidgets +#include +#include +#include +#include +#include +#include +#include #include #include #include #include #include #include "../krglobal.h" #include "../krslots.h" #include "../GUI/krtreewidget.h" #define STARTING_RANK 20 #define INCREASE 2 #define DECREASE 1 PopularUrls::PopularUrls(QObject *parent) : QObject(parent), head(0), tail(0), count(0) { dlg = new PopularUrlsDlg(); } PopularUrls::~PopularUrls() { clearList(); delete dlg; } void PopularUrls::clearList() { if (head) { UrlNodeP p = head, tmp; while (p) { tmp = p; p = p->next; delete tmp; } } ranks.clear(); head = tail = 0; } void PopularUrls::save() { KConfigGroup svr(krConfig, "Private"); // prepare the string list containing urls and int list with ranks QStringList urlList; QList rankList; UrlNodeP p = head; while (p) { urlList << p->url.toDisplayString(); rankList << p->rank; p = p->next; } svr.writeEntry("PopularUrls", urlList); svr.writeEntry("PopularUrlsRank", rankList); } void PopularUrls::load() { KConfigGroup svr(krConfig, "Private"); QStringList urlList = svr.readEntry("PopularUrls", QStringList()); QList rankList = svr.readEntry("PopularUrlsRank", QList()); if (urlList.count() != rankList.count()) { KMessageBox::error(krMainWindow, i18n("The saved 'Popular URLs' are invalid. The list will be cleared.")); return; } clearList(); count = 0; // iterate through both lists and QStringList::Iterator uit; QList::Iterator rit; for (uit = urlList.begin(), rit = rankList.begin(); uit != urlList.end() && rit != rankList.end(); ++uit, ++rit) { UrlNodeP node = new UrlNode; node->url = QUrl(*uit); node->rank = *rit; appendNode(node); ranks.insert(*uit, node); } } // returns a url list with the 'max' top popular urls QList PopularUrls::getMostPopularUrls(int max) { // get at most 'max' urls QList list; UrlNodeP p = head; int tmp = 0; if (maxUrls < max) max = maxUrls; // don't give more than maxUrls while (p && tmp < max) { list << p->url; p = p->next; ++tmp; } return list; } // adds a url to the list, or increase rank of an existing url, making // sure to bump it up the list if needed void PopularUrls::addUrl(const QUrl& url) { QUrl tmpurl = url; tmpurl.setPassword(QString()); // make sure no passwords are permanently stored if (!tmpurl.path().endsWith('/')) // make a uniform trailing slash policy tmpurl.setPath(tmpurl.path() + '/'); UrlNodeP pnode; decreaseRanks(); if (!head) { // if the list is empty ... (assumes dict to be empty as well) pnode = new UrlNode; pnode->rank = STARTING_RANK; pnode->url = tmpurl; appendNode(pnode); ranks.insert(tmpurl.url(), head); } else { if (ranks.find(tmpurl.url()) == ranks.end()) { // is the added url new? if so, append it pnode = new UrlNode; pnode->rank = STARTING_RANK; pnode->url = tmpurl; appendNode(pnode); ranks.insert(tmpurl.url(), pnode); } else { pnode = ranks[ tmpurl.url()]; pnode->rank += INCREASE; } } // do we need to change location for this one? relocateIfNeeded(pnode); // too many urls? if (count > maxUrls) removeNode(tail); //dumpList(); } // checks if 'node' needs to be bumped-up the ranking list and does it if needed void PopularUrls::relocateIfNeeded(UrlNodeP node) { if (node->prev && (node->prev->rank < node->rank)) { // iterate until we find the correct place to put it UrlNodeP tmp = node->prev->prev; while (tmp) { if (tmp->rank >= node->rank) break; // found it! else tmp = tmp->prev; } // now, if tmp isn't null, we need to move node to tmp->next // else move it to become head removeNode(node); insertNode(node, tmp); } } // iterate over the list, decreasing each url's rank // this is very naive, but a 1..30 for loop is acceptable (i hope) void PopularUrls::decreaseRanks() { if (head) { UrlNodeP p = head; while (p) { if (p->rank - DECREASE >= 0) p->rank -= DECREASE; else p->rank = 0; p = p->next; } } } // removes a node from the list, but doesn't free memory! // note: this will be buggy in case the list becomes empty (which should never happen) void PopularUrls::removeNode(UrlNodeP node) { if (node->prev) { if (tail == node) tail = node->prev; node->prev->next = node->next; } if (node->next) { if (head == node) head = node->next; node->next->prev = node->prev; } --count; } void PopularUrls::insertNode(UrlNodeP node, UrlNodeP after) { if (!after) { // make node head node->next = head; node->prev = 0; head->prev = node; head = node; } else { if (tail == after) tail = node; node->prev = after; node->next = after->next; if (node->next) { after->next->prev = node; after->next = node; } } ++count; } // appends 'node' to the end of the list, collecting garbage if needed void PopularUrls::appendNode(UrlNodeP node) { if (!tail) { // creating the first element head = tail = node; node->prev = node->next = 0; } else { node->next = 0; node->prev = tail; tail->next = node; tail = node; } ++count; } void PopularUrls::dumpList() { UrlNodeP p = head; printf("====start %d====\n", count); while (p) { printf("%d : %s\n", p->rank, p->url.url().toLatin1().data()); p = p->next; } fflush(stdout); } void PopularUrls::showDialog() { QList list = getMostPopularUrls(maxUrls); dlg->run(list); if (dlg->result() == -1) return; SLOTS->refresh(list[dlg->result()]); //printf("running %s\n", list[dlg->result()].url().toLatin1());fflush(stdout); } // ===================================== PopularUrlsDlg ====================================== PopularUrlsDlg::PopularUrlsDlg(): QDialog(krMainWindow) { setWindowTitle(i18n("Popular URLs")); setWindowModality(Qt::WindowModal); QVBoxLayout *mainLayout = new QVBoxLayout; setLayout(mainLayout); QGridLayout *layout = new QGridLayout; layout->setContentsMargins(0, 0, 0, 0); // listview to contain the urls urls = new KrTreeWidget(this); urls->header()->hide(); urls->setSortingEnabled(false); urls->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); // quick search search = new KTreeWidgetSearchLine(this, urls); QLabel *lbl = new QLabel(i18n("&Search:"), this); lbl->setBuddy(search); layout->addWidget(lbl, 0, 0); layout->addWidget(search, 0, 1); layout->addWidget(urls, 1, 0, 1, 2); mainLayout->addLayout(layout); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); mainLayout->addWidget(buttonBox); setTabOrder(search, urls); setTabOrder((QWidget *)urls, buttonBox->button(QDialogButtonBox::Close)); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(urls, SIGNAL(activated(const QModelIndex &)), this, SLOT(slotItemSelected(const QModelIndex &))); connect(search, SIGNAL(hiddenChanged(QTreeWidgetItem *, bool)), this, SLOT(slotVisibilityChanged())); } void PopularUrlsDlg::slotItemSelected(const QModelIndex & ndx) { selection = ndx.row(); accept(); } void PopularUrlsDlg::slotVisibilityChanged() { // select the first visible item QList list = urls->selectedItems(); if (list.count() > 0 && !list[0]->isHidden()) return; urls->clearSelection(); urls->setCurrentItem(0); QTreeWidgetItemIterator it(urls); while (*it) { if (!(*it)->isHidden()) { (*it)->setSelected(true); urls->setCurrentItem(*it); break; } it++; } } PopularUrlsDlg::~PopularUrlsDlg() { delete search; delete urls; } void PopularUrlsDlg::run(QList list) { // populate the listview urls->clear(); QList::Iterator it; QTreeWidgetItem * lastItem = 0; for (it = list.begin(); it != list.end(); ++it) { QTreeWidgetItem *item = new QTreeWidgetItem(urls, lastItem); lastItem = item; item->setText(0, (*it).isLocalFile() ? (*it).path() : (*it).toDisplayString()); item->setIcon(0, (*it).isLocalFile() ? SmallIcon("folder") : SmallIcon("folder-html")); } setMinimumSize(urls->sizeHint().width() + 45, 400); search->clear(); search->setFocus(); selection = -1; slotVisibilityChanged(); exec(); } diff --git a/krusader/Dialogs/popularurls.h b/krusader/Dialogs/popularurls.h index 464cc9d3..94842f7a 100644 --- a/krusader/Dialogs/popularurls.h +++ b/krusader/Dialogs/popularurls.h @@ -1,107 +1,109 @@ /***************************************************************************** * Copyright (C) 2002 Shie Erlich * * Copyright (C) 2002 Rafi Yanai * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This package is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this package; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef POPULARURLS_H #define POPULARURLS_H -#include -#include -#include -#include +// QtCore +#include +#include +#include +// QtWidgets +#include // the class holds a list of most popular links in a dual data structure // * linked list, with head and tail: for fast append/prepend support // * dictionary that maps urls to list nodes: to save the need to iterate // over the list in order to find the correct node for each new url // // also, the class holds a maximum number of urls. two variables affect this: // * maxUrls - the num. of urls the user can see // * hardLimit - the actual number of urls kept. // when the number of urls reaches hardLimit, a garbage collection is done and // the bottom (hardLimit-maxUrls) entries are removed from the list typedef struct _UrlNode* UrlNodeP; typedef struct _UrlNode { UrlNodeP prev; QUrl url; int rank; UrlNodeP next; } UrlNode; class PopularUrlsDlg; class PopularUrls : public QObject { Q_OBJECT public: PopularUrls(QObject *parent = 0); ~PopularUrls(); void save(); void load(); void addUrl(const QUrl& url); QList getMostPopularUrls(int max); public slots: void showDialog(); protected: // NOTE: the following methods append/insert/remove a node to the list // but NEVER free memory or allocate memory! void appendNode(UrlNodeP node); void insertNode(UrlNodeP node, UrlNodeP after); void removeNode(UrlNodeP node); void relocateIfNeeded(UrlNodeP node); void clearList(); void dumpList(); void decreaseRanks(); private: UrlNodeP head, tail; QHash ranks; // actually holds UrlNode* int count; static const int maxUrls = 30; PopularUrlsDlg *dlg; }; class KrTreeWidget; class KTreeWidgetSearchLine; class QModelIndex; class PopularUrlsDlg: public QDialog { Q_OBJECT public: PopularUrlsDlg(); ~PopularUrlsDlg(); void run(QList list); // use this to open the dialog inline int result() const { return selection; } // returns index 0 - topmost, or -1 protected slots: void slotVisibilityChanged(); void slotItemSelected(const QModelIndex &); private: KrTreeWidget *urls; KTreeWidgetSearchLine *search; int selection; }; #endif