مقایسه کامیت‌‌ها

..

No commits in common. "master" and "wip/inheritance" have entirely different histories.

15فایلهای تغییر یافته به همراه204 افزوده شده و 689 حذف شده

4
TODO Normal file
مشاهده پرونده

@ -0,0 +1,4 @@
- Investigate memory leaks (relevant now that we have a single user mode,
so qsrun may stay open after launch)
- Provide --help
- ESC/CTRL+Q close the app. May not be expected behaviour

مشاهده پرونده

@ -13,11 +13,6 @@ EntryProvider::EntryProvider(QStringList userEntriesDirsPaths, QStringList syste
<< "%u";
}
bool EntryProvider::isSavable(const EntryConfig &config) const
{
return ! config.entryPath.isEmpty() && (config.type == EntryType::USER || config.type == EntryType::INHERIT);
}
EntryConfig EntryProvider::readFromDesktopFile(const QString &path)
{
EntryConfig result;
@ -25,22 +20,20 @@ EntryConfig EntryProvider::readFromDesktopFile(const QString &path)
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
// TODO: better exception class
throw std::runtime_error("Failed to open file");
throw new std::runtime_error("Failed to open file");
}
QTextStream stream(&file);
// There should be nothing preceding this group in the desktop entry file but possibly one or more comments.
// https://standards.freedesktop.org/desktop-entry-spec/latest/ar01s03.html#group-header
// Ignore that as there some that violate that in the wild
const QString startSection = "[Desktop Entry]";
QString line;
QString firstLine;
do
{
line = stream.readLine().trimmed();
} while(!stream.atEnd() && line != startSection);
firstLine = stream.readLine().trimmed();
} while(!stream.atEnd() && (firstLine.isEmpty() || firstLine[0] == '#'));
if(line != startSection)
if(firstLine != "[Desktop Entry]")
{
throw ConfigFormatException(".desktop file does not contain [Desktop Entry] section: " + path.toStdString());
throw ConfigFormatException(".desktop file does not start with [Desktop Entry]: " + path.toStdString());
}
while(!stream.atEnd())
@ -63,7 +56,7 @@ EntryConfig EntryProvider::readFromDesktopFile(const QString &path)
}
if(key == "icon")
{
result.iconPath = args;
result.icon = QIcon::fromTheme(args);
}
if(key == "exec")
{
@ -82,39 +75,12 @@ EntryConfig EntryProvider::readFromDesktopFile(const QString &path)
}
}
}
if(key == "nodisplay")
{
result.hidden = args == "true";
}
if(key == "terminal")
{
result.isTerminalCommand = args == "true";
}
}
result.type = EntryType::SYSTEM;
return result;
}
std::optional<EntryConfig> EntryProvider::readEntryFromPath(const QString &path)
{
QFileInfo info(path);
if(info.isFile())
{
QString suffix = info.suffix();
if(suffix == "desktop")
{
return readFromDesktopFile(path);
}
if(suffix == "qsrun")
{
return readqsrunFile(path);
}
}
return {};
}
/* qsrun's own format */
EntryConfig EntryProvider::readqsrunFile(const QString &path)
/* qsrun own's config file */
EntryConfig EntryProvider::readFromFile(const QString &path)
{
EntryConfig result;
EntryConfig inheritedConfig;
@ -122,73 +88,21 @@ EntryConfig EntryProvider::readqsrunFile(const QString &path)
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
// TODO: better exception class
throw std::runtime_error("Failed to open file");
throw new std::runtime_error("Failed to open file");
}
QHash<QString, QString> map;
QTextStream stream(&file);
while(!stream.atEnd())
{
QString line = stream.readLine();
int spacePos = line.indexOf(' ');
if(spacePos == -1)
QStringList splitted = line.split(" ");
if(splitted.length() < 2)
{
throw ConfigFormatException("misformated line in .qsrun config file " + path.toStdString());
throw new ConfigFormatException("misformated line in .qsrun config file " + path.toStdString());
}
QString key = line.mid(0, spacePos);
QString value = line.mid(spacePos + 1);
if(key == "" || value == "")
QString key = splitted[0];
if(key == "arguments")
{
throw ConfigFormatException("empty key or value in .qsrun config file " + path.toStdString());
}
map[key] = value;
}
if(map.contains("inherit"))
{
auto entry = readEntryFromPath(map["inherit"]);
if(entry)
{
result = entry.value();
result.inherit = map["inherit"];
}
else
{
throw ConfigFormatException("Error attempting to read inherited entry");
}
}
QString type = map["type"];
if(!type.isEmpty())
{
if(type == "system")
{
throw ConfigFormatException(".qsrun files cannot be designated as system entries " +
path.toStdString());
}
else if(type == "inherit")
{
result.type = EntryType::INHERIT;
}
else if(type == "user")
{
result.type = EntryType::USER;
}
else
{
throw ConfigFormatException("Invalid value for type provided in file: " + path.toStdString());
}
}
else
{
result.type = EntryType::USER;
}
if(result.type != EntryType::INHERIT)
{
if(map.contains("arguments"))
{
auto args = map["arguments"].split(' ');
auto args = splitted.mid(1);
QString merged;
for(QString &str : args)
{
@ -217,21 +131,38 @@ EntryConfig EntryProvider::readqsrunFile(const QString &path)
throw ConfigFormatException("non-closed \" in config file " + path.toStdString());
}
}
auto assignIfSourceNotEmpty = [](QString source, QString &val) {
if(!source.isEmpty())
{
val = source;
}
};
assignIfSourceNotEmpty(map["key"].toLower(), result.key);
assignIfSourceNotEmpty(map["command"], result.command);
assignIfSourceNotEmpty(map["icon"], result.iconPath);
assignIfSourceNotEmpty(map["name"], result.name);
if(key == "name")
{
result.name = splitted[1];
}
if(key == "icon")
{
result.icon = QIcon(splitted[1]);
}
if(key == "row")
{
result.row = splitted[1].toInt();
}
if(key == "col")
{
result.col = splitted[1].toInt();
}
if(key == "command")
{
result.command = splitted[1];
}
if(key == "key")
{
// QKeySequence sequence(splitted[1]);
// result.keySequence = sequence;
result.key = splitted[1].toLower();
}
if(key == "inherit")
{
inheritedConfig = readFromDesktopFile(resolveEntryPath(splitted[1]));
}
}
result.col = map["col"].toInt();
result.row = map["row"].toInt();
result.isTerminalCommand = map["terminal"] == "true";
return result;
return result.update(inheritedConfig);
}
QString EntryProvider::resolveEntryPath(QString path)
@ -266,13 +197,17 @@ QVector<EntryConfig> EntryProvider::readConfig(QStringList paths)
while(it.hasNext())
{
QString path = it.next();
std::optional<EntryConfig> entry = readEntryFromPath(path);
if(entry)
QFileInfo info(path);
if(info.isFile())
{
if(!entry->hidden)
QString suffix = info.suffix();
if(suffix == "desktop")
{
entry->entryPath = path;
result.append(*entry);
result.append(readFromDesktopFile(path));
}
if(suffix == "qsrun")
{
result.append(readFromFile(path));
}
}
}
@ -290,73 +225,6 @@ QVector<EntryConfig> EntryProvider::getSystemEntries()
return readConfig(this->systemEntriesDirsPaths);
}
void EntryProvider::saveUserEntry(const EntryConfig &config)
{
if(!isSavable(config))
{
throw std::runtime_error("Only user/inherited entries can be saved");
}
QString transitPath = config.entryPath + ".transit";
QFile file{transitPath};
if(!file.open(QIODevice::WriteOnly))
{
throw std::runtime_error("Error: Can not open file for writing");
}
QTextStream outStream(&file);
outStream << "type" << " " << ((config.type == EntryType::USER) ? "user" : "inherit") << Qt::endl;
if(!config.inherit.isEmpty())
{
outStream << "inherit" << " " << config.inherit << Qt::endl;
}
outStream << "row" << " " << config.row << Qt::endl;
outStream << "col" << " " << config.col << Qt::endl;
outStream << "hidden" << " " << config.hidden << Qt::endl;
if(!config.key.isEmpty())
{
outStream << "key" << " " << config.key << Qt::endl;
}
if(config.type == EntryType::USER)
{
if(!config.name.isEmpty())
{
outStream << "name" << " " << config.name << Qt::endl;
}
if(!config.command.isEmpty())
{
outStream << "command" << " " << config.command << Qt::endl;
}
if(!config.iconPath.isEmpty())
{
outStream << "icon" << " " << config.iconPath << Qt::endl;
}
if(!config.arguments.empty())
{
outStream << "arguments" << " " << config.arguments.join(' ') << Qt::endl;
}
}
outStream.flush();
file.close();
// Qts don't work if file already exists and c++17... don't want to pull in the fs lib yet
int ret = rename(transitPath.toStdString().c_str(), config.entryPath.toStdString().c_str());
if(ret != 0)
{
qDebug() << strerror(errno);
throw std::runtime_error("Failed to save entry file: Error during rename");
}
}
bool EntryProvider::deleteUserEntry(const EntryConfig &config)
{
if(!isSavable(config))
{
throw std::runtime_error("Only user/inherited entries can be deleted");
}
QFile file{config.entryPath};
return file.remove();
}
template <class T> void assignIfDestDefault(T &dest, const T &source)
{
if(dest == T())
@ -370,16 +238,12 @@ EntryConfig &EntryConfig::update(const EntryConfig &o)
assignIfDestDefault(this->arguments, o.arguments);
assignIfDestDefault(this->col, o.col);
assignIfDestDefault(this->command, o.command);
if(this->iconPath.isEmpty())
if(this->icon.isNull())
{
this->iconPath = o.iconPath;
this->icon = o.icon;
}
assignIfDestDefault(this->key, o.key);
assignIfDestDefault(this->name, o.name);
assignIfDestDefault(this->row, o.row);
assignIfDestDefault(this->hidden, o.hidden);
assignIfDestDefault(this->inherit, o.inherit);
assignIfDestDefault(this->entryPath, o.entryPath);
assignIfDestDefault(this->type, o.type);
return *this;
}

