View Issue Details
ID | Project | Category | View Status | Date Submitted | Last Update |
---|---|---|---|---|---|
0015579 | Scribus | Scripter | public | 2019-02-20 08:31 | 2024-12-26 16:24 |
Reporter | ale | Assigned To | cbradney | ||
Priority | normal | Severity | feature | Reproducibility | N/A |
Status | closed | Resolution | fixed | ||
Product Version | 1.5.5.svn | ||||
Fixed in Version | 1.7.0.svn | ||||
Summary | 0015579: [PATCH] add user's scripts to the navigation | ||||
Description | currently, the scribus official scripts are added to "Scripter > Scribus Scripts". i propose adding a "Scripter > Scripts" menu entry, if the user has own scripts. where the own scripts are placed is defined in a new field in "file > preferences > Scripter". - the text field can contain multiple paths separated by a comma. - if no path is defined, no "Scripter > Scripts" menu entry is displayed. - for a first implementation, the menu entries are the file name, without the .py extension. please give feedback. i can try to implement this, if there is some sort of agreement hat his is interesting / useful. | ||||
Tags | patch | ||||
Patch | Yes | ||||
|
I agree with this proposal. I feel you should make the scripter preferences window tabbed like the "PDF Export" in preferences. Then keep the "Extensions" stuff as one tab and make a new tab called "Scripts" and there have a big QListWidget with add/delete buttons to add/delete paths to user scripts (optionally you could have a tickbox next to the path to enable/disable reading scripts from that path without deleting the path itself. May be handy for people who want to keep stable and dev version of same scripts in 2 folders and toggle for testing). The plugin can store the paths in appdata internally with a "," or ";" whatever you prefer with escaped/quoted paths(optional) so a comma/semicolon in the path itself doesn't matter (I think linux allows ;/, in a path name ntfs does too the OS restricts it). |
|
adding a tab with a list is more work, than adding a text field... i'd prefer to first program it as a simple text field, with semicolon separated values for now, and -- if we notice that people start using the feature and need a more friendly UI -- we can easily add it later. so, i would do it the other way round: already store the single paths in the xml (so that we can easily move to a better solution), but show / edit it as a single text field. |
|
Yes initially a proof of concept is best. Impt question is should we allow the same script names on multiple folders. Currently the Action search shows the full path. But it may be nice to restrict same name scripts e.g. only the dev folder path or the stable folder path of the scripts can be used at a time. This validation could optionally be turned off but at a later point. I would be willing to test your logic even if you made a C++ variable where the paths are stored at compile time. |
|
imo, if two script have the same name, they should be shown with the same label. up to you to pick different names. most users will have only one source anyway. |
|
note to myself: - list all scripts at the root of the path - list all scripts in sub directories that have the same name as the directory containing them. |
|
next feature: the listed directory can have a "project.xml" (in the future: yaml...) file with a list of scripts: - we have to find a name for the "project.xml" - it will contain the script name (shown in the navigation), the path to the script and optionally a defnition of where in the navigation the script should be shown (is it really needed?) - if a "project" file is found, only the files listed in there are shown in the menus, otherwise all the files that match the requirements are listed. (*.py in main directory; main.py or directoryname.py in the sub directories) |
|
user scripts are only scanned when scribus starts. a "rescan" command could be added at the end of the user scripts or in the preferences... |
|
here is a first patch userscripts.patch (12,207 bytes)
From 73f42d8972746905014337babe9c30aa48babab1 Mon Sep 17 00:00:00 2001 From: ale rimoldi <ale@graphicslab.org> Date: Thu, 28 Feb 2019 17:42:10 +0100 Subject: [PATCH] add a scripter > scripts with user's scripts --- .../plugins/scriptplugin/prefs_scripter.cpp | 21 ++++ .../scriptplugin/prefs_scripterbase.ui | 14 +++ scribus/plugins/scriptplugin/scriptercore.cpp | 99 +++++++++++++++++++ scribus/plugins/scriptplugin/scriptercore.h | 9 ++ scribus/scraction.cpp | 4 + scribus/scraction.h | 2 +- 6 files changed, 148 insertions(+), 1 deletion(-) diff --git a/scribus/plugins/scriptplugin/prefs_scripter.cpp b/scribus/plugins/scriptplugin/prefs_scripter.cpp index b4bcf8094a..856aa8d6b8 100644 --- a/scribus/plugins/scriptplugin/prefs_scripter.cpp +++ b/scribus/plugins/scriptplugin/prefs_scripter.cpp @@ -31,6 +31,17 @@ Prefs_Scripter::Prefs_Scripter(QWidget* parent) // The startup script box should be disabled if ext scripts are off startupScriptEdit->setEnabled(extensionScriptsChk->isChecked()); startupScriptEdit->setText(scripterCore->startupScript()); + + PrefsContext* prefs = PrefsManager::instance()->prefsFile->getPluginContext("scriptplugin"); + PrefsTable* prefUserScriptsPath = prefs->getTable("userscriptspaths"); + QStringList paths{}; + for (int i = 0; i < prefUserScriptsPath->getRowCount(); i++) + { + paths.append(prefUserScriptsPath->get(i, 0)); + } + userScriptPathEdit->setText(paths.join(";")); + userScriptPathEdit->setToolTip( "<qt>" + tr("Multiple paths are separated by semicolons. You need to restart Scribus to see new scripts.") + "</qt>"); + // signals and slots connections connect(extensionScriptsChk, SIGNAL(toggled(bool)), startupScriptEdit, SLOT(setEnabled(bool))); // colors @@ -78,6 +89,16 @@ void Prefs_Scripter::apply() prefs->set("syntaxstring", stringColor.name()); prefs->set("syntaxtext", textColor.name()); + // qDebug() << userScriptPathEdit->text(); + PrefsTable* prefUserScriptsPath = prefs->getTable("userscriptspaths"); + prefUserScriptsPath->clear(); + int i = 0; + for (auto path: userScriptPathEdit->text().split(";")) + { + prefUserScriptsPath->set(i, 0, path); + i++; + } + emit prefsChanged(); } } diff --git a/scribus/plugins/scriptplugin/prefs_scripterbase.ui b/scribus/plugins/scriptplugin/prefs_scripterbase.ui index 7c35b7505c..892a31b1e3 100644 --- a/scribus/plugins/scriptplugin/prefs_scripterbase.ui +++ b/scribus/plugins/scriptplugin/prefs_scripterbase.ui @@ -98,6 +98,20 @@ </item> </layout> </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_4"> + <item> + <widget class="QLabel" name="label_3"> + <property name="text"> + <string>User Script:</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="userScriptPathEdit"/> + </item> + </layout> + </item> <item> <spacer name="verticalSpacer_2"> <property name="orientation"> diff --git a/scribus/plugins/scriptplugin/scriptercore.cpp b/scribus/plugins/scriptplugin/scriptercore.cpp index c9c8672cca..07548adb7a 100644 --- a/scribus/plugins/scriptplugin/scriptercore.cpp +++ b/scribus/plugins/scriptplugin/scriptercore.cpp @@ -15,6 +15,8 @@ for which a new license (GPL+exception) is in place. #include <QTextCodec> #include <QByteArray> #include <QPixmap> +#include <QDir> +#include <QDirIterator> #include <cstdlib> #include "runscriptdialog.h" @@ -48,6 +50,7 @@ ScripterCore::ScripterCore(QWidget* parent) pcon = new PythonConsole(parent); scrScripterActions.clear(); scrRecentScriptActions.clear(); + scrUserScriptActions.clear(); returnString = "init"; scrScripterActions.insert("scripterExecuteScript", new ScrAction(QObject::tr("&Execute Script..."), QKeySequence(), this)); @@ -90,6 +93,11 @@ void ScripterCore::addToMainWindowMenu(ScribusMainWindow *mw) menuMgr->addMenuItemString("scripterExecuteScript", "Scripter"); menuMgr->createMenu("RecentScripts", QObject::tr("&Recent Scripts"), "Scripter", false, true); menuMgr->addMenuItemString("RecentScripts", "Scripter"); + if (m_userScriptsEnabled) + { + menuMgr->createMenu("UserScripts", QObject::tr("S&cripts"), "Scripter", false, true); + menuMgr->addMenuItemString("UserScripts", "Scripter"); + } menuMgr->addMenuItemString("scripterExecuteScript", "Scripter"); menuMgr->addMenuItemString("SEPARATOR", "Scripter"); menuMgr->addMenuItemString("scripterShowConsole", "Scripter"); @@ -101,6 +109,10 @@ void ScripterCore::addToMainWindowMenu(ScribusMainWindow *mw) menuMgr->addMenuItemStringstoMenuBar("Scripter", scrScripterActions); RecentScripts = SavedRecentScripts; rebuildRecentScriptsMenu(); + if (m_userScriptsEnabled) + { + rebuildUserScriptsMenu(); + } } void ScripterCore::enableMainWindowMenu() @@ -109,6 +121,10 @@ void ScripterCore::enableMainWindowMenu() return; menuMgr->setMenuEnabled("ScribusScripts", true); menuMgr->setMenuEnabled("RecentScripts", true); + if (m_userScriptsEnabled) + { + menuMgr->setMenuEnabled("UserScripts", true); + } scrScripterActions["scripterExecuteScript"]->setEnabled(true); } @@ -118,6 +134,10 @@ void ScripterCore::disableMainWindowMenu() return; menuMgr->setMenuEnabled("ScribusScripts", false); menuMgr->setMenuEnabled("RecentScripts", false); + if (m_userScriptsEnabled) + { + menuMgr->setMenuEnabled("UserScripts", false); + } scrScripterActions["scripterExecuteScript"]->setEnabled(false); } @@ -156,6 +176,20 @@ void ScripterCore::rebuildRecentScriptsMenu() menuMgr->addMenuItemStringstoRememberedMenu("RecentScripts", scrRecentScriptActions); } +void ScripterCore::rebuildUserScriptsMenu() +{ + menuMgr->clearMenuStrings("UserScripts"); + scrUserScriptActions.clear(); + for (auto script: m_userScripts) + { + QString menuEntry = QFileInfo(script).baseName(); + scrUserScriptActions.insert(menuEntry, new ScrAction( ScrAction::RecentScript, menuEntry, QKeySequence(), this, script)); + connect( scrUserScriptActions[menuEntry], SIGNAL(triggeredData(QString)), this, SLOT(runUserScript(QString)) ); + menuMgr->addMenuItemString(menuEntry, "UserScripts"); + } + menuMgr->addMenuItemStringstoRememberedMenu("UserScripts", scrUserScriptActions); +} + void ScripterCore::FinishScriptRun() { ScribusMainWindow* ScMW=ScCore->primaryMainWindow(); @@ -228,6 +262,12 @@ void ScripterCore::RecentScript(const QString& fn) FinishScriptRun(); } +void ScripterCore::runUserScript(const QString& fn) +{ + slotRunScriptFile(fn); + FinishScriptRun(); +} + void ScripterCore::slotRunScriptFile(const QString& fileName, bool inMainInterpreter) { slotRunScriptFile(fileName, QStringList(), inMainInterpreter); @@ -506,6 +546,61 @@ void ScripterCore::ReadPlugPrefs() m_importAllNames = prefs->getBool("importall",true); m_startupScript = prefs->get("startupscript", QString::null); // and have the console window set up its position + + auto prefUserScriptsPath = prefs->getTable("userscriptspaths"); + m_userScriptsPaths.clear(); + for (int i = 0; i < prefUserScriptsPath->getRowCount(); i++) + { + m_userScriptsPaths.append(prefUserScriptsPath->get(i, 0)); + } + + m_userScriptsEnabled = !m_userScriptsPaths.empty(); + + if (m_userScriptsEnabled) + { + m_userScripts = getUserScripts(m_userScriptsPaths); + } +} + +/** + * list all the scripts in the paths' main directory and all + * the main.py and subdirectory.py in the sub directories. + */ +QStringList ScripterCore::getUserScripts(QStringList paths) +{ + QStringList result{}; + for (auto path: paths) + { + QDir dir{path}; + if (!dir.exists()) + continue; + // TODO: do we need to check for .PY? + for (auto scriptPath: dir.entryList(QStringList() << "*.py" << "*.PY", QDir::Files)) + { + + + result << dir.filePath(scriptPath); + } + + QDirIterator dirIter(path, QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); + while(dirIter.hasNext()) + { + QDir subPath{dirIter.next()}; + // TODO: do we need to check for .PY? + QStringList scriptPaths{ + subPath.filePath(subPath.dirName() + ".py"), + subPath.filePath("main.py") + }; + for (auto scriptPath: scriptPaths) + { + if(QFileInfo(scriptPath).exists() && !QDir(scriptPath).exists()) + { + result << scriptPath; + } + } + } + } + return result; } void ScripterCore::SavePlugPrefs() @@ -592,6 +687,10 @@ void ScripterCore::languageChange() menuMgr->setText("Scripter", QObject::tr("&Script")); menuMgr->setText("ScribusScripts", QObject::tr("&Scribus Scripts")); menuMgr->setText("RecentScripts", QObject::tr("&Recent Scripts")); + if (m_userScriptsEnabled) + { + menuMgr->setText("UserScripts", QObject::tr("S&cripts")); + } } bool ScripterCore::setupMainInterpreter() diff --git a/scribus/plugins/scriptplugin/scriptercore.h b/scribus/plugins/scriptplugin/scriptercore.h index 8682a96adb..d9c4795b18 100644 --- a/scribus/plugins/scriptplugin/scriptercore.h +++ b/scribus/plugins/scriptplugin/scriptercore.h @@ -33,11 +33,13 @@ class ScripterCore : public QObject QString returnString; /** @brief String representation of line of code to be passed to the Python interactive interpreter */ QString inValue; + QStringList getUserScriptsPaths() { return m_userScriptsPaths; } public slots: void runScriptDialog(); void StdScript(const QString& filebasename); void RecentScript(const QString& fn); + void runUserScript(const QString& script); void slotRunScriptFile(const QString& fileName, bool inMainInterpreter = false); void slotRunScriptFile(const QString& fileName, QStringList arguments, bool inMainInterpreter = false); void slotRunPythonScript(); // needed for running python script from CLI @@ -78,9 +80,13 @@ public slots: PythonConsole *pcon; QStringList SavedRecentScripts; QStringList RecentScripts; + QStringList m_userScriptsPaths; + bool m_userScriptsEnabled{false}; + QStringList m_userScripts; MenuManager *menuMgr; QMap<QString, QPointer<ScrAction> > scrScripterActions; QMap<QString, QPointer<ScrAction> > scrRecentScriptActions; + QMap<QString, QPointer<ScrAction> > scrUserScriptActions; // Preferences /** \brief pref: Enable access to main interpreter and 'extension scripts' */ @@ -89,6 +95,9 @@ public slots: bool m_importAllNames; /** \brief pref: Load this script on startup */ QString m_startupScript; +private: + QStringList getUserScripts(QStringList paths); + void rebuildUserScriptsMenu(); }; #endif diff --git a/scribus/scraction.cpp b/scribus/scraction.cpp index 9ff8ec0cb4..dddc62eb11 100644 --- a/scribus/scraction.cpp +++ b/scribus/scraction.cpp @@ -114,6 +114,8 @@ void ScrAction::triggeredToTriggeredData() emit triggeredData(data().toString()); if (m_actionType==ScrAction::RecentScript) emit triggeredData(data().toString()); + if (m_actionType==ScrAction::UserScript) + emit triggeredData(data().toString()); if (m_actionType==ScrAction::UnicodeChar) emit triggeredUnicodeShortcut(data().toInt()); if (m_actionType==ScrAction::Layer) @@ -143,6 +145,8 @@ void ScrAction::toggledToToggledData(bool ison) emit toggledData(ison, data().toString()); if (m_actionType==ScrAction::RecentScript) emit toggledData(ison, text()); + if (m_actionType==ScrAction::UserScript) + emit toggledData(ison, text()); if (m_actionType==ScrAction::Layer) emit toggledData(ison, data().toInt()); // no toggle for UnicodeChar diff --git a/scribus/scraction.h b/scribus/scraction.h index 0d409124a0..b526779ea9 100644 --- a/scribus/scraction.h +++ b/scribus/scraction.h @@ -35,7 +35,7 @@ class SCRIBUS_API ScrAction : public QAction Q_OBJECT public: - typedef enum {Normal, DataInt, DataDouble, DataQString, RecentFile, DLL, Window, RecentScript, UnicodeChar, Layer, ActionDLL, RecentPaste, ActionDLLSE } ActionType; + typedef enum {Normal, DataInt, DataDouble, DataQString, RecentFile, DLL, Window, RecentScript, UserScript, UnicodeChar, Layer, ActionDLL, RecentPaste, ActionDLLSE } ActionType; /*! \author Craig Bradney |
|
any feedback? anything i should improve, for a first release? |
|
I like the thing. If you are up for adding a "reload scripts" button next to the user scripts text box which will call the update process on user press it will be nice. But I understand your reasons for not wanting to work on it. I am ok with saving the .sla and relaunching Scribus. I think its good for the first release. For the next release you could add "reload scripts" which refreshes the menu without a restart but again no issue. I was wondering if there is a way to shorten the paths to the scripts displayed in action search to make searching easier. Currently the whole file paths are displayed. If we permit directories to only be added if there is no script name overlap we can abbreviate the searchable string in action_search only to the name of the script itself. So instead of "E:\foo\bar\da\sa\ra\explodeframes.py" "E:\foo\bar\da\sa\ra\fitframes.py" we can just have: explodeframes.py fitframes.py And searching and scanning these with our eyes is much easier. Another idea would be to give user assigned nicknames to each added user script folder. e.g. <sf1>/explodeframes.py <sf2>/explodeframes.py <sf2>/fitframes.py where sf1 is a user assigned nickname for "E:\foo\bar\da\sa\ra\" and sf2 is a nickname for "C:\foo\bar\bla\" "sf" being "script folder". These could even be auto generated too. |
|
personally, i think that the reload "button" should be in a new section, in the "scripter > scripts" dialog. currently, i don't have the patch installed, but you are saying that in the menus you get the scripts with their paths? iirc, it was not the case in my setup... or you get the path only in the action search? the idea was - only display the name of the script, without the .py - if two scripts have the same name, you will get the name twice. - if you are using twice the same script name, it's up to the user to rename the script (and it's rather unlikely (and a bad habit) to have two scripts with the same name... and if you want them to be shown differently, my idea is that one should then list all the script in a project file, which gives full control on which scripts, how and where they are listed. but i'd like to get the current code reviewed and possibly accepted before adding further features. |
|
a-l-e you configure the directories only once in preferences so I feel the "refresh scripts" button should be there only for convenience so a user can press it whenever they change a path and want to force a refresh. And sorry about the full path's thing. The action search was pulling the full paths from the "Scripter->Recent Scripts" menu which happens to display full paths. If you type the word "Recent" you will see full paths to the same scripts. Regarding the user scripts feature -- I would recommend that you keep the .py extension I prefer that the file extensions not be stripped. If a feature could be added to ignore displaying the recent scripts it would be nice to make things cleaner. Especially considering there is often an overlap between recently run scripts and the scripts defined in the user scripts folder. Perhaps a checkbox on by default called "do not display recently run scripts". This concept could be extended into a general purpose menu filter if people want it in the future. The question is can a plugin add stuff to preferences without changing the Scribus main code? I feel these configuration options should be inside the plugin itself and scribus should have some API for plugins to tell Scribus what configuration options they wish to add. I wonder if its better to have a cog wheel button inside the popup action search dialog which opens its won internal preferences window only for the plugins configuration. This breaks the everything in one central place concept of preferences but it encapsulates all logic inside the main plugin. |
|
I think "Reload scripts" can also be in the main "Scripter" menu as "Scripter -> Reload scripts". But usually no one will reload the scripts unless they changed the config which is inside preferences so ... ? |
|
most people won't need to reload after having add a path... this is something very rarely and one can restart scribus after changing it. but what more people will need is: reload the list after having added a new script in known path... and, in that case, restarting scribus must be a bit more of a burden... i think that the list should be reloaded when the path has changed, but i'm not 100% sure that i have the information... i will check it... |
|
new patch that adds - update of the paths when preferences are saved (and the paths list has changed) - menu entry for hot reloading the list of scripts (when you have written that cool new script) i think that the patch is now ready for review and commit. userscripts.diff (15,743 bytes)
diff --git a/scribus/plugins/scriptplugin/prefs_scripter.cpp b/scribus/plugins/scriptplugin/prefs_scripter.cpp index b4bcf8094a..cf0643ad4f 100644 --- a/scribus/plugins/scriptplugin/prefs_scripter.cpp +++ b/scribus/plugins/scriptplugin/prefs_scripter.cpp @@ -31,6 +31,18 @@ Prefs_Scripter::Prefs_Scripter(QWidget* parent) // The startup script box should be disabled if ext scripts are off startupScriptEdit->setEnabled(extensionScriptsChk->isChecked()); startupScriptEdit->setText(scripterCore->startupScript()); + + PrefsContext* prefs = PrefsManager::instance()->prefsFile->getPluginContext("scriptplugin"); + PrefsTable* prefUserScriptsPath = prefs->getTable("userscriptspaths"); + QStringList userPaths{}; + for (int i = 0; i < prefUserScriptsPath->getRowCount(); i++) + { + userPaths.append(prefUserScriptsPath->get(i, 0)); + } + userScriptsPaths = userPaths.join(";"); + userScriptPathEdit->setText(userScriptsPaths); + userScriptPathEdit->setToolTip( "<qt>" + tr("Multiple paths are separated by semicolons. You need to restart Scribus to see new scripts.") + "</qt>"); + // signals and slots connections connect(extensionScriptsChk, SIGNAL(toggled(bool)), startupScriptEdit, SLOT(setEnabled(bool))); // colors @@ -79,6 +91,19 @@ void Prefs_Scripter::apply() prefs->set("syntaxtext", textColor.name()); emit prefsChanged(); + + if (userScriptPathEdit->text() != userScriptsPaths) + { + PrefsTable* prefUserScriptsPath = prefs->getTable("userscriptspaths"); + prefUserScriptsPath->clear(); + int i = 0; + for (auto path: userScriptPathEdit->text().split(";")) + { + prefUserScriptsPath->set(i, 0, path); + i++; + } + emit prefsUserScriptsPathsChanged(); + } } } diff --git a/scribus/plugins/scriptplugin/prefs_scripter.h b/scribus/plugins/scriptplugin/prefs_scripter.h index 597236bab8..2c94d20f8b 100644 --- a/scribus/plugins/scriptplugin/prefs_scripter.h +++ b/scribus/plugins/scriptplugin/prefs_scripter.h @@ -37,6 +37,8 @@ class Prefs_Scripter : public Prefs_Pane, Ui::Prefs_Scripter QColor signColor; QColor stringColor; QColor numberColor; + private: + QString userScriptsPaths{}; protected slots: /*! \brief All requests for color change are handled here. @@ -47,6 +49,7 @@ class Prefs_Scripter : public Prefs_Pane, Ui::Prefs_Scripter signals: void prefsChanged(); + void prefsUserScriptsPathsChanged(); }; #endif // PREFS_SCRIPTER_H diff --git a/scribus/plugins/scriptplugin/prefs_scripterbase.ui b/scribus/plugins/scriptplugin/prefs_scripterbase.ui index 7c35b7505c..00986aca25 100644 --- a/scribus/plugins/scriptplugin/prefs_scripterbase.ui +++ b/scribus/plugins/scriptplugin/prefs_scripterbase.ui @@ -98,6 +98,20 @@ </item> </layout> </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_4"> + <item> + <widget class="QLabel" name="label_3"> + <property name="text"> + <string>User Scripts Path:</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="userScriptPathEdit"/> + </item> + </layout> + </item> <item> <spacer name="verticalSpacer_2"> <property name="orientation"> diff --git a/scribus/plugins/scriptplugin/scriptercore.cpp b/scribus/plugins/scriptplugin/scriptercore.cpp index c9c8672cca..75a16fe16a 100644 --- a/scribus/plugins/scriptplugin/scriptercore.cpp +++ b/scribus/plugins/scriptplugin/scriptercore.cpp @@ -15,6 +15,8 @@ for which a new license (GPL+exception) is in place. #include <QTextCodec> #include <QByteArray> #include <QPixmap> +#include <QDir> +#include <QDirIterator> #include <cstdlib> #include "runscriptdialog.h" @@ -48,6 +50,7 @@ ScripterCore::ScripterCore(QWidget* parent) pcon = new PythonConsole(parent); scrScripterActions.clear(); scrRecentScriptActions.clear(); + scrUserScriptActions.clear(); returnString = "init"; scrScripterActions.insert("scripterExecuteScript", new ScrAction(QObject::tr("&Execute Script..."), QKeySequence(), this)); @@ -90,6 +93,7 @@ void ScripterCore::addToMainWindowMenu(ScribusMainWindow *mw) menuMgr->addMenuItemString("scripterExecuteScript", "Scripter"); menuMgr->createMenu("RecentScripts", QObject::tr("&Recent Scripts"), "Scripter", false, true); menuMgr->addMenuItemString("RecentScripts", "Scripter"); + addUserScriptsMenu(); menuMgr->addMenuItemString("scripterExecuteScript", "Scripter"); menuMgr->addMenuItemString("SEPARATOR", "Scripter"); menuMgr->addMenuItemString("scripterShowConsole", "Scripter"); @@ -101,6 +105,20 @@ void ScripterCore::addToMainWindowMenu(ScribusMainWindow *mw) menuMgr->addMenuItemStringstoMenuBar("Scripter", scrScripterActions); RecentScripts = SavedRecentScripts; rebuildRecentScriptsMenu(); + rebuildUserScriptsMenu(); +} + +void ScripterCore::addUserScriptsMenu() +{ + if (m_userScriptsEnabled) + { + if (!menuMgr->menuExists("UserScripts")) + { + menuMgr->createMenu("UserScripts", QObject::tr("S&cripts"), "Scripter", false, true); + menuMgr->addMenuItemString("UserScripts", "Scripter"); + } + + } } void ScripterCore::enableMainWindowMenu() @@ -109,6 +127,10 @@ void ScripterCore::enableMainWindowMenu() return; menuMgr->setMenuEnabled("ScribusScripts", true); menuMgr->setMenuEnabled("RecentScripts", true); + if (m_userScriptsEnabled) + { + menuMgr->setMenuEnabled("UserScripts", true); + } scrScripterActions["scripterExecuteScript"]->setEnabled(true); } @@ -118,6 +140,10 @@ void ScripterCore::disableMainWindowMenu() return; menuMgr->setMenuEnabled("ScribusScripts", false); menuMgr->setMenuEnabled("RecentScripts", false); + if (m_userScriptsEnabled) + { + menuMgr->setMenuEnabled("UserScripts", false); + } scrScripterActions["scripterExecuteScript"]->setEnabled(false); } @@ -156,6 +182,33 @@ void ScripterCore::rebuildRecentScriptsMenu() menuMgr->addMenuItemStringstoRememberedMenu("RecentScripts", scrRecentScriptActions); } +void ScripterCore::updateUserScriptsMenu() +{ + m_userScripts = getUserScripts(m_userScriptsPaths); + rebuildUserScriptsMenu(); +} + +void ScripterCore::rebuildUserScriptsMenu() +{ + menuMgr->clearMenuStrings("UserScripts"); + scrUserScriptActions.clear(); + for (auto script: m_userScripts) + { + QString menuEntry = QFileInfo(script).baseName(); + scrUserScriptActions.insert(menuEntry, new ScrAction( ScrAction::RecentScript, menuEntry, QKeySequence(), this, script)); + connect( scrUserScriptActions[menuEntry], SIGNAL(triggeredData(QString)), this, SLOT(runUserScript(QString)) ); + menuMgr->addMenuItemString(menuEntry, "UserScripts"); + } + + menuMgr->addMenuItemString("SEPARATOR", "UserScripts"); + + scrUserScriptActions.insert("userScriptsUpdate", new ScrAction(QObject::tr("List &Update"), QKeySequence(), this)); + QObject::connect( scrUserScriptActions["userScriptsUpdate"], SIGNAL(triggered()) , this, SLOT(updateUserScriptsMenu()) ); + menuMgr->addMenuItemString("userScriptsUpdate", "UserScripts"); + + menuMgr->addMenuItemStringstoRememberedMenu("UserScripts", scrUserScriptActions); +} + void ScripterCore::FinishScriptRun() { ScribusMainWindow* ScMW=ScCore->primaryMainWindow(); @@ -228,6 +281,12 @@ void ScripterCore::RecentScript(const QString& fn) FinishScriptRun(); } +void ScripterCore::runUserScript(const QString& fn) +{ + slotRunScriptFile(fn); + FinishScriptRun(); +} + void ScripterCore::slotRunScriptFile(const QString& fileName, bool inMainInterpreter) { slotRunScriptFile(fileName, QStringList(), inMainInterpreter); @@ -506,6 +565,64 @@ void ScripterCore::ReadPlugPrefs() m_importAllNames = prefs->getBool("importall",true); m_startupScript = prefs->get("startupscript", QString::null); // and have the console window set up its position + + m_userScriptsPaths = getUserScriptsPaths(prefs); + m_userScriptsEnabled = !m_userScriptsPaths.empty(); + if (m_userScriptsEnabled) + { + m_userScripts = getUserScripts(m_userScriptsPaths); + } +} + +QStringList ScripterCore::getUserScriptsPaths(PrefsContext* prefs) +{ + QStringList result{}; + + auto prefUserScriptsPath = prefs->getTable("userscriptspaths"); + result.clear(); + for (int i = 0; i < prefUserScriptsPath->getRowCount(); i++) + { + result.append(prefUserScriptsPath->get(i, 0)); + } + + return result; +} + +QStringList ScripterCore::getUserScripts(QStringList paths) +{ + QStringList result{}; + for (auto path: paths) + { + QDir dir{path}; + if (!dir.exists()) + continue; + // TODO: do we need to check for .PY? + for (auto scriptPath: dir.entryList(QStringList() << "*.py" << "*.PY", QDir::Files)) + { + + + result << dir.filePath(scriptPath); + } + + QDirIterator dirIter(path, QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); + while(dirIter.hasNext()) + { + QDir subPath{dirIter.next()}; + // TODO: do we need to check for .PY? + QStringList scriptPaths{ + subPath.filePath(subPath.dirName() + ".py"), + subPath.filePath("main.py") + }; + for (auto scriptPath: scriptPaths) + { + if(QFileInfo(scriptPath).exists() && !QDir(scriptPath).exists()) + { + result << scriptPath; + } + } + } + } + return result; } void ScripterCore::SavePlugPrefs() @@ -592,6 +709,10 @@ void ScripterCore::languageChange() menuMgr->setText("Scripter", QObject::tr("&Script")); menuMgr->setText("ScribusScripts", QObject::tr("&Scribus Scripts")); menuMgr->setText("RecentScripts", QObject::tr("&Recent Scripts")); + if (m_userScriptsEnabled) + { + menuMgr->setText("UserScripts", QObject::tr("S&cripts")); + } } bool ScripterCore::setupMainInterpreter() @@ -635,6 +756,18 @@ void ScripterCore::updateSyntaxHighlighter() pcon->updateSyntaxHighlighter(); } +void ScripterCore::updateUserScriptsPaths() +{ + PrefsContext* prefs = PrefsManager::instance()->prefsFile->getPluginContext("scriptplugin"); + m_userScriptsPaths = getUserScriptsPaths(prefs); + m_userScripts = getUserScripts(m_userScriptsPaths); + m_userScriptsEnabled = !m_userScriptsPaths.empty(); + + addUserScriptsMenu(); + + rebuildUserScriptsMenu(); +} + const QString & ScripterCore::startupScript() const { return m_startupScript; diff --git a/scribus/plugins/scriptplugin/scriptercore.h b/scribus/plugins/scriptplugin/scriptercore.h index 8682a96adb..7505ec218b 100644 --- a/scribus/plugins/scriptplugin/scriptercore.h +++ b/scribus/plugins/scriptplugin/scriptercore.h @@ -33,11 +33,14 @@ class ScripterCore : public QObject QString returnString; /** @brief String representation of line of code to be passed to the Python interactive interpreter */ QString inValue; + QStringList getUserScriptsPaths() { return m_userScriptsPaths; } + QStringList getUserScriptsPaths(PrefsContext* prefs); public slots: void runScriptDialog(); void StdScript(const QString& filebasename); void RecentScript(const QString& fn); + void runUserScript(const QString& script); void slotRunScriptFile(const QString& fileName, bool inMainInterpreter = false); void slotRunScriptFile(const QString& fileName, QStringList arguments, bool inMainInterpreter = false); void slotRunPythonScript(); // needed for running python script from CLI @@ -62,6 +65,7 @@ public slots: void setStartupScript(const QString& newScript); void setExtensionsEnabled(bool enable); void updateSyntaxHighlighter(); + void updateUserScriptsPaths(); protected: // Private helper functions @@ -78,9 +82,13 @@ public slots: PythonConsole *pcon; QStringList SavedRecentScripts; QStringList RecentScripts; + QStringList m_userScriptsPaths; + bool m_userScriptsEnabled{false}; + QStringList m_userScripts; MenuManager *menuMgr; QMap<QString, QPointer<ScrAction> > scrScripterActions; QMap<QString, QPointer<ScrAction> > scrRecentScriptActions; + QMap<QString, QPointer<ScrAction> > scrUserScriptActions; // Preferences /** \brief pref: Enable access to main interpreter and 'extension scripts' */ @@ -89,6 +97,17 @@ public slots: bool m_importAllNames; /** \brief pref: Load this script on startup */ QString m_startupScript; +private slots: + void updateUserScriptsMenu(); +private: + /** \brief Add the user menu script if it does not exist yet */ + void addUserScriptsMenu(); + /** + * \brief List all the scripts in the paths' main directory and all + * the main.py and subdirectory.py in the sub directories. + */ + QStringList getUserScripts(QStringList paths); + void rebuildUserScriptsMenu(); }; #endif diff --git a/scribus/plugins/scriptplugin/scriptplugin.cpp b/scribus/plugins/scriptplugin/scriptplugin.cpp index 87795e8e87..9a0f8c0a40 100644 --- a/scribus/plugins/scriptplugin/scriptplugin.cpp +++ b/scribus/plugins/scriptplugin/scriptplugin.cpp @@ -205,6 +205,7 @@ bool ScriptPlugin::newPrefsPanelWidget(QWidget* parent, PrefsPanel*& panel, QStr panel = new ScripterPrefsGui(parent); Q_CHECK_PTR(panel); connect(panel, SIGNAL(prefsChanged()), scripterCore, SLOT(updateSyntaxHighlighter())); + connect(panel, SIGNAL(prefsUserScriptsPathsChanged()), scripterCore, SLOT(updateUserScriptsPaths())); caption = tr("Scripter"); icon = IconManager::instance()->loadPixmap("python.png"); return true; @@ -216,6 +217,7 @@ bool ScriptPlugin::newPrefsPanelWidget(QWidget* parent, Prefs_Pane*& panel, QStr panel = new Prefs_Scripter(parent); Q_CHECK_PTR(panel); connect(panel, SIGNAL(prefsChanged()), scripterCore, SLOT(updateSyntaxHighlighter())); + connect(panel, SIGNAL(prefsUserScriptsPathsChanged()), scripterCore, SLOT(updateUserScriptsPaths())); caption = tr("Scripter"); icon = IconManager::instance()->loadPixmap("python_16.png"); return true; diff --git a/scribus/plugins/scriptplugin/scriptplugin.h b/scribus/plugins/scriptplugin/scriptplugin.h index 6f6bdfce72..1983e39629 100644 --- a/scribus/plugins/scriptplugin/scriptplugin.h +++ b/scribus/plugins/scriptplugin/scriptplugin.h @@ -41,6 +41,8 @@ class PLUGIN_API ScriptPlugin : public ScPersistentPlugin // Special features (none) QByteArray pythonHome; + private slots: + void updateUserScriptsPaths(); }; extern "C" PLUGIN_API int scriptplugin_getPluginAPIVersion(); diff --git a/scribus/scraction.cpp b/scribus/scraction.cpp index 9ff8ec0cb4..dddc62eb11 100644 --- a/scribus/scraction.cpp +++ b/scribus/scraction.cpp @@ -114,6 +114,8 @@ void ScrAction::triggeredToTriggeredData() emit triggeredData(data().toString()); if (m_actionType==ScrAction::RecentScript) emit triggeredData(data().toString()); + if (m_actionType==ScrAction::UserScript) + emit triggeredData(data().toString()); if (m_actionType==ScrAction::UnicodeChar) emit triggeredUnicodeShortcut(data().toInt()); if (m_actionType==ScrAction::Layer) @@ -143,6 +145,8 @@ void ScrAction::toggledToToggledData(bool ison) emit toggledData(ison, data().toString()); if (m_actionType==ScrAction::RecentScript) emit toggledData(ison, text()); + if (m_actionType==ScrAction::UserScript) + emit toggledData(ison, text()); if (m_actionType==ScrAction::Layer) emit toggledData(ison, data().toInt()); // no toggle for UnicodeChar diff --git a/scribus/scraction.h b/scribus/scraction.h index 0d409124a0..b526779ea9 100644 --- a/scribus/scraction.h +++ b/scribus/scraction.h @@ -35,7 +35,7 @@ class SCRIBUS_API ScrAction : public QAction Q_OBJECT public: - typedef enum {Normal, DataInt, DataDouble, DataQString, RecentFile, DLL, Window, RecentScript, UnicodeChar, Layer, ActionDLL, RecentPaste, ActionDLLSE } ActionType; + typedef enum {Normal, DataInt, DataDouble, DataQString, RecentFile, DLL, Window, RecentScript, UserScript, UnicodeChar, Layer, ActionDLL, RecentPaste, ActionDLLSE } ActionType; /*! \author Craig Bradney |
|
the "Scripts" menu entry is not created when one adds the first path. the code gets to the code adding the menu https://github.com/aoloe/scribus/blob/userscripts/scribus/plugins/scriptplugin/scriptercore.cpp#L117 but the menu does not show up. looks like a restriction of Qt or of the way menumanager works... imo it's ok to commit the patch as is, but if someone finds a solution, i'm more than happy : - ) |
|
I absolutely need this. I have so many odds and ends of scripts that do various things for my workflow that I keep losing them. It's getting to the stage that I spend more time hunting for them than they save when I run them (I'm not the most organised editor in the world)! I'd love to be able to attach them to a menu option, rather than having them disappear off the list of 'Recent Scripts' list by the time I want to use them again. |
|
i have a new patch that provides a real widget for the preferences and "correctly" manages a "scripts" sub menu in script. |
|
Here is the local checkout of https://github.com/aoloe/scribus-script-repository as it looked a couple of days ago... |
|
Here is a new patch: https://gitlab.com/scribus/scribus/-/merge_requests/45/diffs - has a real widget in the preferences. - only adds the Script > Scripts sub menu if it finds scripts to be shown. - updates the list of scripts at start time and when the list of folders has changed. Since the scripts are now in the menues, it's then possible to run them with the actions launcher. Some technical details: - It adds a ScriptPaths class that is managing the "hard" work for the list of folders and detecting the scripts. - it finds scripts at the root of the given folders: - if they are .py files - if they are in a folder inside of it and are called main.py or have the exact the same name as the folder containing them (the_script/the_script.py) - changes the first letter of the script name to uppercase and replaces the underscores by spaces. - menumanager.h gets functions for hiding and showing rembered menus. Once this patch is in (in its actual form or revised), I would like to work on some sort of "manifest" file that would make it possible to further control how the scripts in a directory work / are detected. item-dialog.diff (4,329 bytes)
diff --git a/scribus/plugins/scriptplugin/cmddialog.cpp b/scribus/plugins/scriptplugin/cmddialog.cpp index 263188fd087f6bf68e43bdd1392ab112a9aee185..d63ec41e072ceb72bae0e83e204520dadcd95367 100644 --- a/scribus/plugins/scriptplugin/cmddialog.cpp +++ b/scribus/plugins/scriptplugin/cmddialog.cpp @@ -123,6 +123,48 @@ PyObject *scribus_valuedialog(PyObject* /* self */, PyObject* args) return PyUnicode_FromString(txt.toUtf8()); } +PyObject *scribus_itemdialog(PyObject* /* self */, PyObject* args) +{ + char *caption = const_cast<char*>(""); + char *message = const_cast<char*>(""); + PyObject* listObject; + unsigned int editable = 0; + if (!PyArg_ParseTuple(args, "esesO|p", "utf-8", &caption, "utf-8", &message, &listObject, &editable)) + return nullptr; + + QStringList items; + PyObject* list = PySequence_List(listObject); + if (list == nullptr) + { + PyErr_SetString(PyExc_ValueError, QObject::tr("Expected a list of options", "python error").toLocal8Bit().constData()); + return nullptr; + } + + int n = PyList_Size(list); + for (int i = 0; i < n; ++i) + { + PyObject* itemObject = PyList_GetItem(list, i); + char *item = const_cast<char*>(""); + if (!PyArg_Parse(itemObject, "es", "utf-8", &item)) + { + PyErr_SetString(PyExc_ValueError, QObject::tr("Items must be strings", "python error").toLocal8Bit().constData()); + return nullptr; + } + items << QString::fromUtf8(item); + } + + QApplication::changeOverrideCursor(QCursor(Qt::ArrowCursor)); + bool ok; + QString choice = QInputDialog::getItem(ScCore->primaryMainWindow(), + QString::fromUtf8(caption), + QString::fromUtf8(message), + items, + 0, + editable == 1, + &ok); + return PyUnicode_FromString(choice.toUtf8()); +} + PyObject *scribus_newstyledialog(PyObject*, PyObject* args) { if (!checkHaveDocument()) @@ -155,6 +197,7 @@ void cmddialogdocwarnings() { QStringList s; s << scribus_filedialog__doc__ + << scribus_itemdialog__doc__ << scribus_messagebox__doc__ << scribus_newdocdialog__doc__ << scribus_newstyledialog__doc__ diff --git a/scribus/plugins/scriptplugin/cmddialog.h b/scribus/plugins/scriptplugin/cmddialog.h index 6940b730d5dda85105447c9e28fb274652e2eb93..0b2348b606d3525dd10495c25193361c20e3049e 100644 --- a/scribus/plugins/scriptplugin/cmddialog.h +++ b/scribus/plugins/scriptplugin/cmddialog.h @@ -103,6 +103,17 @@ Example: valueDialog('title', 'text in the window', 'optional')\n\ /* 09/24/2004 petr vanek */ PyObject *scribus_valuedialog(PyObject * /*self*/, PyObject* args); +/*! docstring */ +PyDoc_STRVAR(scribus_itemdialog__doc__, +QT_TR_NOOP("itemDialog(caption, message, list_of_strings[, editable]) -> string\n\ +\n\ +Shows the common 'Make a choice' dialog and returns the selected value as a string\n\ +Parameters: window title, text in the window and a list of string values.\n\ +Optionally, you can let the user edit the value by setting `editable` to `True`.\n\ +\n\ +Example: itemDialog('title', 'text in the window', ['apples', 'pears', 'raisins'])\n\ +")); +PyObject *scribus_itemdialog(PyObject * /*self*/, PyObject* args); PyDoc_STRVAR(scribus_newstyledialog__doc__, QT_TR_NOOP("newStyleDialog() -> string\n\ diff --git a/scribus/plugins/scriptplugin/scriptplugin.cpp b/scribus/plugins/scriptplugin/scriptplugin.cpp index 2836dfb9672dd54a06ee5ff98f8084e54a9b9f7c..d7ade0199a4602af94a45906d8cf676d33493c0c 100644 --- a/scribus/plugins/scriptplugin/scriptplugin.cpp +++ b/scribus/plugins/scriptplugin/scriptplugin.cpp @@ -441,6 +441,7 @@ PyMethodDef scribus_methods[] = { {const_cast<char*>("isLocked"), scribus_islocked, METH_VARARGS, tr(scribus_islocked__doc__)}, {const_cast<char*>("isPDFBookmark"), scribus_ispdfbookmark, METH_VARARGS, tr(scribus_ispdfbookmark__doc__)}, {const_cast<char*>("isSpotColor"), scribus_isspotcolor, METH_VARARGS, tr(scribus_isspotcolor__doc__)}, + {const_cast<char*>("itemDialog"), scribus_itemdialog, METH_VARARGS, tr(scribus_itemdialog__doc__)}, {const_cast<char*>("layoutText"), scribus_layouttext, METH_VARARGS, tr(scribus_layouttext__doc__)}, {const_cast<char*>("layoutTextChain"), scribus_layouttextchain, METH_VARARGS, tr(scribus_layouttextchain__doc__)}, {const_cast<char*>("linkTextFrames"), scribus_linktextframes, METH_VARARGS, tr(scribus_linktextframes__doc__)}, |
|
any feedback? |
|
Ale... can you please update the script for current code (1.6.x or 1.7.x, your choice) and I'll review it? |
|
here it is for master |
|
... there seems to be issues with the uploading... ... ah, ok probably i have to wait until the progress bar gets green... which can take a long time... still completely gray... reloading (again) and retrying... no activity in the browser's dev tools... trying to add the note... if there is not diff, attached, can you please check that the upload works? own-script.diff (23,083 bytes)
From 50ece2748a89791879ecf15cffee2faa4655fd66 Mon Sep 17 00:00:00 2001 From: ale rimoldi <ale@graphicslab.org> Date: Thu, 14 Nov 2024 10:45:20 +0100 Subject: add own scripts in a script submenu diff --git a/scribus/menumanager.cpp b/scribus/menumanager.cpp index d5df098a0..35f89d3cf 100644 --- a/scribus/menumanager.cpp +++ b/scribus/menumanager.cpp @@ -220,6 +220,28 @@ void MenuManager::addMenuItemStringsToRememberedMenu(const QString &menuName, co addMenuItemStringsToMenu(menuName, rememberedMenus.value(menuName), menuActions); } +void MenuManager::hideRemberedMenu(const QString& menuName) +{ + if (!rememberedMenus.contains(menuName)) + return; + if (rememberedMenus.value(menuName) == nullptr) + return; + + auto menu = rememberedMenus.value(menuName); + menu->menuAction()->setVisible(false); +} + +void MenuManager::showRemberedMenu(const QString& menuName) +{ + if (!rememberedMenus.contains(menuName)) + return; + if (rememberedMenus.value(menuName) == nullptr) + return; + + auto menu = rememberedMenus.value(menuName); + menu->menuAction()->setVisible(true); +} + void MenuManager::clearMenuStrings(const QString &menuName) { QMenu* menu = rememberedMenus.value(menuName, nullptr); diff --git a/scribus/menumanager.h b/scribus/menumanager.h index eee3a8e37..2bdd08d3f 100644 --- a/scribus/menumanager.h +++ b/scribus/menumanager.h @@ -67,6 +67,9 @@ class SCRIBUS_API MenuManager : public QObject void addMenuItemStringAfter(const QString &s, const QString &after, const QString &parent); void addMenuItemStringsToMenu(const QString &menuName, QMenu *menuToAddTo, const QMap<QString, QPointer<ScrAction> > &menuActions); void addMenuItemStringsToRememberedMenu(const QString &menuName, const QMap<QString, QPointer<ScrAction> > &menuActions); + void hideRemberedMenu(const QString& menuName); + void showRemberedMenu(const QString& menuName); + void addMenuItemStringsToMenuBar(const QString &menuName, const QMap<QString, QPointer<ScrAction> > &menuActions); void clearMenuStrings(const QString &menuName); void dumpMenuStrings(); diff --git a/scribus/plugins/scriptplugin/CMakeLists.txt b/scribus/plugins/scriptplugin/CMakeLists.txt index ef2c21758..0276c0b12 100644 --- a/scribus/plugins/scriptplugin/CMakeLists.txt +++ b/scribus/plugins/scriptplugin/CMakeLists.txt @@ -37,6 +37,7 @@ set(SCRIPTER_PLUGIN_SOURCES pyesstring.cpp runscriptdialog.cpp scriptercore.cpp + scriptpaths.cpp scriptplugin.cpp svgimport.cpp ) diff --git a/scribus/plugins/scriptplugin/prefs_scripter.cpp b/scribus/plugins/scriptplugin/prefs_scripter.cpp index 2d3d9f5d8..5e5ed340e 100644 --- a/scribus/plugins/scriptplugin/prefs_scripter.cpp +++ b/scribus/plugins/scriptplugin/prefs_scripter.cpp @@ -36,6 +36,7 @@ Prefs_Scripter::Prefs_Scripter(QWidget* parent) // The startup script box should be disabled if ext scripts are off startupScriptEdit->setEnabled(extensionScriptsChk->isChecked()); startupScriptEdit->setText(scripterCore->startupScript()); + scriptPathsListWidget->addItems(scripterCore->scriptPaths.get()); // signals and slots connections connect(extensionScriptsChk, SIGNAL(toggled(bool)), startupScriptEdit, SLOT(setEnabled(bool))); // colors @@ -48,6 +49,15 @@ Prefs_Scripter::Prefs_Scripter(QWidget* parent) connect(numberButton, SIGNAL(clicked()), this, SLOT(setColor())); connect(extensionScriptsChk, SIGNAL(toggled(bool)), startupScriptChangeButton, SLOT(setEnabled(bool))); connect(startupScriptChangeButton, SIGNAL(clicked()), this, SLOT(changeStartupScript())); + + changePathButton->setEnabled(false); + removePathButton->setEnabled(false); + connect(scriptPathsListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(selectPath(QListWidgetItem*))); + connect(addPathButton, SIGNAL(clicked()), this, SLOT(addPath())); + connect(changePathButton, SIGNAL(clicked()), this, SLOT(changePath())); + connect(removePathButton, SIGNAL(clicked()), this, SLOT(removePath())); + + } Prefs_Scripter::~Prefs_Scripter() = default; @@ -81,6 +91,17 @@ void Prefs_Scripter::apply() prefs->set("syntaxstring", stringColor.name()); prefs->set("syntaxtext", textColor.name()); + if (pathsChanged) + { + scripterCore->scriptPaths.clear(); + for (int i = 0; i < scriptPathsListWidget->count(); i++) { + scripterCore->scriptPaths.append(scriptPathsListWidget->item(i)->text()); + } + scripterCore->scriptPaths.buildMenu(); + } + + scripterCore->scriptPaths.saveToPrefs(); + emit prefsChanged(); } } @@ -161,3 +182,74 @@ void Prefs_Scripter::changeStartupScript() startupScriptEdit->setText(s); } +void Prefs_Scripter::selectPath(QListWidgetItem *c) +{ + changePathButton->setEnabled(true); + removePathButton->setEnabled(true); +} + +void Prefs_Scripter::addPath() +{ + QString s = QFileDialog::getExistingDirectory(this, tr("Choose a Directory"), latestPath); + if (s.isEmpty()) + return; + + if (s.endsWith("/")) + { + s.chop(1); + } + s = QDir::toNativeSeparators(s); + if (scriptPathsListWidget->findItems(s, Qt::MatchExactly).count() != 0) + return; + + scriptPathsListWidget->addItem(s); + + scriptPathsListWidget->setCurrentRow(scriptPathsListWidget->count() - 1); + changePathButton->setEnabled(true); + removePathButton->setEnabled(true); + latestPath = s; + pathsChanged = true; +} + +void Prefs_Scripter::changePath() +{ + QString s = QFileDialog::getExistingDirectory(this, tr("Choose a Directory"), latestPath); + if (s.isEmpty()) + return; + + if (s.endsWith("/")) + { + s.chop(1); + } + s = QDir::toNativeSeparators(s); + // if the new path is already in the list, just remove the old path + if (scriptPathsListWidget->findItems(s, Qt::MatchExactly).count() != 0) + { + removePath(); + return; + } + + scriptPathsListWidget->currentItem()->setText(s); + + latestPath = s; + pathsChanged = true; +} + +void Prefs_Scripter::removePath() +{ + const int i = scriptPathsListWidget->currentRow(); + if (scriptPathsListWidget->count() == 1) + { + scriptPathsListWidget->clear(); + } + else + { + delete scriptPathsListWidget->takeItem(i); + } + if (scriptPathsListWidget->count() == 0) + { + changePathButton->setEnabled(false); + removePathButton->setEnabled(false); + } + pathsChanged = true; +} diff --git a/scribus/plugins/scriptplugin/prefs_scripter.h b/scribus/plugins/scriptplugin/prefs_scripter.h index 46a8dffba..29bfbc76b 100644 --- a/scribus/plugins/scriptplugin/prefs_scripter.h +++ b/scribus/plugins/scriptplugin/prefs_scripter.h @@ -28,6 +28,11 @@ class Prefs_Scripter : public Prefs_Pane, Ui::Prefs_Scripter //! \brief Apply changes to prefs. Auto connected. void apply() override; + void selectPath(QListWidgetItem *c); + void addPath(); + void changePath(); + void removePath(); + protected: void setupSyntaxColors(); QColor textColor; @@ -38,6 +43,9 @@ class Prefs_Scripter : public Prefs_Pane, Ui::Prefs_Scripter QColor stringColor; QColor numberColor; + QString latestPath; + bool pathsChanged = false; + protected slots: /*! \brief All requests for color change are handled here. \author Petr Vanek diff --git a/scribus/plugins/scriptplugin/prefs_scripterbase.ui b/scribus/plugins/scriptplugin/prefs_scripterbase.ui index d077c0c12..0f07f60b1 100644 --- a/scribus/plugins/scriptplugin/prefs_scripterbase.ui +++ b/scribus/plugins/scriptplugin/prefs_scripterbase.ui @@ -40,46 +40,109 @@ <item> <widget class="Line" name="line"> <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - </widget> - </item> - <item> - <widget class="QScrollArea" name="scrollArea"> - <property name="frameShape"> - <enum>QFrame::NoFrame</enum> - </property> - <property name="frameShadow"> - <enum>QFrame::Plain</enum> - </property> - <property name="widgetResizable"> - <bool>true</bool> - </property> - <widget class="QWidget" name="scrollAreaWidgetContents"> - <property name="geometry"> - <rect> + <enum>Qt::Horizontal</enum> + </property> + </widget> + </item> + <item> + <widget class="QScrollArea" name="scrollArea"> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Plain</enum> + </property> + <property name="widgetResizable"> + <bool>true</bool> + </property> + <widget class="QWidget" name="scrollAreaWidgetContents"> + <property name="geometry"> + <rect> <x>0</x> - <y>0</y> - <width>742</width> - <height>538</height> - </rect> - </property> - <layout class="QVBoxLayout" name="verticalLayout"> - <property name="leftMargin"> - <number>0</number> - </property> - <property name="topMargin"> - <number>0</number> - </property> - <property name="rightMargin"> - <number>0</number> - </property> - <item> - <widget class="QLabel" name="extensionsTitleLabel"> - <property name="font"> - <font> - <weight>75</weight> - <bold>true</bold> + <y>0</y> + <width>678</width> + <height>570</height> + </rect> + </property> + <layout class="QVBoxLayout" name="verticalLayout"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <item> + <widget class="QLabel" name="ownScripts"> + <property name="font"> + <font> + <bold>true</bold> + </font> + </property> + <property name="text"> + <string>Own Scripts</string> + </property> + </widget> + </item> + <item> + <widget class="Line" name="line_4"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + </widget> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> + <widget class="QListWidget" name="scriptPathsListWidget"/> + </item> + <item> + <layout class="QVBoxLayout" name="verticalLayout_2"> + <item> + <widget class="QPushButton" name="changePathButton"> + <property name="text"> + <string>C&hange</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="addPathButton"> + <property name="text"> + <string>A&dd</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="removePathButton"> + <property name="text"> + <string>&Remove</string> + </property> + </widget> + </item> + <item> + <spacer name="verticalSpacer_3"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + </layout> + </item> + <item> + <widget class="QLabel" name="extensionsTitleLabel"> + <property name="font"> + <font> + <bold>true</bold> </font> </property> <property name="text"> diff --git a/scribus/plugins/scriptplugin/scriptercore.cpp b/scribus/plugins/scriptplugin/scriptercore.cpp index 103038c27..96f5c701d 100644 --- a/scribus/plugins/scriptplugin/scriptercore.cpp +++ b/scribus/plugins/scriptplugin/scriptercore.cpp @@ -70,6 +70,8 @@ ScripterCore::ScripterCore(QWidget* parent) QObject::connect(ScQApp, SIGNAL(appStarted()) , this, SLOT(runStartupScript()) ); QObject::connect(ScQApp, SIGNAL(appStarted()) , this, SLOT(slotRunPythonScript()) ); + + QObject::connect(&scriptPaths, &ScriptPaths::runScriptFile, this, &ScripterCore::runScriptFile); } ScripterCore::~ScripterCore() @@ -82,6 +84,7 @@ void ScripterCore::addToMainWindowMenu(ScribusMainWindow *mw) { m_menuMgr = mw->scrMenuMgr; m_menuMgr->createMenu("Scripter", QObject::tr("&Script")); + scriptPaths.attachToMenu(m_menuMgr); m_menuMgr->createMenu("ScribusScripts", QObject::tr("&Scribus Scripts"), "Scripter"); m_menuMgr->addMenuItemString("ScribusScripts", "Scripter"); m_menuMgr->addMenuItemString("scripterExecuteScript", "Scripter"); @@ -98,6 +101,7 @@ void ScripterCore::addToMainWindowMenu(ScribusMainWindow *mw) m_menuMgr->addMenuItemStringsToMenuBar("Scripter", m_scripterActions); m_recentScripts = m_savedRecentScripts; rebuildRecentScriptsMenu(); + scriptPaths.buildMenu(); } void ScripterCore::enableMainWindowMenu() @@ -177,6 +181,15 @@ void ScripterCore::finishScriptRun() mainWin->HaveNewDoc(); } +/** + * setup the environment for running the script, run the script and clean up the environment + */ +void ScripterCore::runScriptFile(const QString& path) +{ + slotRunScriptFile(path); + finishScriptRun(); +} + void ScripterCore::runScriptDialog() { RunScriptDialog dia( ScCore->primaryMainWindow(), m_enableExtPython ); diff --git a/scribus/plugins/scriptplugin/scriptercore.h b/scribus/plugins/scriptplugin/scriptercore.h index ceb4e68b2..15475b293 100644 --- a/scribus/plugins/scriptplugin/scriptercore.h +++ b/scribus/plugins/scriptplugin/scriptercore.h @@ -11,6 +11,7 @@ for which a new license (GPL+exception) is in place. #include "qmap.h" #include "qpointer.h" +#include "scriptpaths.h" class ScrAction; class ScribusMainWindow; @@ -34,10 +35,13 @@ public: /** @brief String representation of line of code to be passed to the Python interactive interpreter */ QString inValue; + ScriptPaths scriptPaths; + public slots: void runScriptDialog(); void StdScript(const QString& baseFilename); void RecentScript(const QString& fn); + void runScriptFile(const QString& path); void slotRunScriptFile(const QString& fileName, bool inMainInterpreter = false); void slotRunScriptFile(const QString& fileName, QStringList arguments, bool inMainInterpreter = false); void slotRunPythonScript(); // needed for running python script from CLI @@ -57,6 +61,7 @@ public slots: void runStartupScript(); void languageChange(); + // Preferences const QString & startupScript() const; bool extensionsEnabled() const; void setStartupScript(const QString& newScript); diff --git a/scribus/plugins/scriptplugin/scriptpaths.cpp b/scribus/plugins/scriptplugin/scriptpaths.cpp new file mode 100644 index 000000000..428c10b8e --- /dev/null +++ b/scribus/plugins/scriptplugin/scriptpaths.cpp @@ -0,0 +1,174 @@ +#include "scriptpaths.h" +#include "prefsmanager.h" +#include "prefsfile.h" +#include "prefscontext.h" +#include "prefstable.h" + +#include <QWidget> +#include "menumanager.h" + +ScriptPaths::ScriptPaths() +{ +} + +void ScriptPaths::saveToPrefs() const +{ + paths.saveToPrefs(); +} + +/** + * Add a Scripts sub menu to the Scripts navigation (if there is any user script). + * It will be hidden if buildMenu() detects that no scripts have been found. + */ +void ScriptPaths::attachToMenu(MenuManager* menuManager) +{ + menuManager->createMenu("OwnScripts", QObject::tr("&Scripts"), "Scripter", false, true); + menuManager->addMenuItemString("OwnScripts", "Scripter"); + this->menuManager = menuManager; +} + +void ScriptPaths::buildMenu() +{ + if (menuManager == nullptr) + return; + + updateScriptsList(); + + if (empty()) + { + menuManager->hideRemberedMenu("OwnScripts"); + return; + } + + menuManager->showRemberedMenu("OwnScripts"); + + scriptsActions.clear(); + menuManager->clearMenuStrings("OwnScripts"); + + for (const auto& scriptInfo: scriptsList) + { + // TODO: strippedName sould be unique for the whole menu (repo index + script name?)... we could use the full path... + auto scriptName = scriptInfo.name; + scriptName.replace('_', ' '); + scriptName = scriptName.first(1).toUpper() + scriptName.mid(1); + scriptsActions.insert(scriptName, new ScrAction(ScrAction::OwnScript, scriptName, QKeySequence(), this, scriptInfo.path)); + connect( + scriptsActions[scriptName], qOverload<QString>(&ScrAction::triggeredData), + this, &ScriptPaths::runScript + ); + menuManager->addMenuItemString(scriptName, "OwnScripts"); + } + + menuManager->addMenuItemStringsToRememberedMenu("OwnScripts", scriptsActions); +} + +/** + * Detect the scripts in the paths defined in the Preferences > Scripter. + * + * The following scripts are detected: + * + * - The *.py files at the root of the repository. + * - The main.py files in the directories at the root of the repository. + * - The .py files with the same name as their directory (at root level): + * the-script/the-script.py + * + * TODO: we might prefer using a QList<QPair<QString, QString>> with the name to be shown and the absolute path to the script. + */ +void ScriptPaths::updateScriptsList() +{ + scriptsList.clear(); + // TODO: how to manage duplicate file names? (in different repositories) + for (const auto& path: paths.paths) { + { + QDir scriptDirectory(QDir::toNativeSeparators(path), "*.py", QDir::Name | QDir::IgnoreCase, QDir::Files | QDir::NoSymLinks); + for (const auto& file: scriptDirectory.entryList()) + { + scriptsList.append(ScriptPathsInfo(QDir(path).filePath(file), QFileInfo{file}.baseName())); + } + } + { + QDir scriptDirectory(QDir::toNativeSeparators(path), "*", QDir::Name | QDir::IgnoreCase, QDir::Dirs | QDir::NoSymLinks); + for (const auto& directory: scriptDirectory.entryList()) + { + { + auto script = QFileInfo(QDir(path).filePath(directory + "/main.py")); + if (script.exists() || script.isFile()) + { + scriptsList.append(ScriptPathsInfo(script.absoluteFilePath(), directory)); + continue; + } + } + { + auto script = QFileInfo(QDir(path).filePath(directory + "/" + directory + ".py")); + if (script.exists() || script.isFile()) + { + scriptsList.append(ScriptPathsInfo(script.absoluteFilePath(), directory)); + } + } + } + } + } + std::sort(scriptsList.begin(), scriptsList.end()); +} + +void ScriptPaths::runScript(const QString& path) +{ + // TODO: give some sort of warning? + if (!QFileInfo(path).exists()) + return; + + emit runScriptFile(path); +} + +QStringList ScriptPaths::get() +{ + return paths.paths; +} + +void ScriptPaths::append(const QString& s) +{ + paths.paths.append(s); +} + +void ScriptPaths::remove(int i) +{ + paths.paths.remove(i); +} + +void ScriptPaths::clear() +{ + paths.paths.clear(); +} + +QString ScriptPaths::item(int i) const +{ + return paths.paths.at(i); +} + +ScriptPathsList::ScriptPathsList() +{ + PrefsContext* prefs = PrefsManager::instance().prefsFile->getPluginContext("scriptplugin"); + if (!prefs) + return; + + auto scriptPaths = prefs->getTable("scriptpaths"); + for (int i = 0; i < scriptPaths->getRowCount(); ++i) + { + paths.append(QDir::toNativeSeparators(scriptPaths->get(i, 0))); + } +} + +void ScriptPathsList::saveToPrefs() const +{ + PrefsContext* prefs = PrefsManager::instance().prefsFile->getPluginContext("scriptplugin"); + if (!prefs) + return; + + auto scriptPaths = prefs->getTable("scriptpaths"); + scriptPaths->clear(); + for (int i = 0; i < paths.count(); i++) + { + // pathListWidget->item(i)->text() + scriptPaths->set(i, 0, QDir::fromNativeSeparators(paths[i])); + } +} diff --git a/scribus/plugins/scriptplugin/scriptpaths.h b/scribus/plugins/scriptplugin/scriptpaths.h new file mode 100644 index 000000000..9002e6e1b --- /dev/null +++ b/scribus/plugins/scriptplugin/scriptpaths.h @@ -0,0 +1,74 @@ +/* +For general Scribus (>=1.3.2) copyright and licensing information please refer +to the COPYING file provided with the program. Following this notice may exist +a copyright and/or license notice that predates the release of Scribus 1.3.2 +for which a new license (GPL+exception) is in place. +*/ + +#ifndef SCRIPTPATHS_H +#define SCRIPTPATHS_H + +/** + * Allow the user to add local script to the Script menu and run them. + */ + +#include <QStringList> +#include <QPointer> +#include "scraction.h" + +class MenuManager; + +struct ScriptPathsList +{ + ScriptPathsList(); + void saveToPrefs() const; + QStringList paths; +}; + +struct ScriptPathsInfo +{ + ScriptPathsInfo(QString path, QString name): path{path}, name{name} {} + + QString path; + QString name; + + friend bool operator<(const ScriptPathsInfo& l, const ScriptPathsInfo& r) + { + return l.name < r.name; + } +}; + +class ScriptPaths : public QObject +{ + Q_OBJECT + +public: + ScriptPaths(); + void saveToPrefs() const; + + void updateScriptsList(); + void attachToMenu(MenuManager* menuManager); + void buildMenu(); + + bool empty() { return paths.paths.count() == 0; } + QStringList get(); + void append(const QString& s); + void remove (int i); + void clear (); + QString item(int i) const; + +signals: + void runScriptFile(const QString& path); + +public slots: + void runScript(const QString& name); + +private: + MenuManager* menuManager = nullptr; + QList<ScriptPathsInfo> scriptsList; + + ScriptPathsList paths; + QMap<QString, QPointer<ScrAction>> scriptsActions; +}; + +#endif diff --git a/scribus/scraction.cpp b/scribus/scraction.cpp index fde4064af..e045fa330 100644 --- a/scribus/scraction.cpp +++ b/scribus/scraction.cpp @@ -114,6 +114,8 @@ void ScrAction::triggeredToTriggeredData() emit triggeredData(data().toString()); if (m_actionType == ScrAction::RecentScript) emit triggeredData(data().toString()); + if (m_actionType == ScrAction::OwnScript) + emit triggeredData(data().toString()); if (m_actionType == ScrAction::UnicodeChar) emit triggeredUnicodeShortcut(data().toInt()); if (m_actionType == ScrAction::Layer) @@ -144,6 +146,8 @@ void ScrAction::toggledToToggledData(bool ison) emit toggledData(ison, data().toString()); if (m_actionType == ScrAction::RecentScript) emit toggledData(ison, text()); + if (m_actionType == ScrAction::OwnScript) + emit toggledData(ison, text()); if (m_actionType == ScrAction::Layer) emit toggledData(ison, data().toInt()); // no toggle for UnicodeChar diff --git a/scribus/scraction.h b/scribus/scraction.h index 48a95d8a7..eae2db59d 100644 --- a/scribus/scraction.h +++ b/scribus/scraction.h @@ -37,7 +37,7 @@ class SCRIBUS_API ScrAction : public QAction Q_OBJECT public: - enum ActionType { Normal, DataInt, DataDouble, DataQString, RecentFile, DLL, Window, RecentScript, UnicodeChar, Layer, ActionDLL, RecentPaste, ActionDLLSE }; + enum ActionType { Normal, DataInt, DataDouble, DataQString, RecentFile, DLL, Window, RecentScript, UnicodeChar, Layer, ActionDLL, RecentPaste, ActionDLLSE, OwnScript }; /*! \author Craig Bradney |
|
Its building but its a full build.. will come back to it tomorrow. Thanks |
|
it works. thanks! |
Date Modified | Username | Field | Change |
---|---|---|---|
2019-02-20 08:31 | ale | New Issue | |
2019-02-21 14:09 | aiena | Note Added: 0045908 | |
2019-02-21 14:23 | ale | Note Added: 0045909 | |
2019-02-24 06:34 | aiena | Note Added: 0045917 | |
2019-02-26 08:29 | ale | Note Added: 0045924 | |
2019-02-26 08:30 | ale | Note Added: 0045925 | |
2019-02-28 12:34 | ale | Note Added: 0045938 | |
2019-02-28 12:49 | ale | Note Added: 0045939 | |
2019-02-28 17:33 | ale | File Added: userscripts.patch | |
2019-02-28 17:33 | ale | Note Added: 0045940 | |
2019-03-01 17:18 | ale | Note Added: 0045945 | |
2019-03-04 07:07 | aiena | Note Added: 0045952 | |
2019-03-04 07:43 | ale | Note Added: 0045954 | |
2019-03-06 10:01 | aiena | Note Added: 0045968 | |
2019-03-06 10:03 | aiena | Note Added: 0045969 | |
2019-03-06 14:36 | ale | Note Added: 0045970 | |
2019-03-07 10:37 | ale | File Added: userscripts.diff | |
2019-03-07 10:37 | ale | Note Added: 0045974 | |
2019-03-07 10:38 | ale | Summary | add user's scripts to the navigation => [PATCH] add user's scripts to the navigation |
2019-03-07 10:38 | ale | Patch | No => Yes |
2019-03-07 10:38 | ale | Tag Attached: patch | |
2019-03-07 11:21 | ale | Note Added: 0045975 | |
2020-12-06 14:28 | DerekD | Note Added: 0048529 | |
2023-11-18 16:35 | ale | Note Added: 0050484 | |
2023-11-18 16:35 | ale | File Added: own-scripts-list.png | |
2023-11-18 16:35 | ale | Note Added: 0050485 | |
2023-11-18 16:35 | ale | File Added: script-scripts.png | |
2023-11-18 16:36 | ale | Note Edited: 0050485 | |
2023-11-19 10:31 | ale | Note Added: 0050489 | |
2023-11-19 10:31 | ale | File Added: item-dialog.diff | |
2023-12-17 20:43 | ale | Note Added: 0050616 | |
2024-11-12 20:48 | cbradney | Note Added: 0051569 | |
2024-11-14 09:49 | ale | Note Added: 0051574 | |
2024-11-14 10:01 | ale | Note Added: 0051575 | |
2024-11-14 10:01 | ale | File Added: own-script.diff | |
2024-11-18 21:10 | cbradney | Note Added: 0051592 | |
2024-11-19 22:21 | cbradney | Assigned To | => cbradney |
2024-11-19 22:21 | cbradney | Status | new => resolved |
2024-11-19 22:21 | cbradney | Resolution | open => fixed |
2024-11-19 22:21 | cbradney | Fixed in Version | => 1.7.0.svn |
2024-11-20 19:14 | ale | Note Added: 0051611 | |
2024-12-08 11:41 | cbradney | Status | resolved => closed |
2024-12-26 16:24 | cbradney | Relationship added | has duplicate 0010110 |