Debian Codegraph @

src/Gui/CommandDoc.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 <Inventor/nodes/SoCamera.h>
24 #include <QApplication>
25 #include <QCheckBox>
26 #include <QClipboard>
27 #include <QDateTime>
28 #include <QMessageBox>
29 #include <QTextStream>
30 #include <QTreeWidgetItem>
31
32 #include <boost/regex.hpp>
33 #include <boost/algorithm/string/replace.hpp>
34
35 #include <App/AutoTransaction.h>
36 #include <App/Document.h>
37 #include <App/DocumentObject.h>
38 #include <App/Expression.h>
39 #include <App/GeoFeature.h>
40 #include <Base/Exception.h>
41 #include <Base/FileInfo.h>
42 #include <Base/Stream.h>
43 #include <Base/Tools.h>
44
45 #include "Action.h"
46 #include "Application.h"
47 #include "BitmapFactory.h"
48 #include "Command.h"
49 #include "Control.h"
50 #include "DockWindowManager.h"
51 #include "FileDialog.h"
52 #include "MainWindow.h"
53 #include "Selection.h"
54 #include "Dialogs/DlgObjectSelection.h"
55 #include "Dialogs/DlgProjectInformationImp.h"
56 #include "Dialogs/DlgProjectUtility.h"
57 #include "GraphvizView.h"
58 #include "ManualAlignment.h"
59 #include "MergeDocuments.h"
60 #include "Navigation/NavigationStyle.h"
61 #include "Placement.h"
62 #include "Tools.h"
63 #include "Transform.h"
64 #include "View3DInventor.h"
65 #include "View3DInventorViewer.h"
66 #include "ViewProvider.h"
67 #include "WaitCursor.h"
68
69 FC_LOG_LEVEL_INIT("Command", false)
70
71 using namespace Gui;
72
73
74 //===========================================================================
75 // Std_Open
76 //===========================================================================
77
78 DEF_STD_CMD(StdCmdOpen)
79
80 StdCmdOpen::StdCmdOpen()
81 : Command("Std_Open")
82 {
83 // setting the
84 sGroup = "File";
85 sMenuText = QT_TR_NOOP("&Open…");
86 sToolTipText = QT_TR_NOOP("Opens a document or imports files");
87 sWhatsThis = "Std_Open";
88 sStatusTip = sToolTipText;
89 sPixmap = "document-open";
90 sAccel = keySequenceToAccel(QKeySequence::Open);
91 eType = NoTransaction;
92 }
93
94 void StdCmdOpen::activated(int iMsg)
95 {
96 Q_UNUSED(iMsg);
97
98 // fill the list of registered endings
99 QString formatList;
100 const char* supported = QT_TR_NOOP("Supported formats");
101 const char* allFiles = QT_TR_NOOP("All files (*.*)");
102 formatList = QObject::tr(supported);
103 formatList += QLatin1String(" (");
104
105 std::vector<std::string> filetypes = App::GetApplication().getImportTypes();
106 // Make sure FCStd is the very first fileformat
107 auto it = std::ranges::find(filetypes, "FCStd");
108 if (it != filetypes.end()) {
109 filetypes.erase(it);
110 filetypes.insert(filetypes.begin(), "FCStd");
111 }
112 for (it = filetypes.begin(); it != filetypes.end(); ++it) {
113 formatList += QLatin1String(" *.");
114 formatList += QLatin1String(it->c_str());
115 }
116
117 formatList += QLatin1String(");;");
118
119 std::map<std::string, std::string> FilterList = App::GetApplication().getImportFilters();
120 std::map<std::string, std::string>::iterator jt;
121 // Make sure the format name for FCStd is the very first in the list
122 for (jt = FilterList.begin(); jt != FilterList.end(); ++jt) {
123 if (jt->first.find("*.FCStd") != std::string::npos) {
124 formatList += QLatin1String(jt->first.c_str());
125 formatList += QLatin1String(";;");
126 FilterList.erase(jt);
127 break;
128 }
129 }
130 for (jt = FilterList.begin(); jt != FilterList.end(); ++jt) {
131 formatList += QLatin1String(jt->first.c_str());
132 formatList += QLatin1String(";;");
133 }
134 formatList += QObject::tr(allFiles);
135
136 QString selectedFilter;
137 QStringList fileList = FileDialog::getOpenFileNames(
138 getMainWindow(),
139 QObject::tr("Open document"),
140 QString(),
141 formatList,
142 &selectedFilter
143 );
144 if (fileList.isEmpty()) {
145 return;
146 }
147
148 // load the files with the associated modules
149 SelectModule::Dict dict = SelectModule::importHandler(fileList, selectedFilter);
150 if (dict.isEmpty()) {
151 QMessageBox::critical(
152 getMainWindow(),
153 qApp->translate("StdCmdOpen", "Cannot open file"),
154 qApp->translate("StdCmdOpen", "Loading the file %1 is not supported").arg(fileList.front())
155 );
156 }
157 else {
158 for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) {
159
160 // Set flag indicating that this load/restore has been initiated by the user (not by a macro)
161 getGuiApplication()->setStatus(Gui::Application::UserInitiatedOpenDocument, true);
162
163 getGuiApplication()->open(it.key().toUtf8(), it.value().toLatin1());
164
165 getGuiApplication()->setStatus(Gui::Application::UserInitiatedOpenDocument, false);
166
167 App::Document* doc = App::GetApplication().getActiveDocument();
168
169 getGuiApplication()->checkPartialRestore(doc);
170 getGuiApplication()->checkRestoreError(doc);
171 }
172 }
173 }
174
175 //===========================================================================
176 // Std_Import
177 //===========================================================================
178
179 DEF_STD_CMD_A(StdCmdImport)
180
181 StdCmdImport::StdCmdImport()
182 : Command("Std_Import")
183 {
184 // setting the
185 sGroup = "File";
186 sMenuText = QT_TR_NOOP("&Import…");
187 sToolTipText = QT_TR_NOOP("Imports a file into the active document");
188 sWhatsThis = "Std_Import";
189 sStatusTip = sToolTipText;
190 sPixmap = "Std_Import";
191 sAccel = "Ctrl+Shift+I";
192 }
193
194 void StdCmdImport::activated(int iMsg)
195 {
196 Q_UNUSED(iMsg);
197
198 // fill the list of registered endings
199 QString formatList;
200 const char* supported = QT_TR_NOOP("Supported formats");
201 const char* allFiles = QT_TR_NOOP("All files (*.*)");
202 formatList = QObject::tr(supported);
203 formatList += QLatin1String(" (");
204
205 std::vector<std::string> filetypes = App::GetApplication().getImportTypes();
206 std::vector<std::string>::const_iterator it;
207 for (it = filetypes.begin(); it != filetypes.end(); ++it) {
208 if (*it != "FCStd") {
209 // ignore the project file format
210 formatList += QLatin1String(" *.");
211 formatList += QLatin1String(it->c_str());
212 }
213 }
214
215 formatList += QLatin1String(");;");
216
217 std::map<std::string, std::string> FilterList = App::GetApplication().getImportFilters();
218 std::map<std::string, std::string>::const_iterator jt;
219 for (jt = FilterList.begin(); jt != FilterList.end(); ++jt) {
220 // ignore the project file format
221 if (jt->first.find("(*.FCStd)") == std::string::npos) {
222 formatList += QLatin1String(jt->first.c_str());
223 formatList += QLatin1String(";;");
224 }
225 }
226 formatList += QObject::tr(allFiles);
227
228 Base::Reference<ParameterGrp> hPath = App::GetApplication()
229 .GetUserParameter()
230 .GetGroup("BaseApp")
231 ->GetGroup("Preferences")
232 ->GetGroup("General");
233 QString selectedFilter = QString::fromStdString(hPath->GetASCII("FileImportFilter"));
234 QStringList fileList = FileDialog::getOpenFileNames(
235 getMainWindow(),
236 QObject::tr("Import file"),
237 QString(),
238 formatList,
239 &selectedFilter
240 );
241 if (!fileList.isEmpty()) {
242 hPath->SetASCII("FileImportFilter", selectedFilter.toLatin1().constData());
243 SelectModule::Dict dict = SelectModule::importHandler(fileList, selectedFilter);
244
245 bool emptyDoc = (getActiveGuiDocument()->getDocument()->countObjects() == 0);
246 // load the files with the associated modules
247 for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) {
248 getGuiApplication()->importFrom(
249 it.key().toUtf8(),
250 getActiveGuiDocument()->getDocument()->getName(),
251 it.value().toLatin1()
252 );
253 }
254
255 if (emptyDoc) {
256 // only do a view fit if the document was empty before. See also parameter
257 // 'AutoFitToView' in importFrom()
258 std::list<Gui::MDIView*> views = getActiveGuiDocument()->getMDIViewsOfType(
259 Gui::View3DInventor::getClassTypeId()
260 );
261 for (const auto& view : views) {
262 view->viewAll();
263 }
264 }
265 }
266 }
267
268 bool StdCmdImport::isActive()
269 {
270 return (getActiveGuiDocument() ? true : false);
271 }
272
273
274 //===========================================================================
275 // Std_Export
276 //===========================================================================
277
278 DEF_STD_CMD_A(StdCmdExport)
279
280 StdCmdExport::StdCmdExport()
281 : Command("Std_Export")
282 {
283 // setting the
284 sGroup = "File";
285 sMenuText = QT_TR_NOOP("&Export…");
286 sToolTipText = QT_TR_NOOP("Exports an object in the active document");
287 sWhatsThis = "Std_Export";
288 sStatusTip = sToolTipText;
289 sAccel = "Ctrl+E";
290 sPixmap = "Std_Export";
291 eType = 0;
292 }
293
294 /**
295 Create a default filename from a user-specified format string
296
297 Format options are:
298 %F - the basename of the .FCStd file (or the label, if it is not saved yet)
299 %Lx - the label of the selected object(s), separated by character 'x'
300 %Px - the label of the selected object(s) and their first parent, separated by character 'x'
301 %U - the date and time, in UTC, ISO 8601
302 %D - the date and time, in local timezone, ISO 8601
303 Any other characters are treated literally, though if the filename is illegal
304 it will be changed on saving.
305
306 The format string is stored in two user preferences (not currently exposed in the GUI):
307 * BaseApp/Preferences/General/ExportDefaultFilenameSingle
308 * BaseApp/Preferences/General/ExportDefaultFilenameMultiple
309 */
310 QString createDefaultExportBasename()
311 {
312 QString defaultFilename;
313
314 auto selection = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId());
315 QString exportFormatString;
316 if (selection.size() == 1) {
317 exportFormatString = QString::fromStdString(
318 App::GetApplication()
319 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
320 ->GetASCII("ExportDefaultFilenameSingle", "%F-%P-")
321 );
322 }
323 else {
324 exportFormatString = QString::fromStdString(
325 App::GetApplication()
326 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
327 ->GetASCII("ExportDefaultFilenameMultiple", "%F")
328 );
329 }
330
331 // For code simplicity, pull all values we might need
332
333 // %F - the basename of the.FCStd file(or the label, if it is not saved yet)
334 QString docFilename = QString::fromUtf8(App::GetApplication().getActiveDocument()->getFileName());
335 QFileInfo fi(docFilename);
336 QString fcstdBasename = fi.completeBaseName();
337 if (fcstdBasename.isEmpty()) {
338 fcstdBasename = QString::fromStdString(
339 App::GetApplication().getActiveDocument()->Label.getStrValue()
340 );
341 }
342
343 // %L - the label of the selected object(s)
344 QStringList objectLabels;
345 for (const auto& object : selection) {
346 objectLabels.push_back(QString::fromStdString(object->Label.getStrValue()));
347 }
348
349 // %P - the label of the selected objects and their first parent
350 QStringList parentLabels;
351 for (const auto& object : selection) {
352 auto parents = object->getParents();
353 QString firstParent;
354 if (!parents.empty()) {
355 firstParent = QString::fromStdString(parents.front().first->Label.getStrValue());
356 }
357 parentLabels.append(firstParent + QString::fromStdString(object->Label.getStrValue()));
358 }
359
360 // %U - the date and time, in UTC, ISO 8601
361 QDateTime utc = QDateTime(QDateTime::currentDateTimeUtc());
362 QString utcISO8601 = utc.toString(Qt::ISODate);
363
364 // %D - the date and time, in local timezone, ISO 8601
365 QDateTime local = utc.toLocalTime();
366 QString localISO8601 = local.toString(Qt::ISODate);
367
368 // Parse the format string one character at a time:
369 for (int i = 0; i < exportFormatString.size(); ++i) {
370 auto c = exportFormatString.at(i);
371 if (c != QLatin1Char('%')) {
372 // Anything that's not a format start character is just a literal
373 defaultFilename.append(c);
374 }
375 else {
376 // The format start character now requires us to look at at least the next single
377 // character (if there isn't another character, the % just gets eaten)
378 if (i < exportFormatString.size() - 1) {
379 ++i;
380 auto formatChar = exportFormatString.at(i);
381 QChar separatorChar = QLatin1Char('-');
382 // If this format type requires an additional char, read that now (or default to
383 // '-' if the format string ends)
384 if (formatChar == QLatin1Char('L') || formatChar == QLatin1Char('P')) {
385 if (i < exportFormatString.size() - 1) {
386 ++i;
387 separatorChar = exportFormatString.at(i);
388 }
389 }
390
391 // Handle our format characters:
392 if (formatChar == QLatin1Char('F')) {
393 defaultFilename.append(fcstdBasename);
394 }
395 else if (formatChar == QLatin1Char('L')) {
396 defaultFilename.append(objectLabels.join(separatorChar));
397 }
398 else if (formatChar == QLatin1Char('P')) {
399 defaultFilename.append(parentLabels.join(separatorChar));
400 }
401 else if (formatChar == QLatin1Char('U')) {
402 defaultFilename.append(utcISO8601);
403 }
404 else if (formatChar == QLatin1Char('D')) {
405 defaultFilename.append(localISO8601);
406 }
407 else {
408 FC_WARN(
409 "When parsing default export filename format string, %"
410 << QString(formatChar).toStdString() << " is not a known format string."
411 );
412 }
413 }
414 }
415 }
416
417 // Finally, clean the string so it's valid for all operating systems:
418 QString invalidCharacters = QLatin1String("/\\?%*:|\"<>");
419 for (const auto& c : invalidCharacters) {
420 defaultFilename.replace(c, QLatin1String("_"));
421 }
422
423 return defaultFilename;
424 }
425
426 void StdCmdExport::activated(int iMsg)
427 {
428 Q_UNUSED(iMsg);
429
430 auto selection = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId());
431 if (selection.empty()) {
432 QMessageBox::warning(
433 Gui::getMainWindow(),
434 QCoreApplication::translate("StdCmdExport", "No selection"),
435 QCoreApplication::translate(
436 "StdCmdExport",
437 "Select objects to export before using the Export command."
438 )
439 );
440 return;
441 }
442
443 App::DocumentObject* toExport = selection.front();
444 App::Document* doc = toExport->getDocument();
445 App::ExportInfo exportInfo = doc->exportInfo();
446 bool filenameWasGenerated = false;
447
448 // fill the list of registered suffixes
449 QStringList filterList;
450 std::map<std::string, std::string> filterMap = App::GetApplication().getExportFilters();
451 for (const auto& filter : filterMap) {
452 // ignore the project file format
453 if (filter.first.find("(*.FCStd)") == std::string::npos) {
454 filterList << QString::fromStdString(filter.first);
455 }
456 }
457 QString formatList = filterList.join(QLatin1String(";;"));
458 Base::Reference<ParameterGrp> hPath = App::GetApplication()
459 .GetUserParameter()
460 .GetGroup("BaseApp")
461 ->GetGroup("Preferences")
462 ->GetGroup("General");
463 QString selectedFilter;
464
465 if (!exportInfo.filter.empty()) {
466 selectedFilter = QString::fromStdString(exportInfo.filter);
467 }
468 else {
469 selectedFilter = QString::fromStdString(hPath->GetASCII("FileExportFilter"));
470 }
471
472 // Create a default filename for the export
473 // * If this is the first export (the ExportInfo object' fields are empty)
474 // * If this is a repeated export using a filled ExportInfo object:
475 // * If the user accepted the default filename last time, regenerate a new
476 // default, potentially updating the object label.
477 // * If not, default to their previously-set export filename.
478 // * If this is an export of a different object than last time
479 QString defaultFilename;
480 if (exportInfo.filename.empty() || exportInfo.generatedName || exportInfo.object != toExport) {
481 // First, get the name and path of the current .FCStd file, if there is one:
482 QString docFilename = QString::fromStdString(doc->getFileName());
483
484 // Find the default location for our exported file. Three possibilities:
485 QString exportPath;
486 if (!exportInfo.filename.empty()) {
487 QFileInfo fi(QString::fromStdString(exportInfo.filename));
488 exportPath = fi.path();
489 }
490 else if (!docFilename.isEmpty()) {
491 QFileInfo fi(docFilename);
492 exportPath = fi.path();
493 }
494 else {
495 exportPath = Gui::FileDialog::getWorkingDirectory();
496 }
497
498 if (exportInfo.generatedName
499 || exportInfo.object != toExport) { /*<- static, true on first call*/
500 defaultFilename = exportPath + QLatin1Char('/') + createDefaultExportBasename();
501
502 // Append the last extension used, if there is one.
503 if (!exportInfo.filename.empty()) {
504 QFileInfo lastExportFile(QString::fromStdString(exportInfo.filename));
505 if (!lastExportFile.suffix().isEmpty()) {
506 defaultFilename += QLatin1String(".") + lastExportFile.suffix();
507 }
508 }
509 filenameWasGenerated = true;
510 }
511 }
512 else {
513 defaultFilename = QString::fromStdString(exportInfo.filename);
514 }
515 // Launch the file selection modal dialog
516 QString filename = FileDialog::getSaveFileName(
517 getMainWindow(),
518 QObject::tr("Export file"),
519 defaultFilename,
520 formatList,
521 &selectedFilter
522 );
523 if (!filename.isEmpty()) {
524 hPath->SetASCII("FileExportFilter", selectedFilter.toLatin1().constData());
525
526 SelectModule::Dict dict = SelectModule::exportHandler(filename, selectedFilter);
527 // export the files with the associated modules
528 for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) {
529 getGuiApplication()->exportTo(it.key().toUtf8(), doc->getName(), it.value().toLatin1());
530 }
531
532 // Keep a record of if the user used our suggested generated filename. If they
533 // did, next time we can recreate it, which will update the object label if
534 // there is one.
535 QFileInfo defaultExportFI(defaultFilename);
536 QFileInfo thisExportFI(filename);
537
538 if (filenameWasGenerated
539 && thisExportFI.completeBaseName() != defaultExportFI.completeBaseName()) {
540 filenameWasGenerated = false;
541 }
542
543 exportInfo.filename = filename.toStdString();
544 exportInfo.object = toExport;
545 exportInfo.filter = selectedFilter.toStdString();
546 exportInfo.generatedName = filenameWasGenerated;
547
548 doc->setExportInfo(exportInfo);
549 }
550 }
551
552 bool StdCmdExport::isActive()
553 {
554 return (getActiveGuiDocument() ? true : false);
555 }
556
557 //===========================================================================
558 // Std_MergeProjects
559 //===========================================================================
560
561 DEF_STD_CMD_A(StdCmdMergeProjects)
562
563 StdCmdMergeProjects::StdCmdMergeProjects()
564 : Command("Std_MergeProjects")
565 {
566 sAppModule = "File";
567 sGroup = "File";
568 sMenuText = QT_TR_NOOP("&Merge Document");
569
570 sToolTipText = QT_TR_NOOP("Merges another FreeCAD document into the active one");
571
572 sWhatsThis = "Std_MergeProjects";
573 sStatusTip = sToolTipText;
574 sPixmap = "Std_MergeProjects";
575 }
576
577 void StdCmdMergeProjects::activated(int iMsg)
578 {
579 Q_UNUSED(iMsg);
580
581 QString exe = qApp->applicationName();
582 QString project = FileDialog::getOpenFileName(
583 Gui::getMainWindow(),
584 QString::fromUtf8(QT_TR_NOOP("Merge document")),
585 FileDialog::getWorkingDirectory(),
586 QString::fromUtf8(QT_TR_NOOP("%1 document (*.FCStd)")).arg(exe)
587 );
588 if (!project.isEmpty()) {
589 FileDialog::setWorkingDirectory(project);
590 App::Document* doc = App::GetApplication().getActiveDocument();
591 QFileInfo info(QString::fromUtf8(doc->FileName.getValue()));
592 QFileInfo proj(project);
593 if (proj == info) {
594 QMessageBox::critical(
595 Gui::getMainWindow(),
596 QString::fromUtf8(QT_TR_NOOP("Merge document")),
597 QString::fromUtf8(QT_TR_NOOP("Cannot merge document with itself."))
598 );
599 return;
600 }
601
602 doc->openTransaction("Merge document");
603 Base::FileInfo fi((const char*)project.toUtf8());
604 Base::ifstream str(fi, std::ios::in | std::ios::binary);
605 MergeDocuments md(doc);
606 md.importObjects(str);
607 str.close();
608 doc->commitTransaction();
609 }
610 }
611
612 bool StdCmdMergeProjects::isActive()
613 {
614 return this->hasActiveDocument();
615 }
616
617 //===========================================================================
618 // Std_DependencyGraph
619 //===========================================================================
620
621 DEF_STD_CMD_A(StdCmdDependencyGraph)
622
623 StdCmdDependencyGraph::StdCmdDependencyGraph()
624 : Command("Std_DependencyGraph")
625 {
626 // setting the
627 sGroup = "Tools";
628 sMenuText = QT_TR_NOOP("Dependency Gra&ph");
629
630 sToolTipText = QT_TR_NOOP("Shows the dependency graph of the objects in the active document");
631 sStatusTip = sToolTipText;
632 sWhatsThis = "Std_DependencyGraph";
633 eType = 0;
634 sPixmap = "Std_DependencyGraph";
635 }
636
637 void StdCmdDependencyGraph::activated(int iMsg)
638 {
639 Q_UNUSED(iMsg);
640 App::Document* doc = App::GetApplication().getActiveDocument();
641 auto view = new Gui::GraphvizView(*doc);
642 view->setWindowTitle(qApp->translate("Std_DependencyGraph", "Dependency Graph"));
643 getMainWindow()->addWindow(view);
644 }
645
646 bool StdCmdDependencyGraph::isActive()
647 {
648 return (getActiveGuiDocument() ? true : false);
649 }
650
651 //===========================================================================
652 // Std_ExportDependencyGraph
653 //===========================================================================
654
655 DEF_STD_CMD_A(StdCmdExportDependencyGraph)
656
657 StdCmdExportDependencyGraph::StdCmdExportDependencyGraph()
658 : Command("Std_ExportDependencyGraph")
659 {
660 sGroup = "Tools";
661 sMenuText = QT_TR_NOOP("Export Dependency &Graph");
662 sToolTipText = QT_TR_NOOP("Exports the dependency graph as a Graphviz (.gv) file");
663 sStatusTip = sToolTipText;
664 sWhatsThis = "Std_ExportDependencyGraph";
665 eType = 0;
666 // sPixmap = "Std_ExportDependencyGraph";
667 }
668
669 void StdCmdExportDependencyGraph::activated(int iMsg)
670 {
671 Q_UNUSED(iMsg);
672 App::Document* doc = App::GetApplication().getActiveDocument();
673 QString format = QStringLiteral("%1 (*.gv)").arg(Gui::GraphvizView::tr("Graphviz format"));
674 QString fn = Gui::FileDialog::getSaveFileName(
675 Gui::getMainWindow(),
676 Gui::GraphvizView::tr("Export graph"),
677 QString(),
678 format
679 );
680 if (!fn.isEmpty()) {
681 QFile file(fn);
682 if (file.open(QFile::WriteOnly)) {
683 std::stringstream str;
684 doc->exportGraphviz(str);
685 QByteArray buffer = QByteArray::fromStdString(str.str());
686 file.write(buffer);
687 file.close();
688 }
689 }
690 }
691
692 bool StdCmdExportDependencyGraph::isActive()
693 {
694 return (getActiveGuiDocument() ? true : false);
695 }
696
697 //===========================================================================
698 // Std_New
699 //===========================================================================
700
701 DEF_STD_CMD(StdCmdNew)
702
703 StdCmdNew::StdCmdNew()
704 : Command("Std_New")
705 {
706 sGroup = "File";
707 sMenuText = QT_TR_NOOP("&New Document");
708 sToolTipText = QT_TR_NOOP("Creates a new empty document");
709 sWhatsThis = "Std_New";
710 sStatusTip = sToolTipText;
711 sPixmap = "document-new";
712 sAccel = keySequenceToAccel(QKeySequence::New);
713 }
714
715 void StdCmdNew::activated(int iMsg)
716 {
717 Q_UNUSED(iMsg);
718 QString cmd;
719 cmd = QStringLiteral("App.newDocument()");
720 runCommand(Command::Doc, cmd.toUtf8());
721 doCommand(Command::Gui, "Gui.activeDocument().activeView().viewDefaultOrientation()");
722
723 ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath(
724 "User parameter:BaseApp/Preferences/View"
725 );
726 if (hViewGrp->GetBool("ShowAxisCross")) {
727 doCommand(Command::Gui, "Gui.ActiveDocument.ActiveView.setAxisCross(True)");
728 }
729 }
730
731 //===========================================================================
732 // Std_Save
733 //===========================================================================
734 DEF_STD_CMD_A(StdCmdSave)
735
736 StdCmdSave::StdCmdSave()
737 : Command("Std_Save")
738 {
739 sGroup = "File";
740 sMenuText = QT_TR_NOOP("&Save");
741 sToolTipText = QT_TR_NOOP("Saves the active document");
742 sWhatsThis = "Std_Save";
743 sStatusTip = sToolTipText;
744 sPixmap = "document-save";
745 sAccel = keySequenceToAccel(QKeySequence::Save);
746 eType = 0;
747 }
748
749 void StdCmdSave::activated(int iMsg)
750 {
751 Q_UNUSED(iMsg);
752 doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"Save\")");
753 }
754
755 bool StdCmdSave::isActive()
756 {
757 return getGuiApplication()->sendHasMsgToActiveView("Save");
758 }
759
760 //===========================================================================
761 // Std_SaveAs
762 //===========================================================================
763 DEF_STD_CMD_A(StdCmdSaveAs)
764
765 StdCmdSaveAs::StdCmdSaveAs()
766 : Command("Std_SaveAs")
767 {
768 sGroup = "File";
769 sMenuText = QT_TR_NOOP("Save &As…");
770 sToolTipText = QT_TR_NOOP("Saves the active document under a new file name");
771 sWhatsThis = "Std_SaveAs";
772 sStatusTip = sToolTipText;
773 sPixmap = "document-save-as";
774 sAccel = keySequenceToAccel(QKeySequence::SaveAs);
775 eType = 0;
776 }
777
778 void StdCmdSaveAs::activated(int iMsg)
779 {
780 Q_UNUSED(iMsg);
781 doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"SaveAs\")");
782 }
783
784 bool StdCmdSaveAs::isActive()
785 {
786 return getGuiApplication()->sendHasMsgToActiveView("SaveAs");
787 }
788
789 //===========================================================================
790 // Std_SaveCopy
791 //===========================================================================
792 DEF_STD_CMD_A(StdCmdSaveCopy)
793
794 StdCmdSaveCopy::StdCmdSaveCopy()
795 : Command("Std_SaveCopy")
796 {
797 sGroup = "File";
798 sMenuText = QT_TR_NOOP("Save Cop&y");
799
800 sToolTipText = QT_TR_NOOP("Saves a copy of the active document under a new file name");
801 sWhatsThis = "Std_SaveCopy";
802 sStatusTip = sToolTipText;
803 sPixmap = "Std_SaveCopy";
804 }
805
806 void StdCmdSaveCopy::activated(int iMsg)
807 {
808 Q_UNUSED(iMsg);
809 doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"SaveCopy\")");
810 }
811
812 bool StdCmdSaveCopy::isActive()
813 {
814 return (getActiveGuiDocument() ? true : false);
815 }
816
817 //===========================================================================
818 // Std_SaveAll
819 //===========================================================================
820 DEF_STD_CMD_A(StdCmdSaveAll)
821
822 StdCmdSaveAll::StdCmdSaveAll()
823 : Command("Std_SaveAll")
824 {
825 sGroup = "File";
826 sMenuText = QT_TR_NOOP("Sa&ve All");
827 sToolTipText = QT_TR_NOOP("Saves all open documents");
828 sWhatsThis = "Std_SaveAll";
829 sStatusTip = sToolTipText;
830 sPixmap = "Std_SaveAll";
831 }
832
833 void StdCmdSaveAll::activated(int iMsg)
834 {
835 Q_UNUSED(iMsg);
836 Gui::Document::saveAll();
837 }
838
839 bool StdCmdSaveAll::isActive()
840 {
841 return (getActiveGuiDocument() ? true : false);
842 }
843
844
845 //===========================================================================
846 // Std_Revert
847 //===========================================================================
848 DEF_STD_CMD_A(StdCmdRevert)
849
850 StdCmdRevert::StdCmdRevert()
851 : Command("Std_Revert")
852 {
853 sGroup = "File";
854 sMenuText = QT_TR_NOOP("Rever&t");
855 sToolTipText = QT_TR_NOOP("Reverts to the saved version of this file");
856 sWhatsThis = "Std_Revert";
857 sStatusTip = sToolTipText;
858 sPixmap = "Std_Revert";
859 eType = NoTransaction;
860 }
861
862 void StdCmdRevert::activated(int iMsg)
863 {
864 Q_UNUSED(iMsg);
865 QMessageBox msgBox(Gui::getMainWindow());
866 msgBox.setIcon(QMessageBox::Question);
867 msgBox.setWindowTitle(qApp->translate("Std_Revert", "Revert Document"));
868 msgBox.setText(
869 qApp->translate("Std_Revert", "This will discard all the changes since the last file save.")
870 );
871 msgBox.setInformativeText(qApp->translate("Std_Revert", "Continue?"));
872 msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
873 msgBox.setDefaultButton(QMessageBox::No);
874 int ret = msgBox.exec();
875 if (ret == QMessageBox::Yes) {
876 doCommand(Command::App, "App.ActiveDocument.restore()");
877 }
878 }
879
880 bool StdCmdRevert::isActive()
881 {
882 return (getActiveGuiDocument() ? true : false);
883 }
884
885 //===========================================================================
886 // Std_ProjectInfo
887 //===========================================================================
888
889 DEF_STD_CMD_A(StdCmdProjectInfo)
890
891 StdCmdProjectInfo::StdCmdProjectInfo()
892 : Command("Std_ProjectInfo")
893 {
894 // setting the
895 sGroup = "File";
896 sMenuText = QT_TR_NOOP("Doc&ument Information");
897
898 sToolTipText = QT_TR_NOOP("Shows information about the active document");
899 sWhatsThis = "Std_ProjectInfo";
900 sStatusTip = sToolTipText;
901 sPixmap = "document-properties";
902 }
903
904 void StdCmdProjectInfo::activated(int iMsg)
905 {
906 Q_UNUSED(iMsg);
907 Gui::Dialog::DlgProjectInformationImp dlg(getActiveGuiDocument()->getDocument(), getMainWindow());
908 dlg.exec();
909 }
910
911 bool StdCmdProjectInfo::isActive()
912 {
913 return (getActiveGuiDocument() ? true : false);
914 }
915
916 //===========================================================================
917 // Std_ProjectUtil
918 //===========================================================================
919
920 DEF_STD_CMD_A(StdCmdProjectUtil)
921
922 StdCmdProjectUtil::StdCmdProjectUtil()
923 : Command("Std_ProjectUtil")
924 {
925 // setting the
926 sGroup = "Tools";
927 sWhatsThis = "Std_ProjectUtil";
928 sMenuText = QT_TR_NOOP("Do&cument Utility");
929
930 sToolTipText = QT_TR_NOOP("Extracts or creates document files");
931 sStatusTip = sToolTipText;
932 sPixmap = "Std_ProjectUtil";
933 }
934
935 void StdCmdProjectUtil::activated(int iMsg)
936 {
937 Q_UNUSED(iMsg);
938 Gui::Dialog::DlgProjectUtility dlg(getMainWindow());
939 dlg.exec();
940 }
941
942 bool StdCmdProjectUtil::isActive()
943 {
944 return true;
945 }
946
947 //===========================================================================
948 // Std_Print
949 //===========================================================================
950 DEF_STD_CMD_A(StdCmdPrint)
951
952 StdCmdPrint::StdCmdPrint()
953 : Command("Std_Print")
954 {
955 sGroup = "File";
956 sMenuText = QT_TR_NOOP("&Print");
957
958 sToolTipText = QT_TR_NOOP("Prints the active document");
959 sWhatsThis = "Std_Print";
960 sStatusTip = sToolTipText;
961 sPixmap = "document-print";
962 sAccel = keySequenceToAccel(QKeySequence::Print);
963 eType = 0;
964 }
965
966 void StdCmdPrint::activated(int iMsg)
967 {
968 Q_UNUSED(iMsg);
969 if (getMainWindow()->activeWindow()) {
970 getMainWindow()->showMessage(QObject::tr("Printing…"));
971 getMainWindow()->activeWindow()->print();
972 }
973 }
974
975 bool StdCmdPrint::isActive()
976 {
977 return getGuiApplication()->sendHasMsgToActiveView("Print");
978 }
979
980 //===========================================================================
981 // Std_PrintPreview
982 //===========================================================================
983 DEF_STD_CMD_A(StdCmdPrintPreview)
984
985 StdCmdPrintPreview::StdCmdPrintPreview()
986 : Command("Std_PrintPreview")
987 {
988 sGroup = "File";
989 sMenuText = QT_TR_NOOP("Print Previe&w");
990
991 sToolTipText = QT_TR_NOOP("Previews the active document before printing");
992 sWhatsThis = "Std_PrintPreview";
993 sStatusTip = sToolTipText;
994 sPixmap = "document-print-preview";
995 eType = 0;
996 }
997
998 void StdCmdPrintPreview::activated(int iMsg)
999 {
1000 Q_UNUSED(iMsg);
1001 if (getMainWindow()->activeWindow()) {
1002 getMainWindow()->activeWindow()->printPreview();
1003 }
1004 }
1005
1006 bool StdCmdPrintPreview::isActive()
1007 {
1008 return getGuiApplication()->sendHasMsgToActiveView("PrintPreview");
1009 }
1010
1011 //===========================================================================
1012 // Std_PrintPdf
1013 //===========================================================================
1014 DEF_STD_CMD_A(StdCmdPrintPdf)
1015
1016 StdCmdPrintPdf::StdCmdPrintPdf()
1017 : Command("Std_PrintPdf")
1018 {
1019 sGroup = "File";
1020 sMenuText = QT_TR_NOOP("Export P&DF");
1021
1022 sToolTipText = QT_TR_NOOP("Exports the active document as a PDF file");
1023 sWhatsThis = "Std_PrintPdf";
1024 sStatusTip = sToolTipText;
1025 sPixmap = "Std_PrintPdf";
1026 eType = 0;
1027 }
1028
1029 void StdCmdPrintPdf::activated(int iMsg)
1030 {
1031 Q_UNUSED(iMsg);
1032 if (getMainWindow()->activeWindow()) {
1033 getMainWindow()->showMessage(QObject::tr("Exporting PDF…"));
1034 getMainWindow()->activeWindow()->printPdf();
1035 }
1036 }
1037
1038 bool StdCmdPrintPdf::isActive()
1039 {
1040 return getGuiApplication()->sendHasMsgToActiveView("PrintPdf");
1041 }
1042
1043 //===========================================================================
1044 // Std_Quit
1045 //===========================================================================
1046
1047 DEF_STD_CMD_C(StdCmdQuit)
1048
1049 StdCmdQuit::StdCmdQuit()
1050 : Command("Std_Quit")
1051 {
1052 sGroup = "File";
1053 sMenuText = QT_TR_NOOP("E&xit");
1054 sToolTipText = QT_TR_NOOP("Quits the application");
1055 sWhatsThis = "Std_Quit";
1056 sStatusTip = sToolTipText;
1057 sPixmap = "application-exit";
1058 sAccel = keySequenceToAccel(QKeySequence::Quit);
1059 eType = NoTransaction;
1060 }
1061
1062 Action* StdCmdQuit::createAction()
1063 {
1064 Action* pcAction = Command::createAction();
1065 pcAction->setMenuRole(QAction::QuitRole);
1066
1067 return pcAction;
1068 }
1069
1070 void StdCmdQuit::activated(int iMsg)
1071 {
1072 Q_UNUSED(iMsg);
1073 // close the main window and exit the event loop
1074 getMainWindow()->close();
1075 }
1076
1077 //===========================================================================
1078 // Std_Undo
1079 //===========================================================================
1080
1081 DEF_STD_CMD_AC(StdCmdUndo)
1082
1083 StdCmdUndo::StdCmdUndo()
1084 : Command("Std_Undo")
1085 {
1086 sGroup = "Edit";
1087 sMenuText = QT_TR_NOOP("&Undo");
1088 sToolTipText = QT_TR_NOOP("Undoes the previous action");
1089 sWhatsThis = "Std_Undo";
1090 sStatusTip = sToolTipText;
1091 sPixmap = "edit-undo";
1092 sAccel = keySequenceToAccel(QKeySequence::Undo);
1093 eType = ForEdit | NoTransaction;
1094 }
1095
1096 void StdCmdUndo::activated(int iMsg)
1097 {
1098 Q_UNUSED(iMsg);
1099 // Application::Instance->slotUndo();
1100 getGuiApplication()->sendMsgToActiveView("Undo");
1101 }
1102
1103 bool StdCmdUndo::isActive()
1104 {
1105 return getGuiApplication()->sendHasMsgToActiveView("Undo");
1106 }
1107
1108 Action* StdCmdUndo::createAction()
1109 {
1110 Action* pcAction;
1111
1112 pcAction = new UndoAction(this, getMainWindow());
1113 pcAction->setShortcut(QString::fromLatin1(getAccel()));
1114 applyCommandData(this->className(), pcAction);
1115 if (getPixmap()) {
1116 pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(getPixmap()));
1117 }
1118
1119 return pcAction;
1120 }
1121
1122 //===========================================================================
1123 // Std_Redo
1124 //===========================================================================
1125
1126 DEF_STD_CMD_AC(StdCmdRedo)
1127
1128 StdCmdRedo::StdCmdRedo()
1129 : Command("Std_Redo")
1130 {
1131 sGroup = "Edit";
1132 sMenuText = QT_TR_NOOP("&Redo");
1133 sToolTipText = QT_TR_NOOP("Redoes a previously undone action");
1134 sWhatsThis = "Std_Redo";
1135 sStatusTip = sToolTipText;
1136 sPixmap = "edit-redo";
1137 sAccel = keySequenceToAccel(QKeySequence::Redo);
1138 eType = ForEdit | NoTransaction;
1139 }
1140
1141 void StdCmdRedo::activated(int iMsg)
1142 {
1143 Q_UNUSED(iMsg);
1144 // Application::Instance->slotRedo();
1145 getGuiApplication()->sendMsgToActiveView("Redo");
1146 }
1147
1148 bool StdCmdRedo::isActive()
1149 {
1150 return getGuiApplication()->sendHasMsgToActiveView("Redo");
1151 }
1152
1153 Action* StdCmdRedo::createAction()
1154 {
1155 Action* pcAction;
1156
1157 pcAction = new RedoAction(this, getMainWindow());
1158 pcAction->setShortcut(QString::fromLatin1(getAccel()));
1159 applyCommandData(this->className(), pcAction);
1160 if (getPixmap()) {
1161 pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(getPixmap()));
1162 }
1163
1164 return pcAction;
1165 }
1166
1167 //===========================================================================
1168 // Std_Cut
1169 //===========================================================================
1170 DEF_STD_CMD_A(StdCmdCut)
1171
1172 StdCmdCut::StdCmdCut()
1173 : Command("Std_Cut")
1174 {
1175 sGroup = "Edit";
1176 sMenuText = QT_TR_NOOP("Cu&t");
1177 sToolTipText = QT_TR_NOOP("Removes the selection and copies it to the clipboard");
1178 sWhatsThis = "Std_Cut";
1179 sStatusTip = sToolTipText;
1180 sPixmap = "edit-cut";
1181 sAccel = keySequenceToAccel(QKeySequence::Cut);
1182 }
1183
1184 void StdCmdCut::activated(int iMsg)
1185 {
1186 Q_UNUSED(iMsg);
1187 getGuiApplication()->sendMsgToActiveView("Cut");
1188 }
1189
1190 bool StdCmdCut::isActive()
1191 {
1192 return getGuiApplication()->sendHasMsgToActiveView("Cut");
1193 }
1194
1195 //===========================================================================
1196 // Std_Copy
1197 //===========================================================================
1198 DEF_STD_CMD_A(StdCmdCopy)
1199
1200 StdCmdCopy::StdCmdCopy()
1201 : Command("Std_Copy")
1202 {
1203 sGroup = "Edit";
1204 sMenuText = QT_TR_NOOP("&Copy");
1205 sToolTipText = QT_TR_NOOP("Copies the selection to the clipboard");
1206 sWhatsThis = "Std_Copy";
1207 sStatusTip = sToolTipText;
1208 sPixmap = "edit-copy";
1209 sAccel = keySequenceToAccel(QKeySequence::Copy);
1210 }
1211
1212 void StdCmdCopy::activated(int iMsg)
1213 {
1214 Q_UNUSED(iMsg);
1215 bool done = getGuiApplication()->sendMsgToFocusView("Copy");
1216 if (!done) {
1217 QMimeData* mimeData = getMainWindow()->createMimeDataFromSelection();
1218 QClipboard* cb = QApplication::clipboard();
1219 cb->setMimeData(mimeData);
1220 }
1221 }
1222
1223 bool StdCmdCopy::isActive()
1224 {
1225 if (getGuiApplication()->sendHasMsgToFocusView("Copy")) {
1226 return true;
1227 }
1228 return Selection().hasSelection();
1229 }
1230
1231 //===========================================================================
1232 // Std_Paste
1233 //===========================================================================
1234 DEF_STD_CMD_A(StdCmdPaste)
1235
1236 StdCmdPaste::StdCmdPaste()
1237 : Command("Std_Paste")
1238 {
1239 sGroup = "Edit";
1240 sMenuText = QT_TR_NOOP("&Paste");
1241 sToolTipText = QT_TR_NOOP("Pastes the contents of the clipboard");
1242 sWhatsThis = "Std_Paste";
1243 sStatusTip = sToolTipText;
1244 sPixmap = "edit-paste";
1245 sAccel = keySequenceToAccel(QKeySequence::Paste);
1246 }
1247
1248 void StdCmdPaste::activated(int iMsg)
1249 {
1250 Q_UNUSED(iMsg);
1251 bool done = getGuiApplication()->sendMsgToFocusView("Paste");
1252 if (!done) {
1253 QClipboard* cb = QApplication::clipboard();
1254 const QMimeData* mimeData = cb->mimeData();
1255 if (mimeData) {
1256 WaitCursor wc;
1257 getMainWindow()->insertFromMimeData(mimeData);
1258 }
1259 }
1260 }
1261
1262 bool StdCmdPaste::isActive()
1263 {
1264 if (getGuiApplication()->sendHasMsgToFocusView("Paste")) {
1265 return true;
1266 }
1267 QClipboard* cb = QApplication::clipboard();
1268 const QMimeData* mime = cb->mimeData();
1269 if (!mime) {
1270 return false;
1271 }
1272 return getMainWindow()->canInsertFromMimeData(mime);
1273 }
1274
1275 DEF_STD_CMD_A(StdCmdDuplicateSelection)
1276
1277 StdCmdDuplicateSelection::StdCmdDuplicateSelection()
1278 : Command("Std_DuplicateSelection")
1279 {
1280 sAppModule = "Edit";
1281 sGroup = "Edit";
1282 sMenuText = QT_TR_NOOP("Duplicate Selecti&on");
1283 sToolTipText = QT_TR_NOOP("Duplicates the selected objects to the active document");
1284 sWhatsThis = "Std_DuplicateSelection";
1285 sStatusTip = sToolTipText;
1286 sPixmap = "Std_DuplicateSelection";
1287 }
1288
1289 void StdCmdDuplicateSelection::activated(int iMsg)
1290 {
1291 Q_UNUSED(iMsg);
1292 std::vector<App::DocumentObject*> sel;
1293 std::set<App::DocumentObject*> objSet;
1294 for (auto& s : Selection().getCompleteSelection()) {
1295 if (s.pObject && s.pObject->isAttachedToDocument() && objSet.insert(s.pObject).second) {
1296 sel.push_back(s.pObject);
1297 }
1298 }
1299 if (sel.empty()) {
1300 return;
1301 }
1302
1303 bool hasXLink = false;
1304 Base::FileInfo fi(App::Application::getTempFileName());
1305 {
1306 auto all = App::Document::getDependencyList(sel);
1307 if (all.size() > sel.size()) {
1308 DlgObjectSelection dlg(sel, getMainWindow());
1309 if (dlg.exec() != QDialog::Accepted) {
1310 return;
1311 }
1312 sel = dlg.getSelections();
1313 if (sel.empty()) {
1314 return;
1315 }
1316 }
1317 std::vector<App::Document*> unsaved;
1318 hasXLink = App::PropertyXLink::hasXLink(sel, &unsaved);
1319 if (!unsaved.empty()) {
1320 QMessageBox::critical(
1321 getMainWindow(),
1322 QObject::tr("Unsaved document"),
1323 QObject::tr(
1324 "The exported object contains an external link. Save the document."
1325 "at least once before exporting."
1326 )
1327 );
1328 return;
1329 }
1330
1331 // save stuff to file
1332 Base::ofstream str(fi, std::ios::out | std::ios::binary);
1333 App::Document* doc = sel.front()->getDocument();
1334 MergeDocuments mimeView(doc);
1335 doc->exportObjects(sel, str);
1336 str.close();
1337 }
1338 App::Document* doc = App::GetApplication().getActiveDocument();
1339 if (doc) {
1340 bool proceed = true;
1341 if (hasXLink && !doc->isSaved()) {
1342 auto ret = QMessageBox::question(
1343 getMainWindow(),
1344 qApp->translate("Std_DuplicateSelection", "Object dependencies"),
1345 qApp->translate(
1346 "Std_DuplicateSelection",
1347 "To link to external objects, the document must be saved at least once.\n"
1348 "Save the document now?"
1349 ),
1350 QMessageBox::Yes,
1351 QMessageBox::No
1352 );
1353 if (ret == QMessageBox::Yes) {
1354 proceed = Application::Instance->getDocument(doc)->saveAs();
1355 }
1356 }
1357 if (proceed) {
1358 doc->openTransaction("Duplicate");
1359 // restore objects from file and add to active document
1360 Base::ifstream str(fi, std::ios::in | std::ios::binary);
1361 MergeDocuments mimeView(doc);
1362 mimeView.importObjects(str);
1363 str.close();
1364 doc->commitTransaction();
1365 }
1366 }
1367 fi.deleteFile();
1368 }
1369
1370 bool StdCmdDuplicateSelection::isActive()
1371 {
1372 return Gui::Selection().hasSelection();
1373 }
1374
1375 //===========================================================================
1376 // Std_SelectAll
1377 //===========================================================================
1378
1379 DEF_STD_CMD_A(StdCmdSelectAll)
1380
1381 StdCmdSelectAll::StdCmdSelectAll()
1382 : Command("Std_SelectAll")
1383 {
1384 sGroup = "Edit";
1385 sMenuText = QT_TR_NOOP("Select &All");
1386 sToolTipText = QT_TR_NOOP("Selects all objects in the active document");
1387 sWhatsThis = "Std_SelectAll";
1388 sStatusTip = sToolTipText;
1389 sPixmap = "edit-select-all";
1390 sAccel = "Ctrl+A"; // supersedes shortcuts for text edits
1391
1392 // this cmd only alters selection, not doc or 3d view
1393 eType = AlterSelection;
1394 }
1395
1396 void StdCmdSelectAll::activated(int iMsg)
1397 {
1398 Q_UNUSED(iMsg);
1399
1400 auto* activeDoc = Application::Instance->activeDocument();
1401 if (activeDoc) {
1402 auto* editingVP = activeDoc->getInEdit();
1403 if (editingVP && editingVP->selectAll()) {
1404 return;
1405 }
1406 }
1407
1408 // fallback to doc level select
1409 SelectionSingleton& rSel = Selection();
1410 App::Document* doc = App::GetApplication().getActiveDocument();
1411 if (doc) {
1412 std::vector<App::DocumentObject*> objs = doc->getObjectsOfType(
1413 App::DocumentObject::getClassTypeId()
1414 );
1415 rSel.setSelection(doc->getName(), objs);
1416 }
1417 }
1418
1419 bool StdCmdSelectAll::isActive()
1420 {
1421 return App::GetApplication().getActiveDocument() != nullptr;
1422 }
1423
1424 //===========================================================================
1425 // Std_Delete
1426 //===========================================================================
1427 DEF_STD_CMD_A(StdCmdDelete)
1428
1429 StdCmdDelete::StdCmdDelete()
1430 : Command("Std_Delete")
1431 {
1432 sGroup = "Edit";
1433 sMenuText = QT_TR_NOOP("&Delete");
1434 sToolTipText = QT_TR_NOOP("Deletes the selected objects");
1435 sWhatsThis = "Std_Delete";
1436 sStatusTip = sToolTipText;
1437 sPixmap = "edit-delete";
1438 sAccel = keySequenceToAccel(QtTools::deleteKeySequence());
1439 eType = ForEdit;
1440 }
1441
1442 void StdCmdDelete::activated(int iMsg)
1443 {
1444 Q_UNUSED(iMsg);
1445
1446 std::set<App::Document*> docs;
1447 try {
1448 openCommand(QT_TRANSLATE_NOOP("Command", "Delete"));
1449 if (getGuiApplication()->sendHasMsgToFocusView(getName())) {
1450 commitCommand();
1451 return;
1452 }
1453
1454 App::TransactionLocker tlock;
1455
1456 Gui::getMainWindow()->setUpdatesEnabled(false);
1457 auto editDoc = Application::Instance->editDocument();
1458 ViewProviderDocumentObject* vpedit = nullptr;
1459 if (editDoc) {
1460 vpedit = freecad_cast<ViewProviderDocumentObject*>(editDoc->getInEdit());
1461 }
1462 if (vpedit && !vpedit->acceptDeletionsInEdit()) {
1463 for (auto& sel : Selection().getSelectionEx(editDoc->getDocument()->getName())) {
1464 if (sel.getObject() == vpedit->getObject()) {
1465 if (!sel.getSubNames().empty()) {
1466 vpedit->onDelete(sel.getSubNames());
1467 docs.insert(editDoc->getDocument());
1468 }
1469 break;
1470 }
1471 }
1472 }
1473 else {
1474 std::set<QString> affectedLabels;
1475 bool more = false;
1476 auto sels = Selection().getSelectionEx();
1477 bool autoDeletion = true;
1478 for (auto& sel : sels) {
1479 auto obj = sel.getObject();
1480 if (obj == nullptr) {
1481 Base::Console().developerWarning(
1482 "StdCmdDelete::activated",
1483 "App::DocumentObject pointer is nullptr\n"
1484 );
1485 continue;
1486 }
1487 for (auto parent : obj->getInList()) {
1488 if (!Selection().isSelected(parent)) {
1489 ViewProvider* vp = Application::Instance->getViewProvider(parent);
1490 if (vp && !vp->canDelete(obj)) {
1491 autoDeletion = false;
1492 QString label;
1493 if (parent->getDocument() != obj->getDocument()) {
1494 label = QLatin1String(parent->getFullName().c_str());
1495 }
1496 else {
1497 label = QLatin1String(parent->getNameInDocument());
1498 }
1499 if (parent->Label.getStrValue() != parent->getNameInDocument()) {
1500 label += QStringLiteral(" (%1)").arg(
1501 QString::fromUtf8(parent->Label.getValue())
1502 );
1503 }
1504 affectedLabels.insert(label);
1505 if (affectedLabels.size() >= 10) {
1506 more = true;
1507 break;
1508 }
1509 }
1510 }
1511 }
1512 if (more) {
1513 break;
1514 }
1515 }
1516
1517 if (!autoDeletion) {
1518 QString bodyMessage;
1519 QTextStream bodyMessageStream(&bodyMessage);
1520 bodyMessageStream << qApp->translate(
1521 "Std_Delete",
1522 "The following referencing objects might break.\n\n"
1523 "Continue?\n"
1524 );
1525 for (const auto& currentLabel : affectedLabels) {
1526 bodyMessageStream << '\n' << currentLabel;
1527 }
1528 if (more) {
1529 bodyMessageStream << "\n...";
1530 }
1531
1532 auto ret = QMessageBox::warning(
1533 Gui::getMainWindow(),
1534 qApp->translate("Std_Delete", "Object dependencies"),
1535 bodyMessage,
1536 QMessageBox::Yes,
1537 QMessageBox::No
1538 );
1539 if (ret == QMessageBox::Yes) {
1540 autoDeletion = true;
1541 }
1542 }
1543 if (autoDeletion) {
1544 for (auto& sel : sels) {
1545 auto obj = sel.getObject();
1546 Gui::ViewProvider* vp = Application::Instance->getViewProvider(obj);
1547 if (vp) {
1548 // ask the ViewProvider if it wants to do some clean up
1549 if (vp->onDelete(sel.getSubNames())) {
1550 docs.insert(obj->getDocument());
1551 FCMD_OBJ_DOC_CMD(obj, "removeObject('" << obj->getNameInDocument() << "')");
1552 }
1553 }
1554 }
1555 }
1556 }
1557 if (!docs.empty()) {
1558 const auto& outList = App::PropertyXLink::getDocumentOutList();
1559 for (auto it = docs.begin(); it != docs.end(); ++it) {
1560 auto itd = outList.find(*it);
1561 if (itd != outList.end()) {
1562 for (auto doc : itd->second) {
1563 if (doc != *it) {
1564 docs.erase(doc);
1565 }
1566 }
1567 }
1568 }
1569 for (auto doc : docs) {
1570 FCMD_DOC_CMD(doc, "recompute()");
1571 }
1572 }
1573 }
1574 catch (const Base::Exception& e) {
1575 QMessageBox::critical(
1576 getMainWindow(),
1577 QObject::tr("Delete failed"),
1578 QString::fromLatin1(e.what())
1579 );
1580 e.reportException();
1581 }
1582 catch (...) {
1583 QMessageBox::critical(
1584 getMainWindow(),
1585 QObject::tr("Delete failed"),
1586 QStringLiteral("Unknown error")
1587 );
1588 }
1589 commitCommand();
1590 Gui::getMainWindow()->setUpdatesEnabled(true);
1591 Gui::getMainWindow()->update();
1592 }
1593
1594 bool StdCmdDelete::isActive()
1595 {
1596 return !Selection().getCompleteSelection().empty();
1597 }
1598
1599 //===========================================================================
1600 // Std_Refresh
1601 //===========================================================================
1602 DEF_STD_CMD_A(StdCmdRefresh)
1603
1604 StdCmdRefresh::StdCmdRefresh()
1605 : Command("Std_Refresh")
1606 {
1607 sGroup = "Edit";
1608 sMenuText = QT_TR_NOOP("Recompute");
1609 sToolTipText = QT_TR_NOOP("Recomputes the active document");
1610 sWhatsThis = "Std_Refresh";
1611 sStatusTip = sToolTipText;
1612 sPixmap = "view-refresh";
1613 sAccel = keySequenceToAccel(QKeySequence::Refresh);
1614 eType = AlterDoc | Alter3DView | AlterSelection | ForEdit;
1615 bCanLog = false;
1616
1617 // Make it optional to create a transaction for a recompute.
1618 // The new default behaviour is quite cumbersome in some cases because when
1619 // undoing the last transaction the manual recompute will clear the redo stack.
1620 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
1621 "User parameter:BaseApp/Preferences/Document"
1622 );
1623 bool create = hGrp->GetBool("TransactionOnRecompute", false);
1624 if (!create) {
1625 eType = eType | NoTransaction;
1626 }
1627 }
1628
1629 void StdCmdRefresh::activated([[maybe_unused]] int iMsg)
1630 {
1631 if (!getActiveGuiDocument()) {
1632 return;
1633 }
1634
1635 App::AutoTransaction trans((eType & NoTransaction) ? nullptr : "Recompute");
1636 try {
1637 doCommand(Doc, "App.activeDocument().recompute(None,True,True)");
1638 }
1639 catch (Base::Exception& /*e*/) {
1640 auto ret = QMessageBox::warning(
1641 getMainWindow(),
1642 QObject::tr("Dependency error"),
1643 qApp->translate(
1644 "Std_Refresh",
1645 "The document contains dependency cycles.\n"
1646 "Check the report view for more details.\n\n"
1647 "Proceed?"
1648 ),
1649 QMessageBox::Yes,
1650 QMessageBox::No
1651 );
1652 if (ret == QMessageBox::No) {
1653 return;
1654 }
1655 doCommand(Doc, "App.activeDocument().recompute(None,True)");
1656 }
1657 }
1658
1659 bool StdCmdRefresh::isActive()
1660 {
1661 return this->getDocument() && this->getDocument()->mustExecute();
1662 }
1663
1664 //===========================================================================
1665 // Std_Transform
1666 //===========================================================================
1667 DEF_STD_CMD_A(StdCmdTransform)
1668
1669 StdCmdTransform::StdCmdTransform()
1670 : Command("Std_Transform")
1671 {
1672 sGroup = "Edit";
1673 sMenuText = QT_TR_NOOP("Transform");
1674
1675 sToolTipText = QT_TR_NOOP("Transforms the selected object");
1676 sStatusTip = sToolTipText;
1677 sWhatsThis = "Std_Transform";
1678 }
1679
1680 void StdCmdTransform::activated(int iMsg)
1681 {
1682 Q_UNUSED(iMsg);
1683 Gui::Control().showDialog(new Gui::Dialog::TaskTransform());
1684 }
1685
1686 bool StdCmdTransform::isActive()
1687 {
1688 return (Gui::Control().activeDialog() == nullptr);
1689 }
1690
1691 //===========================================================================
1692 // Std_Placement
1693 //===========================================================================
1694 DEF_STD_CMD_A(StdCmdPlacement)
1695
1696 StdCmdPlacement::StdCmdPlacement()
1697 : Command("Std_Placement")
1698 {
1699 sGroup = "Edit";
1700 sMenuText = QT_TR_NOOP("P&lacement");
1701
1702 sToolTipText = QT_TR_NOOP(
1703 "Opens the placement editor to adjust the placement of the selected object"
1704 );
1705
1706 sStatusTip = sToolTipText;
1707 sWhatsThis = "Std_Placement";
1708 sPixmap = "Std_Placement";
1709 }
1710
1711 void StdCmdPlacement::activated(int iMsg)
1712 {
1713 Q_UNUSED(iMsg);
1714 std::vector<App::DocumentObject*> sel = Gui::Selection().getObjectsOfType(
1715 App::GeoFeature::getClassTypeId()
1716 );
1717 auto plm = new Gui::Dialog::TaskPlacement();
1718 if (!sel.empty()) {
1719 App::Property* prop = sel.front()->getPropertyByName("Placement");
1720 if (prop && prop->is<App::PropertyPlacement>()) {
1721 plm->setPlacement(static_cast<App::PropertyPlacement*>(prop)->getValue());
1722
1723 std::vector<Gui::SelectionObject> selection;
1724 selection.reserve(sel.size());
1725 std::transform(
1726 sel.cbegin(),
1727 sel.cend(),
1728 std::back_inserter(selection),
1729 [](App::DocumentObject* obj) { return Gui::SelectionObject(obj); }
1730 );
1731
1732 plm->setPropertyName(QLatin1String("Placement"));
1733 plm->setSelection(selection);
1734 plm->bindObject();
1735 plm->clearSelection();
1736 }
1737 }
1738 Gui::Control().showDialog(plm);
1739 }
1740
1741 bool StdCmdPlacement::isActive()
1742 {
1743 std::vector<App::DocumentObject*> sel = Gui::Selection().getObjectsOfType(
1744 App::GeoFeature::getClassTypeId()
1745 );
1746 return !(sel.empty() || std::ranges::any_of(sel, [](auto obj) { return obj->isFreezed(); }));
1747 }
1748
1749 //===========================================================================
1750 // Std_TransformManip
1751 //===========================================================================
1752 DEF_STD_CMD_A(StdCmdTransformManip)
1753
1754 StdCmdTransformManip::StdCmdTransformManip()
1755 : Command("Std_TransformManip")
1756 {
1757 sGroup = "Edit";
1758 sMenuText = QT_TR_NOOP("Trans&form");
1759 sToolTipText = QT_TR_NOOP("Transforms the selected object in the 3D view");
1760 sStatusTip = sToolTipText;
1761 sWhatsThis = "Std_TransformManip";
1762 sPixmap = "Std_TransformManip";
1763 }
1764
1765 void StdCmdTransformManip::activated(int iMsg)
1766 {
1767 Q_UNUSED(iMsg);
1768 if (getActiveGuiDocument()->getInEdit()) {
1769 getActiveGuiDocument()->resetEdit();
1770 }
1771 std::vector<App::DocumentObject*> sel = Gui::Selection().getObjectsOfType(
1772 App::GeoFeature::getClassTypeId()
1773 );
1774 Gui::ViewProvider* vp = Application::Instance->getViewProvider(sel.front());
1775 // FIXME: Need a way to force 'Transform' edit mode
1776 // #0000477: Proper interface for edit modes of view provider
1777 if (vp) {
1778 getActiveGuiDocument()->setEdit(vp, Gui::ViewProvider::Transform);
1779 }
1780 }
1781
1782 bool StdCmdTransformManip::isActive()
1783 {
1784 std::vector<App::DocumentObject*> sel = Gui::Selection().getObjectsOfType(
1785 App::GeoFeature::getClassTypeId()
1786 );
1787 return (sel.size() == 1 && !sel.front()->isFreezed());
1788 }
1789
1790 //===========================================================================
1791 // Std_Alignment
1792 //===========================================================================
1793 DEF_STD_CMD_A(StdCmdAlignment)
1794
1795 StdCmdAlignment::StdCmdAlignment()
1796 : Command("Std_Alignment")
1797 {
1798 sGroup = "Edit";
1799 sMenuText = QT_TR_NOOP("Ali&gn To…");
1800
1801 sToolTipText = QT_TR_NOOP("Aligns the selected objects");
1802 sStatusTip = sToolTipText;
1803 sWhatsThis = "Std_Alignment";
1804 sPixmap = "Std_Alignment";
1805 }
1806
1807 void StdCmdAlignment::activated(int iMsg)
1808 {
1809 Q_UNUSED(iMsg);
1810 std::vector<App::DocumentObject*> sel = Gui::Selection().getObjectsOfType(
1811 App::GeoFeature::getClassTypeId()
1812 );
1813 ManualAlignment* align = ManualAlignment::instance();
1814 QObject::connect(align, &ManualAlignment::emitCanceled, align, &QObject::deleteLater);
1815 QObject::connect(align, &ManualAlignment::emitFinished, align, &QObject::deleteLater);
1816
1817 // Get the fixed and moving meshes
1818 FixedGroup fixedGroup;
1819 std::map<int, MovableGroup> groupMap;
1820 fixedGroup.addView(sel[0]);
1821 groupMap[0].addView(sel[1]);
1822
1823 // add the fixed group
1824 align->setFixedGroup(fixedGroup);
1825
1826 // create the model of movable groups
1827 MovableGroupModel model;
1828 model.addGroups(groupMap);
1829 align->setModel(model);
1830 Base::Type style = Base::Type::fromName("Gui::CADNavigationStyle");
1831 Base::Vector3d upDir(0, 1, 0), viewDir(0, 0, -1);
1832 Gui::Document* doc = Application::Instance->activeDocument();
1833 if (doc) {
1834 auto mdi = qobject_cast<View3DInventor*>(doc->getActiveView());
1835 if (mdi) {
1836 View3DInventorViewer* viewer = mdi->getViewer();
1837 SoCamera* camera = viewer->getSoRenderManager()->getCamera();
1838 if (camera) {
1839 SbVec3f up(0, 1, 0), dir(0, 0, -1);
1840 camera->orientation.getValue().multVec(dir, dir);
1841 viewDir.Set(dir[0], dir[1], dir[2]);
1842 camera->orientation.getValue().multVec(up, up);
1843 upDir.Set(up[0], up[1], up[2]);
1844 }
1845 style = viewer->navigationStyle()->getTypeId();
1846 }
1847 }
1848
1849 align->setMinPoints(1);
1850 align->startAlignment(style);
1851 align->setViewingDirections(viewDir, upDir, viewDir, upDir);
1852 Gui::Selection().clearSelection();
1853 }
1854
1855 bool StdCmdAlignment::isActive()
1856 {
1857 if (ManualAlignment::hasInstance()) {
1858 return false;
1859 }
1860 return Gui::Selection().countObjectsOfType<App::GeoFeature>() == 2;
1861 }
1862
1863 //===========================================================================
1864 // Std_Edit
1865 //===========================================================================
1866 DEF_STD_CMD_A(StdCmdEdit)
1867
1868 StdCmdEdit::StdCmdEdit()
1869 : Command("Std_Edit")
1870 {
1871 sGroup = "Edit";
1872 sMenuText = QT_TR_NOOP("Toggle &Edit Mode");
1873 sToolTipText = QT_TR_NOOP("Toggles the selected object's edit mode");
1874 sWhatsThis = "Std_Edit";
1875 sStatusTip = sToolTipText;
1876 sAccel = "";
1877 sPixmap = "edit-edit";
1878 eType = ForEdit;
1879 }
1880
1881 void StdCmdEdit::activated(int iMsg)
1882 {
1883 Q_UNUSED(iMsg);
1884 Gui::MDIView* view = Gui::getMainWindow()->activeWindow();
1885 if (view && view->isDerivedFrom<Gui::View3DInventor>()) {
1886 Gui::View3DInventorViewer* viewer = static_cast<Gui::View3DInventor*>(view)->getViewer();
1887 if (viewer->isEditingViewProvider()) {
1888 doCommand(Command::Gui, "Gui.activeDocument().resetEdit()");
1889 }
1890 else {
1891 if (!Selection().getCompleteSelection().empty()) {
1892 SelectionSingleton::SelObj obj = Selection().getCompleteSelection()[0];
1893 doCommand(Command::Gui, "Gui.activeDocument().setEdit(\"%s\",0)", obj.FeatName);
1894 }
1895 }
1896 }
1897 }
1898
1899 bool StdCmdEdit::isActive()
1900 {
1901 return (!Selection().getCompleteSelection().empty())
1902 || (Gui::Control().activeDialog() != nullptr);
1903 }
1904
1905 //===========================================================================
1906 // Std_Properties
1907 //===========================================================================
1908 DEF_STD_CMD_A(StdCmdProperties)
1909
1910 StdCmdProperties::StdCmdProperties()
1911 : Command("Std_Properties")
1912 {
1913 sGroup = "Edit";
1914 sMenuText = QT_TR_NOOP("Propert&ies");
1915 sToolTipText = QT_TR_NOOP(
1916 "Shows the property view, which displays the properties of the selected object."
1917 );
1918 sWhatsThis = "Std_Properties";
1919 sStatusTip = sToolTipText;
1920 sAccel = "Alt+Return";
1921 sPixmap = "document-properties";
1922 eType = Alter3DView;
1923 }
1924
1925 void StdCmdProperties::activated(int iMsg)
1926 {
1927 Q_UNUSED(iMsg);
1928 auto dw = Gui::DockWindowManager::instance();
1929 if (auto propertyView = dw->getDockWindow("Property view")) {
1930 dw->activate(propertyView);
1931 return;
1932 }
1933 if (auto comboView = dw->getDockWindow("Model")) {
1934 dw->activate(comboView);
1935 return;
1936 }
1937 }
1938
1939 bool StdCmdProperties::isActive()
1940 {
1941 return !Selection().getCompleteSelection().empty();
1942 }
1943
1944 //======================================================================
1945 // StdCmdExpression
1946 //===========================================================================
1947 class StdCmdExpression: public Gui::Command
1948 {
1949 public:
1950 StdCmdExpression()
1951 : Command("Std_Expressions")
1952 {
1953 sGroup = "Edit";
1954 sMenuText = QT_TR_NOOP("Expression Actions");
1955 sToolTipText = QT_TR_NOOP("Actions that apply to expressions");
1956 sWhatsThis = "Std_Expressions";
1957 sStatusTip = sToolTipText;
1958 eType = ForEdit;
1959 }
1960
1961 const char* className() const override
1962 {
1963 return "StdCmdExpression";
1964 }
1965
1966 protected:
1967 void activated(int iMsg) override
1968 {
1969 std::map<App::Document*, std::set<App::DocumentObject*>> objs;
1970 switch (iMsg) {
1971 case 0:
1972 for (auto& sel : Selection().getCompleteSelection()) {
1973 objs[sel.pObject->getDocument()].insert(sel.pObject);
1974 }
1975 break;
1976 case 1:
1977 if (App::GetApplication().getActiveDocument()) {
1978 auto doc = App::GetApplication().getActiveDocument();
1979 auto array = doc->getObjects();
1980 auto& set = objs[doc];
1981 set.insert(array.begin(), array.end());
1982 }
1983 break;
1984 case 2:
1985 for (auto doc : App::GetApplication().getDocuments()) {
1986 auto& set = objs[doc];
1987 auto array = doc->getObjects();
1988 set.insert(array.begin(), array.end());
1989 }
1990 break;
1991 case 3:
1992 pasteExpressions();
1993 break;
1994 }
1995 copyExpressions(objs);
1996 }
1997
1998 Gui::Action* createAction() override
1999 {
2000 auto pcAction = new ActionGroup(this, getMainWindow());
2001 pcAction->setDropDownMenu(true);
2002 applyCommandData(this->className(), pcAction);
2003
2004 pcActionCopySel = pcAction->addAction(QObject::tr("Copy Selected"));
2005 pcActionCopyActive = pcAction->addAction(QObject::tr("Copy Active Document"));
2006 pcActionCopyAll = pcAction->addAction(QObject::tr("Copy All Documents"));
2007 pcActionPaste = pcAction->addAction(QObject::tr("Paste"));
2008
2009 return pcAction;
2010 }
2011
2012 void copyExpressions(const std::map<App::Document*, std::set<App::DocumentObject*>>& objs)
2013 {
2014 std::ostringstream ss;
2015 std::vector<App::Property*> props;
2016 for (auto& v : objs) {
2017 for (auto obj : v.second) {
2018 props.clear();
2019 obj->getPropertyList(props);
2020 for (auto prop : props) {
2021 auto p = dynamic_cast<App::PropertyExpressionContainer*>(prop);
2022 if (!p) {
2023 continue;
2024 }
2025 for (auto& v : p->getExpressions()) {
2026 ss << "##@@ " << v.first.toString() << ' ' << obj->getFullName() << '.'
2027 << p->getName() << " (" << obj->Label.getValue() << ')' << std::endl;
2028 ss << "##@@";
2029 if (!v.second->comment.empty()) {
2030 if (v.second->comment[0] == '&'
2031 || v.second->comment.find('\n') != std::string::npos
2032 || v.second->comment.find('\r') != std::string::npos) {
2033 std::string comment = v.second->comment;
2034 boost::replace_all(comment, "&", "&amp;");
2035 boost::replace_all(comment, "\n", "&#10;");
2036 boost::replace_all(comment, "\r", "&#13;");
2037 ss << '&' << comment;
2038 }
2039 else {
2040 ss << v.second->comment;
2041 }
2042 }
2043 ss << std::endl << v.second->toString(true) << std::endl << std::endl;
2044 }
2045 }
2046 }
2047 }
2048 QApplication::clipboard()->setText(QString::fromUtf8(ss.str().c_str()));
2049 }
2050
2051 void pasteExpressions()
2052 {
2053 std::map<
2054 App::Document*,
2055 std::map<App::PropertyExpressionContainer*, std::map<App::ObjectIdentifier, App::ExpressionPtr>>>
2056 exprs;
2057
2058 bool failed = false;
2059 std::string txt = QApplication::clipboard()->text().toUtf8().constData();
2060 const char* tstart = txt.c_str();
2061 const char* tend = tstart + txt.size();
2062
2063 static boost::regex rule("^##@@ ([^ ]+) (\\w+)#(\\w+)\\.(\\w+) [^\n]+\n##@@([^\n]*)\n");
2064 boost::cmatch m;
2065 if (!boost::regex_search(tstart, m, rule)) {
2066 FC_WARN("No expression header found");
2067 return;
2068 }
2069 boost::cmatch m2;
2070 bool found = true;
2071 for (; found; m = m2) {
2072 found = boost::regex_search(m[0].second, tend, m2, rule);
2073
2074 auto pathName = m.str(1);
2075 auto docName = m.str(2);
2076 auto objName = m.str(3);
2077 auto propName = m.str(4);
2078 auto comment = m.str(5);
2079
2080 App::Document* doc = App::GetApplication().getDocument(docName.c_str());
2081 if (!doc) {
2082 FC_WARN("Cannot find document '" << docName << "'");
2083 continue;
2084 }
2085
2086 auto obj = doc->getObject(objName.c_str());
2087 if (!obj) {
2088 FC_WARN("Cannot find object '" << docName << '#' << objName << "'");
2089 continue;
2090 }
2091
2092 auto prop = dynamic_cast<App::PropertyExpressionContainer*>(
2093 obj->getPropertyByName(propName.c_str())
2094 );
2095 if (!prop) {
2096 FC_WARN("Invalid property '" << docName << '#' << objName << '.' << propName << "'");
2097 continue;
2098 }
2099
2100 size_t len = (found ? m2[0].first : tend) - m[0].second;
2101 try {
2102 App::ExpressionPtr expr(App::Expression::parse(obj, std::string(m[0].second, len)));
2103 if (expr && !comment.empty()) {
2104 if (comment[0] == '&') {
2105 expr->comment = comment.c_str() + 1;
2106 boost::replace_all(expr->comment, "&amp;", "&");
2107 boost::replace_all(expr->comment, "&#10;", "\n");
2108 boost::replace_all(expr->comment, "&#13;", "\r");
2109 }
2110 else {
2111 expr->comment = comment;
2112 }
2113 }
2114 exprs[doc][prop][App::ObjectIdentifier::parse(obj, pathName)] = std::move(expr);
2115 }
2116 catch (Base::Exception& e) {
2117 FC_ERR(e.what() << std::endl << m[0].str());
2118 failed = true;
2119 }
2120 }
2121 if (failed) {
2122 QMessageBox::critical(
2123 getMainWindow(),
2124 QObject::tr("Expression error"),
2125 QObject::tr(
2126 "Failed to parse some of the expressions.\n"
2127 "Check the report view for more details."
2128 )
2129 );
2130 return;
2131 }
2132
2133 openCommand(QT_TRANSLATE_NOOP("Command", "Paste expressions"));
2134 try {
2135 for (auto& v : exprs) {
2136 for (auto& v2 : v.second) {
2137 auto& expressions = v2.second;
2138 auto old = v2.first->getExpressions();
2139 for (auto it = expressions.begin(), itNext = it; it != expressions.end();
2140 it = itNext) {
2141 ++itNext;
2142 auto iter = old.find(it->first);
2143 if (iter != old.end() && it->second->isSame(*iter->second)) {
2144 expressions.erase(it);
2145 }
2146 }
2147 if (!expressions.empty()) {
2148 v2.first->setExpressions(std::move(expressions));
2149 }
2150 }
2151 }
2152 commitCommand();
2153 }
2154 catch (const Base::Exception& e) {
2155 abortCommand();
2156 QMessageBox::critical(
2157 getMainWindow(),
2158 QObject::tr("Failed to paste expressions"),
2159 QString::fromLatin1(e.what())
2160 );
2161 e.reportException();
2162 }
2163 }
2164
2165 bool isActive() override
2166 {
2167 if (!App::GetApplication().getActiveDocument()) {
2168 pcActionCopyAll->setEnabled(false);
2169 pcActionCopySel->setEnabled(false);
2170 pcActionCopyActive->setEnabled(false);
2171 pcActionPaste->setEnabled(false);
2172 return true;
2173 }
2174 pcActionCopyActive->setEnabled(true);
2175 pcActionCopyAll->setEnabled(true);
2176 pcActionCopySel->setEnabled(Selection().hasSelection());
2177
2178 pcActionPaste->setEnabled(QApplication::clipboard()->text().startsWith(QLatin1String("##@@ ")));
2179 return true;
2180 }
2181
2182 QAction* pcActionCopyAll {nullptr};
2183 QAction* pcActionCopySel {nullptr};
2184 QAction* pcActionCopyActive {nullptr};
2185 QAction* pcActionPaste {nullptr};
2186 };
2187
2188 namespace Gui
2189 {
2190
2191 void CreateDocCommands()
2192 {
2193 CommandManager& rcCmdMgr = Application::Instance->commandManager();
2194
2195 rcCmdMgr.addCommand(new StdCmdNew());
2196 rcCmdMgr.addCommand(new StdCmdOpen());
2197 rcCmdMgr.addCommand(new StdCmdImport());
2198 rcCmdMgr.addCommand(new StdCmdExport());
2199 rcCmdMgr.addCommand(new StdCmdMergeProjects());
2200 rcCmdMgr.addCommand(new StdCmdDependencyGraph());
2201 rcCmdMgr.addCommand(new StdCmdExportDependencyGraph());
2202
2203 rcCmdMgr.addCommand(new StdCmdSave());
2204 rcCmdMgr.addCommand(new StdCmdSaveAs());
2205 rcCmdMgr.addCommand(new StdCmdSaveCopy());
2206 rcCmdMgr.addCommand(new StdCmdSaveAll());
2207 rcCmdMgr.addCommand(new StdCmdRevert());
2208 rcCmdMgr.addCommand(new StdCmdProjectInfo());
2209 rcCmdMgr.addCommand(new StdCmdProjectUtil());
2210 rcCmdMgr.addCommand(new StdCmdUndo());
2211 rcCmdMgr.addCommand(new StdCmdRedo());
2212 rcCmdMgr.addCommand(new StdCmdPrint());
2213 rcCmdMgr.addCommand(new StdCmdPrintPreview());
2214 rcCmdMgr.addCommand(new StdCmdPrintPdf());
2215 rcCmdMgr.addCommand(new StdCmdQuit());
2216 rcCmdMgr.addCommand(new StdCmdCut());
2217 rcCmdMgr.addCommand(new StdCmdCopy());
2218 rcCmdMgr.addCommand(new StdCmdPaste());
2219 rcCmdMgr.addCommand(new StdCmdDuplicateSelection());
2220 rcCmdMgr.addCommand(new StdCmdSelectAll());
2221 rcCmdMgr.addCommand(new StdCmdDelete());
2222 rcCmdMgr.addCommand(new StdCmdRefresh());
2223 rcCmdMgr.addCommand(new StdCmdTransform());
2224 rcCmdMgr.addCommand(new StdCmdPlacement());
2225 rcCmdMgr.addCommand(new StdCmdTransformManip());
2226 rcCmdMgr.addCommand(new StdCmdAlignment());
2227 rcCmdMgr.addCommand(new StdCmdEdit());
2228 rcCmdMgr.addCommand(new StdCmdProperties());
2229 rcCmdMgr.addCommand(new StdCmdExpression());
2230 }
2231
2232 } // namespace Gui