مشاهده پرونده

@ -2,7 +2,6 @@
#define ENTRYPROVIDER_H
#include <QIcon>
#include <QSettings>
#include <optional>
class ConfigFormatException : public std::runtime_error
{
@ -15,27 +14,14 @@ class ConfigFormatException : public std::runtime_error
}
};
enum EntryType
{
USER,
INHERIT,
SYSTEM,
DYNAMIC
};
class EntryConfig
{
public:
EntryType type = SYSTEM;
bool hidden = false;
bool isTerminalCommand = false;
QString entryPath;
QString key;
QString name;
QString command;
QString iconPath;
QStringList arguments;
QString inherit;
QIcon icon;
int row = 0;
int col = 0;
@ -48,19 +34,15 @@ class EntryProvider
QStringList _desktopIgnoreArgs;
QStringList userEntriesDirsPaths;
QStringList systemEntriesDirsPaths;
EntryConfig readqsrunFile(const QString &path);
EntryConfig readFromFile(const QString &path);
EntryConfig readFromDesktopFile(const QString &path);
std::optional<EntryConfig> readEntryFromPath(const QString &path);
QVector<EntryConfig> readConfig(QStringList paths);
QString resolveEntryPath(QString path);
public:
EntryProvider(QStringList userEntriesDirsPaths, QStringList systemEntriesDirsPaths);
bool isSavable(const EntryConfig &config) const;
QVector<EntryConfig> getUserEntries();
QVector<EntryConfig> getSystemEntries();
void saveUserEntry(const EntryConfig &config);
bool deleteUserEntry(const EntryConfig &config);
};
#endif // ENTRYPROVIDER_H

