Debian Codegraph @

src/Gui/Dialogs/DlgMacroExecuteImp.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <QDesktopServices>
24 #include <QInputDialog>
25 #include <QLabel>
26 #include <QMessageBox>
27 #include <QComboBox>
28 #include <QSignalBlocker>
29 #include <QTextStream>
30 #include <QTimer>
31
32 #include <App/Document.h>
33 #include <Base/Interpreter.h>
34
35 #include "Dialogs/DlgMacroExecuteImp.h"
36 #include "ui_DlgMacroExecute.h"
37 #include "Application.h"
38 #include "BitmapFactory.h"
39 #include "Command.h"
40 #include "Dialogs/DlgCustomizeImp.h"
41 #include "Dialogs/DlgToolbarsImp.h"
42 #include "Document.h"
43 #include "EditorView.h"
44 #include "Macro.h"
45 #include "MainWindow.h"
46 #include "PythonEditor.h"
47 #include "Workbench.h"
48 #include "WorkbenchManager.h"
49
50
51 using namespace Gui;
52 using namespace Gui::Dialog;
53
54 namespace Gui
55 {
56 namespace Dialog
57 {
58 class MacroItem: public QTreeWidgetItem
59 {
60 public:
61 MacroItem(QTreeWidget* widget, bool systemwide, const QString& dirPath)
62 : QTreeWidgetItem(widget)
63 , systemWide(systemwide)
64 , dirPath(dirPath)
65 {}
66
67 /**
68 * Acts same as setText method but additionally set toolTip with text of
69 * absolute file path. There may be different macros with same names from
70 * different system paths. So it could be helpful for user to show where
71 * exactly macro is placed.
72 */
73 void setFileName(int column, const QString& text)
74 {
75 QFileInfo file(dirPath, text);
76
77 setToolTip(column, file.absoluteFilePath());
78 return QTreeWidgetItem::setText(column, text);
79 }
80
81 ~MacroItem() override = default;
82
83 bool systemWide;
84 QString dirPath;
85 };
86 } // namespace Dialog
87 } // namespace Gui
88
89
90 /* TRANSLATOR Gui::Dialog::DlgMacroExecuteImp */
91
92 /**
93 * Constructs a DlgMacroExecuteImp which is a child of 'parent', with the
94 * name 'name' and widget flags set to 'f'
95 *
96 * The dialog will by default be modeless, unless you set 'modal' to
97 * true to construct a modal dialog.
98 */
99 DlgMacroExecuteImp::DlgMacroExecuteImp(QWidget* parent, Qt::WindowFlags fl)
100 : QDialog(parent, fl)
101 , WindowParameter("Macro")
102 , ui(new Ui_DlgMacroExecute)
103 {
104 watcher = std::make_unique<PythonTracingWatcher>(this);
105 ui->setupUi(this);
106 setupConnections();
107
108 // retrieve the macro path from parameter or use the user data as default
109 {
110 QSignalBlocker blocker(ui->fileChooser);
111 std::string path = getWindowParameter()->GetASCII(
112 "MacroPath",
113 App::Application::getUserMacroDir().c_str()
114 );
115 this->macroPath = QString::fromUtf8(path.c_str());
116 ui->fileChooser->setFileName(this->macroPath);
117 }
118
119 // Fill the List box
120 QStringList labels;
121 labels << tr("Macros");
122 for (auto* listBox : {ui->userMacroListBox, ui->systemMacroListBox}) {
123 listBox->setHeaderLabels(labels);
124 listBox->header()->hide();
125 }
126 fillUpList();
127 ui->LineEditFind->setFocus();
128 ui->addonsButton->setEnabled(
129 Application::Instance->commandManager().getCommandByName("Std_AddonMgr") != nullptr
130 );
131 }
132
133 /**
134 * Destroys the object and frees any allocated resources
135 */
136 DlgMacroExecuteImp::~DlgMacroExecuteImp() = default;
137
138 void DlgMacroExecuteImp::setupConnections()
139 {
140 // clang-format off
141 connect(ui->fileChooser, &FileChooser::fileNameChanged,
142 this, &DlgMacroExecuteImp::onFileChooserFileNameChanged);
143 connect(ui->createButton, &QPushButton::clicked,
144 this, &DlgMacroExecuteImp::onCreateButtonClicked);
145 connect(ui->deleteButton, &QPushButton::clicked,
146 this, &DlgMacroExecuteImp::onDeleteButtonClicked);
147 connect(ui->editButton, &QPushButton::clicked,
148 this, &DlgMacroExecuteImp::onEditButtonClicked);
149 connect(ui->renameButton, &QPushButton::clicked,
150 this, &DlgMacroExecuteImp::onRenameButtonClicked);
151 connect(ui->duplicateButton, &QPushButton::clicked,
152 this, &DlgMacroExecuteImp::onDuplicateButtonClicked);
153 connect(ui->toolbarButton, &QPushButton::clicked,
154 this, &DlgMacroExecuteImp::onToolbarButtonClicked);
155 connect(ui->addonsButton, &QPushButton::clicked,
156 this, &DlgMacroExecuteImp::onAddonsButtonClicked);
157 connect(ui->folderButton, &QPushButton::clicked,
158 this, &DlgMacroExecuteImp::onFolderButtonClicked);
159 connect(ui->userMacroListBox, &QTreeWidget::currentItemChanged,
160 this, &DlgMacroExecuteImp::onUserMacroListBoxCurrentItemChanged);
161 connect(ui->systemMacroListBox, &QTreeWidget::currentItemChanged,
162 this, &DlgMacroExecuteImp::onSystemMacroListBoxCurrentItemChanged);
163 connect(ui->tabMacroWidget, &QTabWidget::currentChanged,
164 this, &DlgMacroExecuteImp::onTabMacroWidgetCurrentChanged);
165 connect(ui->LineEditFind, &QLineEdit::textChanged,
166 this, &DlgMacroExecuteImp::onLineEditFindTextChanged);
167 connect(ui->LineEditFindInFiles, &QLineEdit::textChanged,
168 this, &DlgMacroExecuteImp::onLineEditFindInFilesTextChanged);
169 // clang-format on
170 }
171
172 /** Take a folder and return a StringList of the filenames in it
173 * filtered by both filename *and* by content, if the user has
174 * put text in one or both of the search line edits.
175 *
176 * First filtering is done by file name, which reduces the
177 * number of files to open and read (relatively expensive operation).
178 *
179 * Then we filter by file content after reducing the number of files
180 * to open and read. But both loops are skipped if there is no text
181 * in either of the line edits.
182 *
183 * We do this as another function in order to reuse this code for
184 * doing both the User and System macro list boxes in the fillUpList() function.
185 */
186
187 QStringList DlgMacroExecuteImp::filterFiles(const QString& folder)
188 {
189 QDir dir(folder, QLatin1String("*.FCMacro *.py"));
190 QStringList unfiltered = dir.entryList(); // all .fcmacro and .py files
191 QString fileFilter = ui->LineEditFind->text(); // used to search by filename
192 QString searchText = ui->LineEditFindInFiles->text(); // used to search in file content
193
194 if (fileFilter.isEmpty() && searchText.isEmpty()) { // skip filtering if no filters
195 return unfiltered;
196 }
197 QStringList filteredByFileName;
198 if (fileFilter.isEmpty()) {
199 filteredByFileName = unfiltered; // skip the loop if no file filter
200 }
201 else {
202 QRegularExpression regexFileName(fileFilter, QRegularExpression::CaseInsensitiveOption);
203 bool isValidFileFilter = regexFileName.isValid(); // check here instead of inside the loop
204 for (auto uf : unfiltered) {
205 if (isValidFileFilter) {
206 if (regexFileName.match(uf).hasMatch()) {
207 filteredByFileName.append(uf);
208 }
209 }
210 else { // not valid, so do a simple text search
211 if (uf.contains(fileFilter, Qt::CaseInsensitive)) {
212 filteredByFileName.append(uf);
213 }
214 }
215 }
216 }
217
218 if (searchText.isEmpty()) { // skip reading file contents if no find in file filter
219 return filteredByFileName;
220 }
221
222 QRegularExpression regexContent(searchText, QRegularExpression::CaseInsensitiveOption);
223 bool isValidContentFilter = regexContent.isValid();
224 QStringList filteredByContent;
225 for (auto fn : filteredByFileName) {
226 const QString& fileName = fn;
227 QString filePath = dir.filePath(fileName);
228 QFile file(filePath);
229 if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
230 QTextStream in(&file);
231 QString fileContent = in.readAll();
232 if (isValidContentFilter) {
233 if (regexContent.match(fileContent).hasMatch()) {
234 filteredByContent.append(fileName);
235 }
236 }
237 else {
238 if (fileContent.contains(searchText, Qt::CaseInsensitive)) {
239 filteredByContent.append(fileName);
240 }
241 }
242 file.close();
243 }
244 }
245 return filteredByContent;
246 }
247
248 /**
249 * Fills up the list with macro files found in the specified location
250 * that have been filtered by both filename and by content
251 */
252 void DlgMacroExecuteImp::fillUpListForDir(const QString& dirPath, bool systemWide)
253 {
254 QStringList filteredByContent = this->filterFiles(dirPath);
255 auto* macroListBox = systemWide ? ui->systemMacroListBox : ui->userMacroListBox;
256 macroListBox->clear();
257 for (auto& fn : filteredByContent) {
258 auto item = new MacroItem(macroListBox, systemWide, dirPath);
259 item->setFileName(0, fn);
260 }
261 }
262
263 /**
264 * Fills up the list with macro files found in all system paths and specified by
265 * user location that have been filtered by both filename and by content
266 */
267 void DlgMacroExecuteImp::fillUpList()
268 {
269 fillUpListForDir(this->macroPath, false);
270
271 QString dirstr = QString::fromStdString(App::Application::getHomePath())
272 + QStringLiteral("Macro");
273 fillUpListForDir(dirstr, true);
274
275 auto& config = App::Application::Config();
276 auto additionalMacros = config.find("AdditionalMacroPaths");
277 if (additionalMacros != config.end()) {
278 QString dirsstrs = QString::fromStdString(additionalMacros->second);
279 QStringList dirs = dirsstrs.split(QChar::fromLatin1(';'));
280 for (const auto& dirstr : dirs) {
281 fillUpListForDir(dirstr, true);
282 }
283 }
284 }
285
286
287 /**
288 * Selects a macro file in the list view.
289 */
290 void DlgMacroExecuteImp::onUserMacroListBoxCurrentItemChanged(QTreeWidgetItem* item)
291 {
292 if (item) {
293 ui->LineEditMacroName->setText(item->text(0));
294
295 ui->executeButton->setEnabled(true);
296 ui->deleteButton->setEnabled(true);
297 ui->toolbarButton->setEnabled(true);
298 ui->createButton->setEnabled(true);
299 ui->editButton->setEnabled(true);
300 ui->renameButton->setEnabled(true);
301 ui->duplicateButton->setEnabled(true);
302 }
303 else {
304 ui->executeButton->setEnabled(false);
305 ui->deleteButton->setEnabled(false);
306 ui->toolbarButton->setEnabled(false);
307 ui->createButton->setEnabled(true);
308 ui->editButton->setEnabled(false);
309 ui->renameButton->setEnabled(false);
310 ui->duplicateButton->setEnabled(false);
311 }
312 }
313
314 void DlgMacroExecuteImp::onLineEditFindTextChanged(const QString& text)
315 {
316 Q_UNUSED(text);
317 this->fillUpList();
318 }
319
320 void DlgMacroExecuteImp::onLineEditFindInFilesTextChanged(const QString& text)
321 {
322 Q_UNUSED(text);
323 this->fillUpList();
324 }
325
326 void DlgMacroExecuteImp::onSystemMacroListBoxCurrentItemChanged(QTreeWidgetItem* item)
327 {
328 if (item) {
329 ui->LineEditMacroName->setText(item->text(0));
330
331 ui->executeButton->setEnabled(true);
332 ui->deleteButton->setEnabled(false);
333 ui->toolbarButton->setEnabled(false);
334 ui->createButton->setEnabled(false);
335 ui->editButton->setEnabled(true); // look but don't touch
336 ui->renameButton->setEnabled(false);
337 ui->duplicateButton->setEnabled(false);
338 }
339 else {
340 ui->executeButton->setEnabled(false);
341 ui->deleteButton->setEnabled(false);
342 ui->toolbarButton->setEnabled(false);
343 ui->createButton->setEnabled(false);
344 ui->editButton->setEnabled(false);
345 ui->renameButton->setEnabled(false);
346 ui->duplicateButton->setEnabled(false);
347 }
348 }
349
350 void DlgMacroExecuteImp::onTabMacroWidgetCurrentChanged(int index)
351 {
352 QTreeWidgetItem* item;
353
354 auto* macroListBox = index == 0 ? ui->userMacroListBox : ui->systemMacroListBox;
355 item = macroListBox->currentItem();
356 ui->executeButton->setEnabled(item);
357 ui->deleteButton->setEnabled(item);
358 ui->toolbarButton->setEnabled(item);
359 ui->createButton->setEnabled(item);
360 ui->editButton->setEnabled(item);
361 ui->renameButton->setEnabled(item);
362 ui->duplicateButton->setEnabled(item);
363
364 ui->LineEditMacroName->setText(item ? item->text(0) : QString());
365 }
366
367 /**
368 * Executes the selected macro file.
369 */
370 void DlgMacroExecuteImp::accept()
371 {
372 QTreeWidgetItem* item;
373
374 int index = ui->tabMacroWidget->currentIndex();
375 auto* macroListBox = index == 0 ? ui->userMacroListBox : ui->systemMacroListBox;
376 item = macroListBox->currentItem();
377 if (!item) {
378 return;
379 }
380
381 QDialog::accept();
382
383 auto mitem = static_cast<MacroItem*>(item);
384
385 QDir dir(mitem->dirPath);
386 QFileInfo fi(dir, item->text(0));
387 try {
388 getMainWindow()->setCursor(Qt::WaitCursor);
389 PythonTracingLocker tracelock(watcher->getTrace());
390
391 getMainWindow()->appendRecentMacro(fi.filePath());
392 Application::Instance->macroManager()->run(Gui::MacroManager::File, fi.filePath().toUtf8());
393 // after macro run recalculate the document
394 if (Application::Instance->activeDocument()) {
395 Application::Instance->activeDocument()->getDocument()->recompute();
396 }
397 getMainWindow()->unsetCursor();
398 }
399 catch (const Base::SystemExitException&) {
400 // handle SystemExit exceptions
401 Base::PyGILStateLocker locker;
402 Base::PyException e;
403 e.reportException();
404 getMainWindow()->unsetCursor();
405 }
406 }
407
408 /**
409 * Specify the location of your macro files. The default location is FreeCAD's home path.
410 */
411 void DlgMacroExecuteImp::onFileChooserFileNameChanged(const QString& fn)
412 {
413 if (!fn.isEmpty()) {
414 this->macroPath = fn;
415 std::filesystem::path chosenPath(fn.toStdString());
416 if (chosenPath.filename().empty()) {
417 chosenPath = chosenPath.parent_path();
418 }
419 std::filesystem::path userMacroDir(App::Application::getUserMacroDir());
420 if (userMacroDir.filename().empty()) {
421 userMacroDir = userMacroDir.parent_path();
422 }
423 if (chosenPath != userMacroDir) {
424 // Save the path in the parameters, but only if it is NOT the default value
425 getWindowParameter()->SetASCII("MacroPath", fn.toUtf8());
426 }
427 else {
428 // If the user specifically chose the default path, actually remove the setting (this
429 // could happen if the user was trying to "undo" setting a custom path).
430 getWindowParameter()->RemoveASCII("MacroPath");
431 }
432 // fill the list box
433 fillUpList();
434 }
435 }
436
437 /**
438 * Opens the macro file in an editor.
439 */
440 void DlgMacroExecuteImp::onEditButtonClicked()
441 {
442 QTreeWidgetItem* item = nullptr;
443
444 int index = ui->tabMacroWidget->currentIndex();
445 auto* macroListBox = index == 0 ? ui->userMacroListBox : ui->systemMacroListBox;
446 item = macroListBox->currentItem();
447 if (!item) {
448 return;
449 }
450
451 auto mitem = static_cast<MacroItem*>(item);
452 QDir dir(mitem->dirPath);
453
454 QString file = QStringLiteral("%1/%2").arg(dir.absolutePath(), item->text(0));
455 auto editor = new PythonEditor();
456 editor->setWindowIcon(Gui::BitmapFactory().iconFromTheme("applications-python"));
457 auto edit = new PythonEditorView(editor, getMainWindow());
458 edit->setDisplayName(PythonEditorView::FileName);
459 edit->open(file);
460 edit->resize(400, 300);
461 getMainWindow()->addWindow(edit);
462 getMainWindow()->appendRecentMacro(file);
463
464 if (mitem->systemWide) {
465 editor->setReadOnly(true);
466 QString shownName;
467 shownName = QStringLiteral("%1[*] - [%2]").arg(item->text(0), tr("Read-Only"));
468 edit->setWindowTitle(shownName);
469 }
470 close();
471 }
472
473 /** Creates a new macro file. */
474 void DlgMacroExecuteImp::onCreateButtonClicked()
475 {
476 // query file name
477 bool replaceSpaces = App::GetApplication()
478 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
479 ->GetBool("ReplaceSpaces", true);
480 App::GetApplication()
481 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
482 ->SetBool("ReplaceSpaces", replaceSpaces); // create parameter
483
484 QString fn = QInputDialog::getText(
485 this,
486 tr("Macro file"),
487 tr("Enter a file name:"),
488 QLineEdit::Normal,
489 QString(),
490 nullptr,
491 Qt::MSWindowsFixedSizeDialogHint
492 );
493
494 if (replaceSpaces) {
495 fn = fn.replace(QStringLiteral(" "), QStringLiteral("_"));
496 }
497
498 if (!fn.isEmpty()) {
499 QString suffix = QFileInfo(fn).suffix().toLower();
500 if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")) {
501 fn += QLatin1String(".FCMacro");
502 }
503 QDir dir(this->macroPath);
504 // create the macroPath if nonexistent
505 if (!dir.exists()) {
506 dir.mkpath(this->macroPath);
507 }
508 QFileInfo fi(dir, fn);
509 if (fi.exists() && fi.isFile()) {
510 QMessageBox::warning(
511 this,
512 tr("Existing file"),
513 tr("'%1'.\nThis file already exists.").arg(fi.fileName())
514 );
515 }
516 else {
517 QFile file(fi.absoluteFilePath());
518 if (!file.open(QFile::WriteOnly)) {
519 QMessageBox::warning(
520 this,
521 tr("Cannot create file"),
522 tr("Creation of file '%1' failed.").arg(fi.absoluteFilePath())
523 );
524 return;
525 }
526 file.close();
527 auto editor = new PythonEditor();
528 editor->setWindowIcon(Gui::BitmapFactory().iconFromTheme("applications-python"));
529 auto edit = new PythonEditorView(editor, getMainWindow());
530 edit->open(fi.absoluteFilePath());
531 getMainWindow()->appendRecentMacro(fi.absoluteFilePath());
532 edit->setWindowTitle(QStringLiteral("%1[*]").arg(fn));
533 edit->resize(400, 300);
534 getMainWindow()->addWindow(edit);
535 close();
536 }
537 }
538 }
539
540 /** Deletes the selected macro file from your harddisc. */
541 void DlgMacroExecuteImp::onDeleteButtonClicked()
542 {
543 int index = ui->tabMacroWidget->currentIndex();
544 auto* macroListBox = index == 0 ? ui->userMacroListBox : ui->systemMacroListBox;
545
546 auto* item = dynamic_cast<MacroItem*>(macroListBox->currentItem());
547 if (!item) {
548 return;
549 }
550
551 if (item->systemWide) {
552 QMessageBox::critical(
553 Gui::getMainWindow(),
554 QObject::tr("Delete macro"),
555 QObject::tr("Not allowed to delete system-wide macros")
556 );
557 return;
558 }
559
560 QString fn = item->text(0);
561 auto ret = QMessageBox::question(
562 this,
563 tr("Delete macro"),
564 tr("Delete the macro '%1'?").arg(fn),
565 QMessageBox::Yes | QMessageBox::No,
566 QMessageBox::No
567 );
568 if (ret == QMessageBox::Yes) {
569 QDir dir(this->macroPath);
570 dir.remove(fn);
571 int index = macroListBox->indexOfTopLevelItem(item);
572 macroListBox->takeTopLevelItem(index);
573 delete item;
574 }
575 }
576
577 /**
578 * Walk user through process of adding macro to global custom toolbar
579 * We create a custom customize dialog with instructions embedded
580 * within the dialog itself for the user, and the buttons to push in red text
581 * There are 2 dialogs we need to create: the macros dialog and the
582 * toolbar dialog.
583 */
584
585 void DlgMacroExecuteImp::onToolbarButtonClicked()
586 {
587 /**
588 * advise user of what we are doing, offer chance to cancel
589 * unless user already said not to show this messagebox again
590 **/
591
592 bool showAgain = App::GetApplication()
593 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
594 ->GetBool("ShowWalkthroughMessage", true);
595 if (showAgain) {
596 QMessageBox msgBox(this);
597 QAbstractButton* doNotShowAgainButton
598 = msgBox.addButton(tr("Do not show again"), QMessageBox::YesRole);
599 msgBox.setText(tr("Guided Walkthrough"));
600 msgBox.setObjectName(QStringLiteral("macroGuideWalkthrough"));
601 msgBox.setInformativeText(tr("This will guide you in setting up this macro in a custom \
602 global toolbar. Instructions will be in red text inside the dialog.\n\
603 \n\
604 Note: your changes will be applied when you next switch workbenches\n"));
605 msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
606 msgBox.setDefaultButton(QMessageBox::Ok);
607 int result = msgBox.exec();
608 if (result == QMessageBox::Cancel) {
609 return;
610 }
611 if (msgBox.clickedButton() == doNotShowAgainButton) {
612 App::GetApplication()
613 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
614 ->SetBool("ShowWalkthroughMessage", false);
615 }
616 }
617
618 QTreeWidgetItem* item = ui->userMacroListBox->currentItem();
619 if (!item) {
620 return;
621 }
622
623 QString fn = item->text(0);
624 QString bareFileName = QFileInfo(fn).baseName(); // for use as default menu text (filename
625 // without extension)
626
627 /** check if user already has custom toolbar, so we can tailor instructions accordingly **/
628 bool hasCustomToolbar = true;
629 if (App::GetApplication()
630 .GetParameterGroupByPath("User parameter:BaseApp/Workbench/Global/Toolbar")
631 ->GetGroups()
632 .empty()) {
633 hasCustomToolbar = false;
634 }
635
636 /** check if user already has this macro command created, if so skip dialog 1 **/
637 bool hasMacroCommand = false;
638 QString macroMenuText;
639 CommandManager& cCmdMgr = Application::Instance->commandManager();
640 std::vector<Command*> aCmds = cCmdMgr.getGroupCommands("Macros");
641 for (const auto& aCmd : aCmds) {
642 auto mc = dynamic_cast<MacroCommand*>(aCmd);
643 if (mc && fn.compare(QLatin1String(mc->getScriptName())) == 0) {
644 hasMacroCommand = true;
645 macroMenuText = QString::fromLatin1(mc->getMenuText());
646 }
647 }
648
649 QTabWidget* tabWidget = nullptr;
650
651 if (!hasMacroCommand) {
652 /** first the custom macros page dialog **/
653 Gui::Dialog::DlgCustomizeImp dlg(this);
654
655 /** title is normally "Customize" **/
656 dlg.setWindowTitle(tr("Walkthrough, Dialog 1 of 2"));
657
658 tabWidget = dlg.findChild<QTabWidget*>(QStringLiteral("Gui__Dialog__TabWidget"));
659 if (!tabWidget) {
660 std::cerr << "Toolbar walkthrough error: Unable to find tabwidget" << std::endl;
661 return;
662 }
663
664 auto setupCustomMacrosPage = tabWidget->findChild<QWidget*>(
665 QStringLiteral("Gui__Dialog__DlgCustomActions")
666 );
667 if (!setupCustomMacrosPage) {
668 std::cerr << "Toolbar walkthrough error: Unable to find setupCustomMacrosPage"
669 << std::endl;
670 return;
671 }
672 tabWidget->setCurrentWidget(setupCustomMacrosPage);
673
674 auto groupBox7 = setupCustomMacrosPage->findChild<QGroupBox*>(QStringLiteral("GroupBox7"));
675 if (!groupBox7) {
676 Base::Console().warning("Toolbar walkthrough: Unable to find groupBox7\n");
677 // just warn when not a fatal error
678 }
679 else {
680 /** normally the groupbox title is "Setup Custom Macros", but we change it here **/
681 groupBox7->setTitle(
682 tr("Walkthrough instructions: Fill in missing fields (optional) "
683 "then click Add, then Close")
684 );
685 groupBox7->setStyleSheet(QStringLiteral("QGroupBox::title {color:red}"));
686 }
687
688 auto buttonAddAction = setupCustomMacrosPage->findChild<QPushButton*>(
689 QStringLiteral("buttonAddAction")
690 );
691 if (!buttonAddAction) {
692 Base::Console().warning("Toolbar walkthrough: Unable to find buttonAddAction\n");
693 }
694 else {
695 buttonAddAction->setStyleSheet(QStringLiteral("color:red"));
696 }
697
698 auto macroListBox = setupCustomMacrosPage->findChild<QComboBox*>(
699 QStringLiteral("actionMacros")
700 );
701 if (!macroListBox) {
702 Base::Console().warning("Toolbar walkthrough: Unable to find actionMacros combo box\n");
703 }
704 else {
705 int macroIndex = macroListBox->findText(fn); // fn is the macro filename
706 macroListBox->setCurrentIndex(macroIndex); // select it for the user so they don't have to
707 }
708
709 auto menuText = setupCustomMacrosPage->findChild<QLineEdit*>(QStringLiteral("actionMenu"));
710 if (!menuText) {
711 Base::Console().warning("Toolbar walkthrough: Unable to find actionMenu menuText\n");
712 }
713 else {
714 menuText->setText(bareFileName); // user can fill in other fields, e.g. tooltip
715 }
716
717 dlg.exec();
718 }
719
720 /** now for the toolbar selection dialog **/
721
722 Gui::Dialog::DlgCustomizeImp dlg(this);
723 dlg.setWindowTitle(
724 hasMacroCommand ? tr("Walkthrough, Dialog 1 of 1") : tr("Walkthrough, Dialog 2 of 2")
725 );
726
727 tabWidget = nullptr;
728 tabWidget = dlg.findChild<QTabWidget*>(QStringLiteral("Gui__Dialog__TabWidget"));
729 if (!tabWidget) {
730 std::cerr << "Toolbar walkthrough: Unable to find tabWidget Gui__Dialog__TabWidget"
731 << std::endl;
732 return;
733 }
734
735 auto setupToolbarPage = tabWidget->findChild<DlgCustomToolbars*>(
736 QStringLiteral("Gui__Dialog__DlgCustomToolbars")
737 );
738 if (!setupToolbarPage) {
739 std::cerr
740 << "Toolbar walkthrough: Unable to find setupToolbarPage Gui__Dialog__DlgCustomToolbars"
741 << std::endl;
742 return;
743 }
744
745 tabWidget->setCurrentWidget(setupToolbarPage);
746 auto moveActionRightButton = setupToolbarPage->findChild<QPushButton*>(
747 QStringLiteral("moveActionRightButton")
748 );
749 if (!moveActionRightButton) {
750 Base::Console().warning("Toolbar walkthrough: Unable to find moveActionRightButton\n");
751 }
752 else {
753 moveActionRightButton->setStyleSheet(QStringLiteral("background-color: red"));
754 }
755 /** tailor instructions depending on whether user already has custom toolbar created
756 * if not, they need to click New button to create one first
757 **/
758
759 QString instructions2
760 = tr("Walkthrough instructions: Select macro from list, then click right arrow button (->), then Close.");
761 auto workbenchBox = setupToolbarPage->findChild<QComboBox*>(QStringLiteral("workbenchBox"));
762 if (!workbenchBox) {
763 Base::Console().warning("Toolbar walkthrough: Unable to find workbenchBox\n");
764 }
765 else {
766 /** find the Global workbench and select it for the user **/
767
768 int globalIdx = workbenchBox->findData(QStringLiteral("Global"));
769 if (globalIdx != -1) {
770 workbenchBox->setCurrentIndex(globalIdx);
771 setupToolbarPage->activateWorkbenchBox(globalIdx);
772 }
773 else {
774 Base::Console().warning("Toolbar walkthrough: Unable to find Global workbench\n");
775 }
776
777 if (!hasCustomToolbar) {
778 auto newButton = setupToolbarPage->findChild<QPushButton*>(QStringLiteral("newButton"));
779 if (!newButton) {
780 Base::Console().warning("Toolbar walkthrough: Unable to find newButton\n");
781 }
782 else {
783 newButton->setStyleSheet(QStringLiteral("color:red"));
784 instructions2 = tr(
785 "Walkthrough instructions: Click New, select macro, then right arrow (->) "
786 "button, then Close."
787 );
788 }
789 }
790 }
791 /** "label" normally says "Note: the changes become active the next time you load the
792 * appropriate workbench" **/
793
794 auto label = setupToolbarPage->findChild<QLabel*>(QStringLiteral("label"));
795 if (!label) {
796 Base::Console().warning("Toolbar walkthrough: Unable to find label\n");
797 }
798 else {
799 label->setText(instructions2);
800 label->setStyleSheet(QStringLiteral("color:red"));
801 }
802
803 /** find Macros category and select it for the user **/
804 auto categoryBox = setupToolbarPage->findChild<QComboBox*>(QStringLiteral("categoryBox"));
805 if (!categoryBox) {
806 Base::Console().warning("Toolbar walkthrough: Unable to find categoryBox\n");
807 }
808 else {
809 int macrosIdx = categoryBox->findText(tr("Macros"));
810 if (macrosIdx != -1) {
811 categoryBox->setCurrentIndex(macrosIdx);
812 }
813 else {
814 Base::Console().warning("Toolbar walkthrough: Unable to find Macros in categoryBox\n");
815 }
816 }
817
818 /** expand custom toolbar items **/
819 auto toolbarTreeWidget = setupToolbarPage->findChild<QTreeWidget*>(
820 QStringLiteral("toolbarTreeWidget")
821 );
822 if (!toolbarTreeWidget) {
823 Base::Console().warning("Toolbar walkthrough: Unable to find toolbarTreeWidget\n");
824 }
825 else {
826 toolbarTreeWidget->expandAll();
827 }
828
829 /** preselect macro command for user after a short delay to allow time for the
830 tree widget to populate all the actions
831 **/
832 QTimer::singleShot(500, [=]() {
833 auto commandTreeWidget = setupToolbarPage->findChild<QTreeWidget*>(
834 QStringLiteral("commandTreeWidget")
835 );
836 if (!commandTreeWidget) {
837 Base::Console().warning("Toolbar walkthrough: Unable to find commandTreeWidget\n");
838 }
839 else {
840 if (!hasMacroCommand) { // will be the last in the list, the one just created
841 commandTreeWidget->setCurrentItem(
842 commandTreeWidget->topLevelItem(commandTreeWidget->topLevelItemCount() - 1)
843 );
844 commandTreeWidget->scrollToItem(commandTreeWidget->currentItem());
845 }
846 else { // preselect it for the user (will be the macro menu text)
847 QList<QTreeWidgetItem*> items = commandTreeWidget->findItems(
848 macroMenuText,
849 Qt::MatchFixedString | Qt::MatchWrap,
850 1
851 );
852 if (!items.empty()) {
853 commandTreeWidget->setCurrentItem(items[0]);
854 commandTreeWidget->scrollToItem(commandTreeWidget->currentItem());
855 }
856 }
857 }
858 });
859 dlg.exec();
860 // refresh toolbar so new icon shows up immediately
861 Workbench* active = Gui::WorkbenchManager::instance()->active();
862 if (active) {
863 active->activate();
864 }
865 }
866
867
868 /**
869 * renames the selected macro
870 */
871 void DlgMacroExecuteImp::onRenameButtonClicked()
872 {
873 QDir dir;
874 QTreeWidgetItem* item = nullptr;
875
876 int index = ui->tabMacroWidget->currentIndex();
877 if (index == 0) { // user-specific
878 item = ui->userMacroListBox->currentItem();
879 dir.setPath(this->macroPath);
880 }
881
882 if (!item) {
883 return;
884 }
885
886 bool replaceSpaces = App::GetApplication()
887 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
888 ->GetBool("ReplaceSpaces", true);
889 App::GetApplication()
890 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
891 ->SetBool("ReplaceSpaces", replaceSpaces); // create parameter
892
893 QString oldName = item->text(0);
894 QFileInfo oldfi(dir, oldName);
895 QFile oldfile(oldfi.absoluteFilePath());
896
897 // query new name
898 QString fn = QInputDialog::getText(
899 this,
900 tr("Renaming Macro File"),
901 tr("Enter new name"),
902 QLineEdit::Normal,
903 oldName,
904 nullptr,
905 Qt::MSWindowsFixedSizeDialogHint
906 );
907
908 if (replaceSpaces) {
909 fn = fn.replace(QStringLiteral(" "), QStringLiteral("_"));
910 }
911
912 if (!fn.isEmpty() && fn != oldName) {
913 QString suffix = QFileInfo(fn).suffix().toLower();
914 if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")) {
915 fn += QLatin1String(".FCMacro");
916 }
917 QFileInfo fi(dir, fn);
918 // check if new name exists
919 if (fi.exists()) {
920 QMessageBox::warning(
921 this,
922 tr("Existing file"),
923 tr("'%1'\n already exists.").arg(fi.absoluteFilePath())
924 );
925 }
926 else if (!oldfile.rename(fi.absoluteFilePath())) {
927 QMessageBox::warning(
928 this,
929 tr("Rename Failed"),
930 tr("Failed to rename to '%1'.\nPerhaps a file permission error?")
931 .arg(fi.absoluteFilePath())
932 );
933 }
934 else {
935 // keep the item selected although it's not necessarily in alphabetic order
936 item->setText(0, fn);
937 ui->LineEditMacroName->setText(fn);
938 }
939 }
940 }
941
942 /**Duplicates selected macro
943 * New file has same name as original but with "@" and 3-digit number appended
944 * Begins with "@001" and increments until available name is found
945 * "MyMacro.FCMacro" becomes "[email protected]"
946 * "[email protected]" becomes "[email protected]" unless there is
947 * no already existing "[email protected]"
948 */
949 void DlgMacroExecuteImp::onDuplicateButtonClicked()
950 {
951 QDir dir;
952 QTreeWidgetItem* item = nullptr;
953
954 // When duplicating a macro we can either begin trying to find a unique name with @001 or begin
955 // with the current @NNN if applicable
956
957 bool from001 = App::GetApplication()
958 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
959 ->GetBool("DuplicateFrom001", false);
960 App::GetApplication()
961 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
962 ->SetBool("DuplicateFrom001", from001); // create parameter
963
964 // A user may wish to add a note to end of the filename when duplicating
965 // example: [email protected]_bug_in_dialog.FCMacro
966 // and then when duplicating to have the extra note removed so the suggested new name is:
967 // [email protected] instead of [email protected]_bug_in_dialog.FCMacro since the new duplicate
968 // will be given a new note
969
970 bool ignoreExtra = App::GetApplication()
971 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
972 ->GetBool("DuplicateIgnoreExtraNote", false);
973 App::GetApplication()
974 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
975 ->SetBool("DuplicateIgnoreExtraNote", ignoreExtra); // create parameter
976
977 // when creating a note it will be convenient to convert spaces to underscores if the user
978 // desires this behavior
979
980 bool replaceSpaces = App::GetApplication()
981 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
982 ->GetBool("ReplaceSpaces", true);
983 App::GetApplication()
984 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
985 ->SetBool("ReplaceSpaces", replaceSpaces); // create parameter
986
987 int index = ui->tabMacroWidget->currentIndex();
988 if (index == 0) { // user-specific
989 item = ui->userMacroListBox->currentItem();
990 dir.setPath(this->macroPath);
991 }
992
993 if (!item) {
994 return;
995 }
996
997 QString oldName = item->text(0);
998 QFileInfo oldfi(dir, oldName);
999 QFile oldfile(oldfi.absoluteFilePath());
1000 QString completeSuffix = oldfi.completeSuffix(); // everything after the first "."
1001 QString extraNote = completeSuffix.left(completeSuffix.size() - oldfi.suffix().size());
1002 QString baseName = oldfi.baseName(); // everything before first "."
1003 QString neutralSymbol = QStringLiteral("@");
1004 QString last3 = baseName.right(3);
1005 bool ok = true; // was conversion to int successful?
1006 int nLast3 = last3.toInt(&ok);
1007 last3 = QStringLiteral("001"); // increment beginning with 001 unless from001 = false
1008 if (ok) {
1009 // last3 were all digits, so we strip them from the base name
1010 if (baseName.size() > 3) { // if <= 3 leave be (e.g. 2.py becomes [email protected])
1011 if (!from001) {
1012 last3 = baseName.right(3); // use these instead of 001
1013 }
1014 baseName = baseName.left(baseName.size() - 3); // strip digits
1015 if (baseName.endsWith(neutralSymbol)) {
1016 baseName = baseName.left(baseName.size() - 1); // trim the "@", will be added back later
1017 }
1018 }
1019 }
1020 // at this point baseName = the base name without any digits, e.g. "MyMacro"
1021 // neutralSymbol = "@"
1022 // last3 is a string representing 3 digits, always "001"
1023 // unless from001 = false, in which case we begin with previous numbers
1024 // completeSuffix = FCMacro or py or FCMacro.py or else suffix will become FCMacro below
1025 // if ignoreExtra any extra notes added between @NN. and .FCMacro will be ignored
1026 // when suggesting a new filename
1027
1028 if (ignoreExtra && !extraNote.isEmpty()) {
1029 nLast3++;
1030 last3 = QString::number(nLast3);
1031 while (last3.size() < 3) {
1032 last3.prepend(QStringLiteral("0")); // pad 0's if needed
1033 }
1034 }
1035
1036
1037 QString oldNameDigitized = baseName + neutralSymbol + last3 + QStringLiteral(".")
1038 + completeSuffix;
1039 QFileInfo fi(dir, oldNameDigitized);
1040
1041
1042 // increment until we find available name with smallest digits
1043 // test from "001" through "999", then give up and let user enter name of choice
1044
1045 while (fi.exists()) {
1046 nLast3 = last3.toInt() + 1;
1047 if (nLast3 >= 1000) { // avoid infinite loop, 999 files will have to be enough
1048 break;
1049 }
1050 last3 = QString::number(nLast3);
1051 while (last3.size() < 3) {
1052 last3.prepend(QStringLiteral("0")); // pad 0's if needed
1053 }
1054 oldNameDigitized = baseName + neutralSymbol + last3 + QStringLiteral(".") + completeSuffix;
1055 fi = QFileInfo(dir, oldNameDigitized);
1056 }
1057
1058 if (ignoreExtra && !extraNote.isEmpty()) {
1059 oldNameDigitized = oldNameDigitized.remove(extraNote);
1060 }
1061
1062 // give user a chance to pick a different name from digitized name suggested
1063 QString fn = QInputDialog::getText(
1064 this,
1065 tr("Duplicate Macro"),
1066 tr("Enter new name"),
1067 QLineEdit::Normal,
1068 oldNameDigitized,
1069 nullptr,
1070 Qt::MSWindowsFixedSizeDialogHint
1071 );
1072 if (replaceSpaces) {
1073 fn = fn.replace(QStringLiteral(" "), QStringLiteral("_"));
1074 }
1075 if (!fn.isEmpty() && fn != oldName) {
1076 QString suffix = QFileInfo(fn).suffix().toLower();
1077 if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")) {
1078 fn += QLatin1String(".FCMacro");
1079 }
1080 QFileInfo fi(dir, fn);
1081 // check again if new name exists in case user changed it
1082 if (fi.exists()) {
1083 QMessageBox::warning(
1084 this,
1085 tr("Existing file"),
1086 tr("'%1'\n already exists.").arg(fi.absoluteFilePath())
1087 );
1088 }
1089 else if (!oldfile.copy(fi.absoluteFilePath())) {
1090 QMessageBox::warning(
1091 this,
1092 tr("Duplicate Failed"),
1093 tr("Failed to duplicate to '%1'.\nPerhaps a file permission error?")
1094 .arg(fi.absoluteFilePath())
1095 );
1096 }
1097
1098 this->fillUpList(); // repopulate list to show new file
1099 }
1100 }
1101
1102 /**
1103 * convenience link button to open tools -> addon manager
1104 * from within macro dialog
1105 */
1106 void DlgMacroExecuteImp::onAddonsButtonClicked()
1107 {
1108 CommandManager& rMgr = Application::Instance->commandManager();
1109 rMgr.runCommandByName("Std_AddonMgr");
1110 this->fillUpList();
1111 }
1112
1113 /**
1114 * convenience link button to open folder with macros
1115 * from within macro dialog
1116 */
1117 void DlgMacroExecuteImp::onFolderButtonClicked()
1118 {
1119 QString path = QString::fromStdString(App::Application::getUserMacroDir());
1120 QUrl url = QUrl::fromLocalFile(path);
1121 QDesktopServices::openUrl(url);
1122 }
1123 #include "moc_DlgMacroExecuteImp.cpp"