مشاهده پرونده

@ -13,56 +13,39 @@
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <QDrag>
#include <QMimeData>
#include <QApplication>
#include "entrypushbutton.h"
EntryPushButton::EntryPushButton(const EntryConfig &config) : QPushButton()
{
this->setText(config.name);
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QIcon icon;
if(config.isTerminalCommand && config.iconPath.isEmpty())
this->setIcon(config.icon);
if(!config.icon.availableSizes().isEmpty())
{
icon = resolveIcon("utilities-terminal");
auto sizes = config.icon.availableSizes();
QSize maxSize = sizes.first();
for(QSize &current : sizes)
{
if(current.width() > maxSize.width())
{
maxSize = current;
}
}
this->setIconSize(maxSize);
}
else
{
icon = resolveIcon(config.iconPath);
}
this->setIcon(icon);
this->setIconSize(QSize{256, 256});
this->config = config;
connect(this, SIGNAL(clicked()), this, SLOT(emitOwnClicked()));
systemEntryMenu.addAction("Add to favorites", [&] { emit addToFavourites(this->config); });
userEntryMenu.addAction("Delete", [&] { emit deleteRequested(this->config); });
}
QIcon EntryPushButton::resolveIcon(QString path)
{
if(!path.isEmpty())
{
if(path[0] == '/')
{
return QIcon(path);
}
else
{
return QIcon::fromTheme(path);
}
}
return QIcon();
}
void EntryPushButton::emitOwnClicked()
{
emit clicked(this->config);
}
const EntryConfig &EntryPushButton::getEntryConfig() const
const EntryConfig &EntryPushButton::getEntryConfig()
{
return this->config;
}
@ -82,82 +65,12 @@ void EntryPushButton::showName()
this->setText(this->config.name);
}
void EntryPushButton::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
dragStartPosition = event->pos();
}
if(event->button() == Qt::RightButton)
{
if(this->config.type == EntryType::USER || this->config.type == EntryType::INHERIT)
{
this->userEntryMenu.exec(QCursor::pos());
}
else if(this->config.type == EntryType::SYSTEM)
{
this->systemEntryMenu.exec(QCursor::pos());
}
}
return QPushButton::mousePressEvent(event);
}
void EntryPushButton::mouseMoveEvent(QMouseEvent *event)
{
if(this->config.type == EntryType::SYSTEM || this->config.type == EntryType::DYNAMIC)
{
return;
}
if(!(event->buttons() & Qt::LeftButton))
{
return;
}
if((event->pos() - dragStartPosition).manhattanLength() < QApplication::startDragDistance())
{
return;
}
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData();
QByteArray data;
mimeData->setData(ENTRYBUTTON_MIME_TYPE_STR, data);
drag->setMimeData(mimeData);
Qt::DropAction dropAction = drag->exec(Qt::MoveAction);
}
int EntryPushButton::getRow() const
{
return config.row;
}
int EntryPushButton::getCol() const
{
return config.col;
}
QString EntryPushButton::getName() const
{
return config.name;
}
QString EntryPushButton::getShortcutKey() const
{
return config.key;
}
void EntryPushButton::setShortcutKey(QString key)
{
this->config.key = key;
}
void EntryPushButton::setRow(int row)
{
this->config.row = row;
}
void EntryPushButton::setCol(int col)
{
this->config.col = col;
}
QStringList EntryPushButton::getArguments() const
{
return this->config.arguments;
}
QString EntryPushButton::getCommand() const
{
return this->config.command;
}
int EntryPushButton::getRow() const { return config.row; }
int EntryPushButton::getCol() const { return config.col; }
QString EntryPushButton::getName() const { return config.name; }
QString EntryPushButton::getShortcutKey() const { return config.key; }
void EntryPushButton::setShortcutKey(QString key) { this->config.key = key; }
void EntryPushButton::setRow(int row) { this->config.row = row; }
void EntryPushButton::setCol(int col) { this->config.col = col; }
QStringList EntryPushButton::getArguments() const { return this->config.arguments; }
QString EntryPushButton::getCommand() const { return this->config.command; }

مشاهده پرونده

@ -18,38 +18,20 @@
#include <QWidget>
#include <QPushButton>
#include <QMouseEvent>
#include <QMenu>
#include "entryprovider.h"
#define ENTRYBUTTON_MIME_TYPE_STR "application/x-qsrun-entrypushbutton"
class EntryPushButton : public QPushButton
{
Q_OBJECT
private:
QMenu systemEntryMenu;
QMenu userEntryMenu;
private:
EntryConfig config;
QPoint dragStartPosition;
private slots:
private slots:
void emitOwnClicked();
signals:
signals:
void clicked(const EntryConfig &config);
void deleteRequested(EntryConfig &config);
void addToFavourites(const EntryConfig &config);
protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
QIcon resolveIcon(QString path);
public:
public:
EntryPushButton(const EntryConfig &config);
const EntryConfig &getEntryConfig() const;
const EntryConfig &getEntryConfig();
void setEntryConfig(const EntryConfig &config);
void showShortcut();
void showName();
@ -64,4 +46,6 @@ class EntryPushButton : public QPushButton
void setShortcutKey(QString key);
};
#endif // ENTRYPUSHBUTTON_H

مشاهده پرونده

@ -14,7 +14,6 @@
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <QApplication>
#include <QCommandLineParser>
#include <QFuture>
#include <QFutureWatcher>
#include <QtConcurrent/QtConcurrentRun>
@ -31,76 +30,56 @@ int main(int argc, char *argv[])
QApplication app(argc, argv);
QString configDirectoryPath;
QDir dir;
bool newInstanceRequested = false;
if(argc >= 2)
{
QCommandLineParser parser;
parser.addOptions({
{"new-instance", "Launch a new instance, ignoring any running ones"},
{"config", "Use supplied config dir instead of default"},
});
parser.addHelpOption();
parser.process(app.arguments());
configDirectoryPath = parser.value("config");
newInstanceRequested = parser.isSet("new-instance");
if(!configDirectoryPath.isEmpty() && !dir.exists(configDirectoryPath))
configDirectoryPath = QCoreApplication::arguments().at(1);
if(!dir.exists(configDirectoryPath))
{
QMessageBox::warning(nullptr, "Directory not found", configDirectoryPath + " was not found");
return 1;
}
}
if(configDirectoryPath.isEmpty())
else
{
configDirectoryPath = QDir::homePath() + "/.config/qsrun/";
}
qRegisterMetaType<QVector<QString> >("QVector<QString>");
qRegisterMetaType<QVector<QString>>("QVector<QString>");
if(!dir.exists(configDirectoryPath))
{
if(!dir.mkdir(configDirectoryPath))
{
QMessageBox::warning(nullptr, "Failed to create dir",
configDirectoryPath + " was not found and could not be created!");
QMessageBox::warning(nullptr, "Failed to create dir", configDirectoryPath + " was not found and could not be created!");
return 1;
}
}
QSettings settings(configDirectoryPath + "qsrun.config", QSettings::NativeFormat);
SettingsProvider settingsProvider{settings};
SettingsProvider settingsProvider { settings };
EntryProvider entryProvider(settingsProvider.userEntriesPaths(), settingsProvider.systemApplicationsEntriesPaths());
SingleInstanceServer *server = nullptr;
bool singleInstanceMode = !newInstanceRequested && settingsProvider.singleInstanceMode();
if(singleInstanceMode)
//TODO if setting single instance mode
QLocalSocket localSocket;
localSocket.connectToServer("/tmp/qsrun.socket");
SingleInstanceServer server;
if(localSocket.isOpen() && localSocket.isWritable())
{
QLocalSocket localSocket;
localSocket.connectToServer(settingsProvider.socketPath());
if(localSocket.isOpen() && localSocket.isWritable())
{
QDataStream stream(&localSocket);
stream << (int)0x01; // maximize
localSocket.flush();
localSocket.waitForBytesWritten();
localSocket.disconnectFromServer();
return 0;
}
server = new SingleInstanceServer();
if(!server->listen(settingsProvider.socketPath()))
QDataStream stream(&localSocket);
stream << (int)0x01; //maximize
localSocket.flush();
localSocket.waitForBytesWritten();
localSocket.disconnectFromServer();
return 0;
}
else
{
if(!server.listen("/tmp/qsrun.socket"))
{
qDebug() << "Failed to listen on socket!";
return 1;
}
}
Window *w = new Window{entryProvider, settingsProvider};
if(singleInstanceMode && server != nullptr)
{
QObject::connect(server, &SingleInstanceServer::receivedMaximizationRequest, [&w] {
Window *w = new Window { entryProvider, settingsProvider };
QObject::connect(&server, &SingleInstanceServer::receivedMaximizationRequest, [&w]{
if(w != nullptr)
{
qInfo() << "maximizing as requested by other instance";
@ -110,10 +89,12 @@ int main(int argc, char *argv[])
w->focusInput();
}
});
w->showMaximized();
w->focusInput();
}
w->showMaximized();
w->focusInput();
return app.exec();
}

مشاهده پرونده

@ -23,5 +23,5 @@ SOURCES += calculationengine.cpp \
QT += widgets sql network
QT_CONFIG -= no-pkg-config
LIBS += -lcln
CONFIG += link_pkgconfig c++17
CONFIG += link_pkgconfig
PKGCONFIG += libqalculate

دودویی (BIN)
screenshots/calc.png

فایل باینری نشان داده نشده است.

قبل از

عرض:  |  ارتفاع:  |  اندازه: 31 KiB

فایل باینری نشان داده نشده است.

قبل از

عرض:  |  ارتفاع:  |  اندازه: 48 KiB

دودویی (BIN)
screenshots/startview.jpg Normal file

فایل باینری نشان داده نشده است.

پس از

عرض:  |  ارتفاع:  |  اندازه: 112 KiB

دودویی (BIN)
screenshots/startview.png

فایل باینری نشان داده نشده است.

قبل از

عرض:  |  ارتفاع:  |  اندازه: 205 KiB

مشاهده پرونده

@ -1,6 +1,6 @@
#include "settingsprovider.h"
#include <QDir>
#include <QFileInfo>
#include <QDir>
SettingsProvider::SettingsProvider(QSettings &settings)
{
@ -9,9 +9,9 @@ SettingsProvider::SettingsProvider(QSettings &settings)
QStringList SettingsProvider::userEntriesPaths() const
{
// TODO: make it configurable, but we stick with this for now.
//TODO: make it configurable, but we stick with this for now.
QFileInfo fi(this->settings->fileName());
return {fi.absoluteDir().absolutePath()};
return { fi.absoluteDir().absolutePath() };
}
QStringList SettingsProvider::systemApplicationsEntriesPaths() const
@ -19,22 +19,9 @@ QStringList SettingsProvider::systemApplicationsEntriesPaths() const
return settings->value("sysAppsPaths", "/usr/share/applications/").toStringList();
}
int SettingsProvider::getMaxCols() const
{
return settings->value("maxColumns", 3).toInt();
}
bool SettingsProvider::singleInstanceMode() const
{
return settings->value("singleInstance", true).toBool();
}
QString SettingsProvider::getTerminalCommand() const
{
return settings->value("terminal", "/usr/bin/x-terminal-emulator -e %c").toString();
}
QString SettingsProvider::socketPath() const
{
return settings->value("singleInstanceSocket", "/tmp/qsrun").toString();
}

مشاهده پرونده

@ -1,22 +1,18 @@
#ifndef SETTINGSPROVIDER_H
#define SETTINGSPROVIDER_H
#include <QSettings>
#include <stdexcept>
#include <QSettings>
class SettingsProvider
{
private:
private:
QSettings *settings;
public:
public:
SettingsProvider(QSettings &settings);
virtual QStringList userEntriesPaths() const;
virtual QStringList systemApplicationsEntriesPaths() const;
virtual int getMaxCols() const;
virtual bool singleInstanceMode() const;
QString getTerminalCommand() const;
QString socketPath() const;
};
#endif // SETTINGSPROVIDER_H

مشاهده پرونده

@ -1,35 +1,34 @@
/*
* Copyright (c) 2018-2020 Albert S. <mail at quitesimple dot org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <QClipboard>
#include <QDate>
#include <QDebug>
#include <QDesktopServices>
* Copyright (c) 2018-2019 Albert S. <mail at quitesimple dot org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <QProcess>
#include <QProcessEnvironment>
#include <QDirIterator>
#include <QFileIconProvider>
#include <QHeaderView>
#include <QIcon>
#include <QKeySequence>
#include <QLabel>
#include <QDate>
#include <QHeaderView>
#include <QDesktopServices>
#include <QFileIconProvider>
#include <QDebug>
#include <QMenu>
#include <QProcess>
#include <QProcessEnvironment>
#include <QClipboard>
#include <QScrollArea>
#include "entryprovider.h"
#include "window.h"
#include "entryprovider.h"
Window::Window(EntryProvider &entryProvider, SettingsProvider &configProvider)
{
this->entryProvider = &entryProvider;
@ -37,7 +36,6 @@ Window::Window(EntryProvider &entryProvider, SettingsProvider &configProvider)
createGui();
initFromConfig();
this->lineEdit->installEventFilter(this);
this->setAcceptDrops(true);
QFont font;
font.setPointSize(48);
font.setBold(true);
@ -45,12 +43,13 @@ Window::Window(EntryProvider &entryProvider, SettingsProvider &configProvider)
calculationResultLabel.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
calculationResultLabel.setAlignment(Qt::AlignCenter);
calculationResultLabel.setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
connect(&calculationResultLabel, &QLabel::customContextMenuRequested, this,
&Window::showCalculationResultContextMenu);
connect(&calculationResultLabel, &QLabel::customContextMenuRequested, this, &Window::showCalculationResultContextMenu);
}
Window::~Window()
{
}
void Window::initFromConfig()
@ -78,9 +77,9 @@ void Window::showCalculationResultContextMenu(const QPoint &point)
menu.exec(QCursor::pos());
}
QVector<EntryPushButton *> Window::generateEntryButtons(const QVector<EntryConfig> &configs)
QVector<EntryPushButton*> Window::generateEntryButtons(const QVector<EntryConfig> &configs)
{
QVector<EntryPushButton *> result;
QVector<EntryPushButton*> result;
for(const EntryConfig &config : configs)
{
EntryPushButton *button = createEntryButton(config);
@ -118,65 +117,12 @@ void Window::populateGrid(const QVector<EntryPushButton *> &list)
}
}
void Window::executeConfig(const EntryConfig &config)
void Window::buttonClick(const EntryPushButton &config)
{
if(config.isTerminalCommand || QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier))
{
QString cmd = settingsProvider->getTerminalCommand();
cmd.replace("%c", config.command);
QStringList args = QProcess::splitCommand(cmd);
QProcess::startDetached(args[0], args);
}
else
{
QProcess::startDetached(config.command, config.arguments);
}
QProcess::startDetached(config.getCommand(), config.getArguments());
this->closeWindow();
}
void Window::addToFavourites(const EntryConfig &config)
{
std::pair<int, int> cell = getNextFreeCell();
EntryConfig userConfig;
userConfig.type = EntryType::INHERIT;
userConfig.row = cell.first;
userConfig.col = cell.second;
userConfig.inherit = config.entryPath;
QFileInfo fi{config.entryPath};
QString entryName = fi.completeBaseName() + ".qsrun";
QString entryPath;
if(config.type == EntryType::SYSTEM)
{
entryPath = this->settingsProvider->userEntriesPaths()[0] + "/" + entryName;
}
else
{
entryPath = fi.absoluteDir().absoluteFilePath(entryName);
}
userConfig.entryPath = entryPath;
try
{
entryProvider->saveUserEntry(userConfig);
}
catch(std::exception &e)
{
QMessageBox::critical(this, "Failed to save item to favourites", e.what());
return;
}
/*we only want to save a minimal, inherited config. but it should be a "complete" button
when we add it to the favourites. the alternative would be to reload the whole config,
but that's probably overkill. */
userConfig.update(config);
userConfig.key = "";
userEntryButtons.append(createEntryButton(userConfig));
}
void Window::deleteEntry(EntryConfig &config)
{
this->entryProvider->deleteUserEntry(config);
initFromConfig();
}
void Window::closeWindow()
{
if(settingsProvider->singleInstanceMode())
@ -190,48 +136,6 @@ void Window::closeWindow()
}
}
std::pair<int, int> Window::getNextFreeCell()
{
/* Not the most efficient way perhaps but for now it'll do */
std::sort(userEntryButtons.begin(), userEntryButtons.end(), [](EntryPushButton *a, EntryPushButton *b) {
const EntryConfig &config_a = a->getEntryConfig();
const EntryConfig &config_b = b->getEntryConfig();
if(config_a.row < config_b.row)
{
return true;
}
if(config_a.row > config_b.row)
{
return false;
}
return config_a.col < config_b.col;
});
int expectedRow = 1;
int expectedCol = 1;
int maxCols = this->settingsProvider->getMaxCols();
for(EntryPushButton *current : userEntryButtons)
{
int currentRow = current->getEntryConfig().row;
int currentCol = current->getEntryConfig().col;
if(currentRow != expectedRow || currentCol != expectedCol)
{
return {expectedRow, expectedCol};
}
if(expectedCol == maxCols)
{
expectedCol = 1;
++expectedRow;
}
else
{
++expectedCol;
}
}
return {expectedRow, expectedCol};
}
QStringList Window::generatePATHSuggestions(const QString &text)
{
QStringList results;
@ -263,11 +167,10 @@ void Window::addPATHSuggestion(const QString &text)
{
EntryConfig e;
e.name = suggestions[0];
e.col = 0;
e.row = 0;
e.col=0;
e.row=0;
e.command = suggestions[0];
e.iconPath = suggestions[0];
e.type = EntryType::DYNAMIC;
e.icon = QIcon::fromTheme(suggestions[0]);
EntryPushButton *button = createEntryButton(e);
clearGrid();
grid->addWidget(button, 0, 0);
@ -295,6 +198,7 @@ void Window::addCalcResult(const QString &expression)
calculationResultLabel.setText(labelText);
calculationResultLabel.setVisible(true);
QFont currentFont = calculationResultLabel.font();
int calculatedPointSize = currentFont.pointSize();
QFontMetrics fm(currentFont);
@ -317,7 +221,7 @@ void Window::addCalcResult(const QString &expression)
grid->addWidget(&calculationResultLabel, 0, 0);
}
// main problem here there is no easy event compression (clearing emit queue and only processing the last one)
//main problem here there is no easy event compression (clearing emit queue and only processing the last one)
void Window::lineEditTextChanged(QString text)
{
if(text.length() >= 2)
@ -344,8 +248,7 @@ void Window::lineEditTextChanged(QString text)
e.arguments = arguments.mid(1);
}
e.command = arguments[0];
e.iconPath = "utilities-terminal";
e.type = EntryType::DYNAMIC;
e.icon = QIcon::fromTheme("utilities-terminal");
EntryPushButton *button = createEntryButton(e);
clearGrid();
@ -365,11 +268,11 @@ void Window::keyReleaseEvent(QKeyEvent *event)
}
}
QWidget::keyReleaseEvent(event);
}
void Window::keyPressEvent(QKeyEvent *event)
{
bool closeWindow =
((event->modifiers() & Qt::ControlModifier && event->key() == Qt::Key_Q) || event->key() == Qt::Key_Escape);
bool closeWindow = ((event->modifiers() & Qt::ControlModifier && event->key() == Qt::Key_Q) || event->key() == Qt::Key_Escape);
if(closeWindow)
{
this->closeWindow();
@ -385,46 +288,21 @@ void Window::keyPressEvent(QKeyEvent *event)
for(EntryPushButton *button : buttonsInGrid)
{
if(!button->getEntryConfig().key.isEmpty())
{
button->showShortcut();
}
button->showShortcut();
}
QKeySequence seq(event->key());
QString key = seq.toString().toLower();
auto it = std::find_if(buttonsInGrid.begin(), buttonsInGrid.end(),
[&key](const EntryPushButton *y) { return y->getShortcutKey() == key; });
auto it = std::find_if(buttonsInGrid.begin(), buttonsInGrid.end(), [&key](const EntryPushButton *y) { return y->getShortcutKey() == key; });
if(it != buttonsInGrid.end())
{
executeConfig((*it)->getEntryConfig());
buttonClick(**it);
}
}
QWidget::keyPressEvent(event);
}
int Window::rankConfig(const EntryConfig &config, QString filter) const
{
if(config.name.startsWith(filter, Qt::CaseInsensitive))
{
return 0;
}
else if(config.command.startsWith(filter, Qt::CaseInsensitive))
{
return 1;
}
else if(config.name.contains(filter, Qt::CaseInsensitive))
{
return 2;
}
else if(config.command.contains(filter, Qt::CaseInsensitive))
{
return 3;
}
return -1;
}
void Window::filterGridFor(QString filter)
{
if(filter.length() > 0)
@ -433,8 +311,7 @@ void Window::filterGridFor(QString filter)
bool userEntryMatch = false;
for(EntryPushButton *button : this->userEntryButtons)
{
if(button->getName().contains(filter, Qt::CaseInsensitive) ||
button->getCommand().contains(filter, Qt::CaseInsensitive))
if(button->getName().contains(filter, Qt::CaseInsensitive))
{
button->setVisible(true);
grid->addWidget(button, button->getRow(), button->getCol());
@ -444,54 +321,43 @@ void Window::filterGridFor(QString filter)
}
if(!userEntryMatch)
{
QVector<RankedButton> rankedEntries;
int currow = 0;
int curcol = 0;
int i = 1;
const int MAX_COLS = this->settingsProvider->getMaxCols();
for(EntryPushButton *button : this->systemEntryButtons)
{
int ranking = rankConfig(button->getEntryConfig(), filter);
if(ranking > -1)
if(button->getName().contains(filter, Qt::CaseInsensitive))
{
RankedButton rb;
rb.button = button;
rb.ranking = ranking;
rankedEntries.append(rb);
}
}
std::sort(rankedEntries.begin(), rankedEntries.end(),
[](const RankedButton &a, const RankedButton &b) -> bool { return a.ranking < b.ranking; });
for(RankedButton &rankedButton : rankedEntries)
{
EntryPushButton *button = rankedButton.button;
button->setVisible(true);
if(i < 10)
{
button->setShortcutKey(QString::number(i++));
}
grid->addWidget(button, currow, curcol++);
this->buttonsInGrid.append(button);
if(curcol == MAX_COLS)
{
curcol = 0;
++currow;
button->setVisible(true);
if(i < 10)
{
button->setShortcutKey(QString::number(i++));
}
grid->addWidget(button, currow, curcol++);
this->buttonsInGrid.append(button);
if(curcol == 3)
{
curcol = 0;
++currow;
}
}
}
}
}
else
{
populateGrid(this->userEntryButtons);
}
}
EntryPushButton *Window::createEntryButton(const EntryConfig &entry)
EntryPushButton * Window::createEntryButton(const EntryConfig &entry)
{
EntryPushButton *button = new EntryPushButton(entry);
connect(button, &EntryPushButton::clicked, this, &Window::executeConfig);
connect(button, &EntryPushButton::addToFavourites, this, &Window::addToFavourites);
connect(button, &EntryPushButton::deleteRequested, this, &Window::deleteEntry);
connect(button, &EntryPushButton::clicked, this, &Window::buttonClick);
return button;
}
@ -504,9 +370,10 @@ void Window::lineEditReturnPressed()
return;
}
if(buttonsInGrid.length() > 0 && this->lineEdit->text().length() > 0)
if(buttonsInGrid.length() > 0 && this->lineEdit->text().length() > 0 )
{
executeConfig(buttonsInGrid[0]->getEntryConfig());
buttonClick(*buttonsInGrid[0]);
return;
}
}
@ -520,7 +387,7 @@ bool Window::eventFilter(QObject *obj, QEvent *event)
{
if(obj == this->lineEdit)
{
if(event->type() == QEvent::KeyPress)
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == Qt::Key_Tab)
@ -529,11 +396,12 @@ bool Window::eventFilter(QObject *obj, QEvent *event)
if(suggestions.length() == 1)
{
this->lineEdit->setText(suggestions[0] + " ");
this->lineEdit->setCursorPosition(this->lineEdit->text().length() + 1);
this->lineEdit->setCursorPosition(this->lineEdit->text().length()+1);
}
return true;
}
}
}
return QObject::eventFilter(obj, event);
}
@ -542,49 +410,3 @@ void Window::focusInput()
{
this->lineEdit->setFocus();
}
void Window::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasFormat(ENTRYBUTTON_MIME_TYPE_STR))
{
event->acceptProposedAction();
}
}
void Window::dropEvent(QDropEvent *event)
{
int count = grid->count();
for(int i = 0; i < count; i++)
{
QLayoutItem *current = grid->itemAt(i);
if(current->geometry().contains(event->pos()))
{
EntryPushButton *buttonAtDrop = (EntryPushButton *)current->widget();
EntryPushButton *buttonAtSource = (EntryPushButton *)event->source();
int tmp_row = buttonAtSource->getRow();
int tmp_col = buttonAtSource->getCol();
grid->addWidget(buttonAtSource, buttonAtDrop->getRow(), buttonAtDrop->getCol());
buttonAtSource->setRow(buttonAtDrop->getRow());
buttonAtSource->setCol(buttonAtDrop->getCol());
grid->addWidget(buttonAtDrop, tmp_row, tmp_col);
buttonAtDrop->setRow(tmp_row);
buttonAtDrop->setCol(tmp_col);
try
{
this->entryProvider->saveUserEntry(buttonAtDrop->getEntryConfig());
this->entryProvider->saveUserEntry(buttonAtSource->getEntryConfig());
}
catch(std::exception &e)
{
QMessageBox::critical(this, "Failed to rearrange items", e.what());
}
break;
}
}
event->acceptProposedAction();
}

مشاهده پرونده

@ -30,34 +30,20 @@
#include <QThread>
#include <QTreeWidget>
#include <QLabel>
#include <QMimeData>
#include <QDebug>
#include <QRect>
#include "entrypushbutton.h"
#include "calculationengine.h"
#include "settingsprovider.h"
class RankedButton
{
public:
EntryPushButton *button = nullptr;
int ranking;
};
class Window : public QWidget
{
Q_OBJECT
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
private:
private:
EntryProvider *entryProvider;
SettingsProvider *settingsProvider;
CalculationEngine calcEngine;
QString calculationresult;
QVector<EntryPushButton *> userEntryButtons;
QVector<EntryPushButton *> systemEntryButtons;
QVector<EntryPushButton*> userEntryButtons;
QVector<EntryPushButton*> systemEntryButtons;
QVector<EntryPushButton *> buttonsInGrid;
QLabel calculationResultLabel;
QString currentCalculationResult;
@ -70,31 +56,27 @@ class Window : public QWidget
void keyReleaseEvent(QKeyEvent *event);
QVector<EntryPushButton *> generateEntryButtons(const QVector<EntryConfig> &userEntryButtons);
void keyPressEvent(QKeyEvent *event);
void executeConfig(const EntryConfig &button);
void addToFavourites(const EntryConfig &button);
void deleteEntry(EntryConfig &config);
void buttonClick(const EntryPushButton &config);
QLineEdit *lineEdit;
QGridLayout *grid;
EntryPushButton *createEntryButton(const EntryConfig &config);
void lineEditTextChanged(QString text);
void addPATHSuggestion(const QString &text);
void clearGrid();
void addCalcResult(const QString &expression);
void addCalcResult(const QString & expression);
void initTreeWidgets();
QStringList generatePATHSuggestions(const QString &text);
void closeWindow();
std::pair<int, int> getNextFreeCell();
int rankConfig(const EntryConfig &config, QString filter) const;
private slots:
private slots:
void lineEditReturnPressed();
void showCalculationResultContextMenu(const QPoint &point);
public:
public:
Window(EntryProvider &entryProvider, SettingsProvider &settingsProvider);
void setSystemConfig(const QVector<EntryConfig> &config);
bool eventFilter(QObject *obj, QEvent *event);
void focusInput();
~Window();
};
#endif