forked from FreeCAD/FreeCAD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Application.cpp
2513 lines (2233 loc) · 91.5 KB
/
Application.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/interprocess/sync/file_lock.hpp>
# include <Inventor/errors/SoDebugError.h>
# include <Inventor/errors/SoError.h>
# include <QCloseEvent>
# include <QDir>
# include <QFileInfo>
# include <QLocale>
# include <QMessageBox>
# include <QMessageLogContext>
# include <QStatusBar>
# include <QStyle>
# include <QTextStream>
# include <QTimer>
# include <QWindow>
#endif
#include <App/Document.h>
#include <App/DocumentObjectPy.h>
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/Parameter.h>
#include <Base/Stream.h>
#include <Base/Tools.h>
#include <Language/Translator.h>
#include <Quarter/Quarter.h>
#include "Application.h"
#include "AutoSaver.h"
#include "AxisOriginPy.h"
#include "BitmapFactory.h"
#include "Command.h"
#include "CommandPy.h"
#include "Control.h"
#include "DlgSettingsCacheDirectory.h"
#include "DocumentPy.h"
#include "DocumentRecovery.h"
#include "EditorView.h"
#include "ExpressionBindingPy.h"
#include "FileDialog.h"
#include "GuiApplication.h"
#include "GuiInitScript.h"
#include "LinkViewPy.h"
#include "MainWindow.h"
#include "Macro.h"
#include "PreferencePackManager.h"
#include "PythonConsolePy.h"
#include "PythonDebugger.h"
#include "MainWindowPy.h"
#include "MDIViewPy.h"
#include "SoFCDB.h"
#include "Selection.h"
#include "SplitView3DInventor.h"
#include "TaskView/TaskView.h"
#include "TaskView/TaskDialogPython.h"
#include "TransactionObject.h"
#include "TextDocumentEditorView.h"
#include "UiLoader.h"
#include "View3DPy.h"
#include "View3DViewerPy.h"
#include "View3DInventor.h"
#include "ViewProviderAnnotation.h"
#include "ViewProviderDocumentObject.h"
#include "ViewProviderDocumentObjectGroup.h"
#include "ViewProviderDragger.h"
#include "ViewProviderExtension.h"
#include "ViewProviderExtern.h"
#include "ViewProviderFeature.h"
#include "ViewProviderGeoFeatureGroup.h"
#include "ViewProviderGeometryObject.h"
#include "ViewProviderGroupExtension.h"
#include "ViewProviderInventorObject.h"
#include "ViewProviderLine.h"
#include "ViewProviderLink.h"
#include "ViewProviderLinkPy.h"
#include "ViewProviderMaterialObject.h"
#include "ViewProviderMeasureDistance.h"
#include "ViewProviderOrigin.h"
#include "ViewProviderOriginFeature.h"
#include "ViewProviderOriginGroup.h"
#include "ViewProviderPlacement.h"
#include "ViewProviderPlane.h"
#include "ViewProviderPart.h"
#include "ViewProviderPythonFeature.h"
#include "ViewProviderTextDocument.h"
#include "ViewProviderVRMLObject.h"
#include "WaitCursor.h"
#include "Workbench.h"
#include "WorkbenchManager.h"
#include "WidgetFactory.h"
#include "SelectionSummary.h"
using namespace Gui;
using namespace Gui::DockWnd;
using namespace std;
namespace sp = std::placeholders;
Application* Application::Instance = nullptr;
namespace Gui {
class ViewProviderMap {
std::unordered_map<const App::DocumentObject *, ViewProvider *> map;
public:
void newObject(const ViewProvider& vp)
{
auto vpd = Base::freecad_dynamic_cast<ViewProviderDocumentObject>(const_cast<ViewProvider*>(&vp));
if (vpd && vpd->getObject())
map[vpd->getObject()] = vpd;
}
void deleteObject(const ViewProvider& vp)
{
auto vpd = Base::freecad_dynamic_cast<ViewProviderDocumentObject>(const_cast<ViewProvider*>(&vp));
if (vpd && vpd->getObject())
map.erase(vpd->getObject());
}
void deleteDocument(const App::Document& doc) {
for (auto obj : doc.getObjects())
map.erase(obj);
}
Gui::ViewProvider* getViewProvider(const App::DocumentObject* obj) const
{
auto it = map.find(obj);
if (it == map.end())
return nullptr;
return it->second;
}
};
// Pimpl class
struct ApplicationP
{
ApplicationP(bool GUIenabled) :
activeDocument(nullptr),
editDocument(nullptr),
isClosing(false),
startingUp(true)
{
// create the macro manager
if (GUIenabled)
macroMngr = new MacroManager();
else
macroMngr = nullptr;
// Create the Theme Manager
prefPackManager = new PreferencePackManager();
}
~ApplicationP()
{
delete macroMngr;
delete prefPackManager;
}
/// list of all handled documents
std::map<const App::Document*, Gui::Document*> documents;
/// Active document
Gui::Document* activeDocument;
Gui::Document* editDocument;
MacroManager* macroMngr;
PreferencePackManager* prefPackManager;
/// List of all registered views
std::list<Gui::BaseView*> passive;
bool isClosing;
bool startingUp;
/// Handles all commands
CommandManager commandManager;
ViewProviderMap viewproviderMap;
};
static PyObject *
FreeCADGui_subgraphFromObject(PyObject * /*self*/, PyObject *args)
{
PyObject *o;
if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type), &o))
return nullptr;
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(o)->getDocumentObjectPtr();
std::string vp = obj->getViewProviderName();
SoNode* node = nullptr;
try {
Base::BaseClass* base = static_cast<Base::BaseClass*>(Base::Type::createInstanceByName(vp.c_str(), true));
if (base && base->getTypeId().isDerivedFrom(Gui::ViewProviderDocumentObject::getClassTypeId())) {
std::unique_ptr<Gui::ViewProviderDocumentObject> vp(static_cast<Gui::ViewProviderDocumentObject*>(base));
std::map<std::string, App::Property*> Map;
obj->getPropertyMap(Map);
vp->attach(obj);
// this is needed to initialize Python-based view providers
App::Property* pyproxy = vp->getPropertyByName("Proxy");
if (pyproxy && pyproxy->getTypeId() == App::PropertyPythonObject::getClassTypeId()) {
static_cast<App::PropertyPythonObject*>(pyproxy)->setValue(Py::Long(1));
}
for (std::map<std::string, App::Property*>::iterator it = Map.begin(); it != Map.end(); ++it) {
vp->updateData(it->second);
}
std::vector<std::string> modes = vp->getDisplayModes();
if (!modes.empty())
vp->setDisplayMode(modes.front().c_str());
node = vp->getRoot()->copy();
node->ref();
std::string prefix = "So";
std::string type = node->getTypeId().getName().getString();
// doesn't start with the prefix 'So'
if (type.rfind("So", 0) != 0) {
type = prefix + type;
}
else if (type == "SoFCSelectionRoot") {
type = "SoSeparator";
}
type += " *";
PyObject* proxy = nullptr;
proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", type.c_str(), (void*)node, 1);
return Py::new_reference_to(Py::Object(proxy, true));
}
}
catch (const Base::Exception& e) {
if (node) node->unref();
PyErr_SetString(PyExc_RuntimeError, e.what());
return nullptr;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
FreeCADGui_exportSubgraph(PyObject * /*self*/, PyObject *args)
{
const char* format = "VRML";
PyObject* proxy;
PyObject* output;
if (!PyArg_ParseTuple(args, "OO|s", &proxy, &output, &format))
return nullptr;
void* ptr = nullptr;
try {
Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoNode *", proxy, &ptr, 0);
SoNode* node = reinterpret_cast<SoNode*>(ptr);
if (node) {
std::string formatStr(format);
std::string buffer;
if (formatStr == "VRML") {
SoFCDB::writeToVRML(node, buffer);
}
else if (formatStr == "IV") {
buffer = SoFCDB::writeNodesToString(node);
}
else {
throw Base::ValueError("Unsupported format");
}
Base::PyStreambuf buf(output);
std::ostream str(nullptr);
str.rdbuf(&buf);
str << buffer;
}
Py_INCREF(Py_None);
return Py_None;
}
catch (const Base::Exception& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
return nullptr;
}
}
static PyObject *
FreeCADGui_getSoDBVersion(PyObject * /*self*/, PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return nullptr;
return PyUnicode_FromString(SoDB::getVersion());
}
struct PyMethodDef FreeCADGui_methods[] = {
{"subgraphFromObject",FreeCADGui_subgraphFromObject,METH_VARARGS,
"subgraphFromObject(object) -> Node\n\n"
"Return the Inventor subgraph to an object"},
{"exportSubgraph",FreeCADGui_exportSubgraph,METH_VARARGS,
"exportSubgraph(Node, File or Buffer, [Format='VRML']) -> None\n\n"
"Exports the sub-graph in the requested format"
"The format string can be VRML or IV"},
{"getSoDBVersion",FreeCADGui_getSoDBVersion,METH_VARARGS,
"getSoDBVersion() -> String\n\n"
"Return a text string containing the name\n"
"of the Coin library and version information"},
{nullptr, nullptr, 0, nullptr} /* sentinel */
};
} // namespace Gui
SelectionSummary* summary;
Application::Application(bool GUIenabled)
{
//App::GetApplication().Attach(this);
if (GUIenabled) {
App::GetApplication().signalNewDocument.connect(std::bind(&Gui::Application::slotNewDocument, this, sp::_1, sp::_2));
App::GetApplication().signalDeleteDocument.connect(std::bind(&Gui::Application::slotDeleteDocument, this, sp::_1));
App::GetApplication().signalRenameDocument.connect(std::bind(&Gui::Application::slotRenameDocument, this, sp::_1));
App::GetApplication().signalActiveDocument.connect(std::bind(&Gui::Application::slotActiveDocument, this, sp::_1));
App::GetApplication().signalRelabelDocument.connect(std::bind(&Gui::Application::slotRelabelDocument, this, sp::_1));
App::GetApplication().signalShowHidden.connect(std::bind(&Gui::Application::slotShowHidden, this, sp::_1));
// install the last active language
ParameterGrp::handle hPGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp");
hPGrp = hPGrp->GetGroup("Preferences")->GetGroup("General");
QString lang = QLocale::languageToString(QLocale().language());
Translator::instance()->activateLanguage(hPGrp->GetASCII("Language", (const char*)lang.toLatin1()).c_str());
GetWidgetFactorySupplier();
// Coin3d disabled VBO support for all Intel drivers but in the meantime they have improved
// so we can try to override the workaround by setting COIN_VBO
ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
if (hViewGrp->GetBool("UseVBO",false)) {
(void)coin_setenv("COIN_VBO", "0", true);
}
// Check for the symbols for group separator and decimal point. They must be different otherwise
// Qt doesn't work properly.
#if defined(Q_OS_WIN32)
if (QLocale().groupSeparator() == QLocale().decimalPoint()) {
QMessageBox::critical(0, QLatin1String("Invalid system settings"),
QLatin1String("Your system uses the same symbol for decimal point and group separator.\n\n"
"This causes serious problems and makes the application fail to work properly.\n"
"Go to the system configuration panel of the OS and fix this issue, please."));
throw Base::RuntimeError("Invalid system settings");
}
#endif
#if 0 // QuantitySpinBox and InputField try to handle the group separator now
// http://forum.freecadweb.org/viewtopic.php?f=10&t=6910
// A workaround is to disable the group separator for double-to-string conversion, i.e.
// setting the flag 'OmitGroupSeparator'.
QLocale loc;
loc.setNumberOptions(QLocale::OmitGroupSeparator);
QLocale::setDefault(loc);
#endif
// setting up Python binding
Base::PyGILStateLocker lock;
PyDoc_STRVAR(FreeCADGui_doc,
"The functions in the FreeCADGui module allow working with GUI documents,\n"
"view providers, views, workbenches and much more.\n\n"
"The FreeCADGui instance provides a list of references of GUI documents which\n"
"can be addressed by a string. These documents contain the view providers for\n"
"objects in the associated App document. An App and GUI document can be\n"
"accessed with the same name.\n\n"
"The FreeCADGui module also provides a set of functions to work with so called\n"
"workbenches."
);
// if this returns a valid pointer then the 'FreeCADGui' Python module was loaded,
// otherwise the executable was launched
PyObject* modules = PyImport_GetModuleDict();
PyObject* module = PyDict_GetItemString(modules, "FreeCADGui");
if (!module) {
static struct PyModuleDef FreeCADGuiModuleDef = {
PyModuleDef_HEAD_INIT,
"FreeCADGui", FreeCADGui_doc, -1,
Application::Methods,
nullptr, nullptr, nullptr, nullptr
};
module = PyModule_Create(&FreeCADGuiModuleDef);
PyDict_SetItemString(modules, "FreeCADGui", module);
}
else {
// extend the method list
PyModule_AddFunctions(module, Application::Methods);
}
Py::Module(module).setAttr(std::string("ActiveDocument"),Py::None());
UiLoaderPy::init_type();
Base::Interpreter().addType(UiLoaderPy::type_object(),
module,"UiLoader");
PyResource::init_type();
// PySide additions
PyModule_AddObject(module, "PySideUic", Base::Interpreter().addModule(new PySideUicModule));
ExpressionBindingPy::init_type();
Base::Interpreter().addType(ExpressionBindingPy::type_object(),
module,"ExpressionBinding");
//insert Selection module
static struct PyModuleDef SelectionModuleDef = {
PyModuleDef_HEAD_INIT,
"Selection", "Selection module", -1,
SelectionSingleton::Methods,
nullptr, nullptr, nullptr, nullptr
};
PyObject* pSelectionModule = PyModule_Create(&SelectionModuleDef);
Py_INCREF(pSelectionModule);
PyModule_AddObject(module, "Selection", pSelectionModule);
SelectionFilterPy::init_type();
Base::Interpreter().addType(SelectionFilterPy::type_object(),
pSelectionModule,"Filter");
Gui::TaskView::ControlPy::init_type();
Py::Module(module).setAttr(std::string("Control"),
Py::Object(Gui::TaskView::ControlPy::getInstance(), true));
Base::Interpreter().addType(&LinkViewPy::Type,module,"LinkView");
Base::Interpreter().addType(&AxisOriginPy::Type,module,"AxisOrigin");
Base::Interpreter().addType(&CommandPy::Type,module, "Command");
Base::Interpreter().addType(&DocumentPy::Type, module, "Document");
Base::Interpreter().addType(&ViewProviderPy::Type, module, "ViewProvider");
Base::Interpreter().addType(&ViewProviderDocumentObjectPy::Type, module, "ViewProviderDocumentObject");
Base::Interpreter().addType(&ViewProviderLinkPy::Type, module, "ViewProviderLink");
}
Base::PyGILStateLocker lock;
PyObject *module = PyImport_AddModule("FreeCADGui");
PyMethodDef *meth = FreeCADGui_methods;
PyObject *dict = PyModule_GetDict(module);
for (; meth->ml_name != nullptr; meth++) {
PyObject *descr;
descr = PyCFunction_NewEx(meth,nullptr,nullptr);
if (descr == nullptr)
break;
if (PyDict_SetItemString(dict, meth->ml_name, descr) != 0)
break;
Py_DECREF(descr);
}
App::Application::Config()["COIN_VERSION"] = COIN_VERSION;
// Python console binding
PythonDebugModule ::init_module();
PythonStdout ::init_type();
PythonStderr ::init_type();
OutputStdout ::init_type();
OutputStderr ::init_type();
PythonStdin ::init_type();
MainWindowPy ::init_type();
MDIViewPy ::init_type();
View3DInventorPy ::init_type();
View3DInventorViewerPy ::init_type();
AbstractSplitViewPy ::init_type();
d = new ApplicationP(GUIenabled);
// global access
Instance = this;
// instantiate the workbench dictionary
_pcWorkbenchDictionary = PyDict_New();
if (GUIenabled) {
createStandardOperations();
MacroCommand::load();
}
// TODO find idiomatically correct way to trigger class instantation
summary = new SelectionSummary();
}
Application::~Application()
{
Base::Console().Log("Destruct Gui::Application\n");
WorkbenchManager::destruct();
SelectionSingleton::destruct();
Translator::destruct();
WidgetFactorySupplier::destruct();
BitmapFactoryInst::destruct();
#if 0
// we must run the garbage collector before shutting down the SoDB
// subsystem because we may reference some class objects of them in Python
Base::Interpreter().cleanupSWIG("SoBase *");
// finish also Inventor subsystem
SoFCDB::finish();
#if (COIN_MAJOR_VERSION >= 2) && (COIN_MINOR_VERSION >= 4)
SoDB::finish();
#elif (COIN_MAJOR_VERSION >= 3)
SoDB::finish();
#else
SoDB::cleanup();
#endif
#endif
{
Base::PyGILStateLocker lock;
Py_DECREF(_pcWorkbenchDictionary);
}
// save macros
try {
MacroCommand::save();
}
catch (const Base::Exception& e) {
std::cerr << "Saving macros failed: " << e.what() << std::endl;
}
//App::GetApplication().Detach(this);
delete d;
Instance = nullptr;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// creating std commands
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void Application::open(const char* FileName, const char* Module)
{
WaitCursor wc;
wc.setIgnoreEvents(WaitCursor::NoEvents);
Base::FileInfo File(FileName);
string te = File.extension();
string unicodepath = Base::Tools::escapedUnicodeFromUtf8(File.filePath().c_str());
unicodepath = Base::Tools::escapeEncodeFilename(unicodepath);
// if the active document is empty and not modified, close it
// in case of an automatically created empty document at startup
App::Document* act = App::GetApplication().getActiveDocument();
Gui::Document* gui = this->getDocument(act);
if (act && act->countObjects() == 0 && gui && gui->isModified() == false){
Command::doCommand(Command::App, "App.closeDocument('%s')", act->getName());
qApp->processEvents(); // an update is needed otherwise the new view isn't shown
}
if (Module != nullptr) {
try {
if (File.hasExtension("FCStd")) {
bool handled = false;
std::string filepath = File.filePath();
for (auto &v : d->documents) {
auto doc = v.second->getDocument();
std::string fi = Base::FileInfo(doc->FileName.getValue()).filePath();
if (filepath == fi) {
handled = true;
Command::doCommand(Command::App, "FreeCADGui.reload('%s')", doc->getName());
break;
}
}
if (!handled)
Command::doCommand(Command::App, "FreeCAD.openDocument('%s')", unicodepath.c_str());
}
else {
// issue module loading
Command::doCommand(Command::App, "import %s", Module);
// load the file with the module
Command::doCommand(Command::App, "%s.open(u\"%s\")", Module, unicodepath.c_str());
// ViewFit
if (sendHasMsgToActiveView("ViewFit")) {
ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath
("User parameter:BaseApp/Preferences/View");
if (hGrp->GetBool("AutoFitToView", true))
Command::doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewFit\")");
}
}
// the original file name is required
QString filename = QString::fromUtf8(File.filePath().c_str());
getMainWindow()->appendRecentFile(filename);
FileDialog::setWorkingDirectory(filename);
}
catch (const Base::PyException& e){
// Usually thrown if the file is invalid somehow
e.ReportException();
}
}
else {
wc.restoreCursor();
QMessageBox::warning(getMainWindow(), QObject::tr("Unknown filetype"),
QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str())));
wc.setWaitCursor();
return;
}
}
void Application::importFrom(const char* FileName, const char* DocName, const char* Module)
{
WaitCursor wc;
wc.setIgnoreEvents(WaitCursor::NoEvents);
Base::FileInfo File(FileName);
std::string te = File.extension();
string unicodepath = Base::Tools::escapedUnicodeFromUtf8(File.filePath().c_str());
unicodepath = Base::Tools::escapeEncodeFilename(unicodepath);
if (Module != nullptr) {
try {
// issue module loading
Command::doCommand(Command::App, "import %s", Module);
// load the file with the module
if (File.hasExtension("FCStd")) {
Command::doCommand(Command::App, "%s.open(u\"%s\")"
, Module, unicodepath.c_str());
if (activeDocument())
activeDocument()->setModified(false);
}
else {
// Open transaction when importing a file
Gui::Document* doc = DocName ? getDocument(DocName) : activeDocument();
bool pendingCommand = false;
if (doc) {
pendingCommand = doc->hasPendingCommand();
if (!pendingCommand)
doc->openCommand(QT_TRANSLATE_NOOP("Command", "Import"));
}
if (DocName) {
Command::doCommand(Command::App, "%s.insert(u\"%s\",\"%s\")"
, Module, unicodepath.c_str(), DocName);
}
else {
Command::doCommand(Command::App, "%s.insert(u\"%s\")"
, Module, unicodepath.c_str());
}
// Commit the transaction
if (doc && !pendingCommand) {
doc->commitCommand();
}
// It's possible that before importing a file the document with the
// given name doesn't exist or there is no active document.
// The import function then may create a new document.
if (!doc) {
doc = activeDocument();
}
if (doc) {
doc->setModified(true);
ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath
("User parameter:BaseApp/Preferences/View");
if (hGrp->GetBool("AutoFitToView", true)) {
MDIView* view = doc->getActiveView();
if (view) {
const char* ret = nullptr;
if (view->onMsg("ViewFit", &ret))
updateActions(true);
}
}
}
}
// the original file name is required
QString filename = QString::fromUtf8(File.filePath().c_str());
auto parameterGroup = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General");
bool addToRecent = parameterGroup->GetBool("RecentIncludesImported", true);
parameterGroup->SetBool("RecentIncludesImported", addToRecent); // Make sure it gets added to the parameter list
if (addToRecent) {
getMainWindow()->appendRecentFile(filename);
}
FileDialog::setWorkingDirectory(filename);
}
catch (const Base::PyException& e){
// Usually thrown if the file is invalid somehow
e.ReportException();
}
}
else {
wc.restoreCursor();
QMessageBox::warning(getMainWindow(), QObject::tr("Unknown filetype"),
QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str())));
wc.setWaitCursor();
}
}
void Application::exportTo(const char* FileName, const char* DocName, const char* Module)
{
WaitCursor wc;
wc.setIgnoreEvents(WaitCursor::NoEvents);
Base::FileInfo File(FileName);
std::string te = File.extension();
string unicodepath = Base::Tools::escapedUnicodeFromUtf8(File.filePath().c_str());
unicodepath = Base::Tools::escapeEncodeFilename(unicodepath);
if (Module != nullptr) {
try {
std::vector<App::DocumentObject*> sel = Gui::Selection().getObjectsOfType
(App::DocumentObject::getClassTypeId(),DocName);
if (sel.empty()) {
App::Document* doc = App::GetApplication().getDocument(DocName);
sel = doc->getObjectsOfType(App::DocumentObject::getClassTypeId());
}
std::stringstream str;
std::set<App::DocumentObject*> unique_objs;
str << "__objs__=[]" << std::endl;
for (std::vector<App::DocumentObject*>::iterator it = sel.begin(); it != sel.end(); ++it) {
if (unique_objs.insert(*it).second) {
str << "__objs__.append(FreeCAD.getDocument(\"" << DocName << "\").getObject(\""
<< (*it)->getNameInDocument() << "\"))" << std::endl;
}
}
str << "import " << Module << std::endl;
str << Module << ".export(__objs__,u\"" << unicodepath << "\")" << std::endl;
//str << "del __objs__" << std::endl;
std::string code = str.str();
// the original file name is required
Gui::Command::runCommand(Gui::Command::App, code.c_str());
auto parameterGroup = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General");
bool addToRecent = parameterGroup->GetBool("RecentIncludesExported", false);
parameterGroup->SetBool("RecentIncludesExported", addToRecent); // Make sure it gets added to the parameter list
if (addToRecent) {
// search for a module that is able to open the exported file because otherwise
// it doesn't need to be added to the recent files list (#0002047)
std::map<std::string, std::string> importMap = App::GetApplication().getImportFilters(te.c_str());
if (!importMap.empty())
getMainWindow()->appendRecentFile(QString::fromUtf8(File.filePath().c_str()));
}
// allow exporters to pass _objs__ to submodules before deleting it
Gui::Command::runCommand(Gui::Command::App, "del __objs__");
}
catch (const Base::PyException& e){
// Usually thrown if the file is invalid somehow
e.ReportException();
wc.restoreCursor();
QMessageBox::critical(getMainWindow(), QObject::tr("Export failed"),
QString::fromUtf8(e.what()));
wc.setWaitCursor();
}
}
else {
wc.restoreCursor();
QMessageBox::warning(getMainWindow(), QObject::tr("Unknown filetype"),
QObject::tr("Cannot save to unknown filetype: %1").arg(QLatin1String(te.c_str())));
wc.setWaitCursor();
}
}
void Application::createStandardOperations()
{
// register the application Standard commands from CommandStd.cpp
Gui::CreateStdCommands();
Gui::CreateDocCommands();
Gui::CreateFeatCommands();
Gui::CreateMacroCommands();
Gui::CreateViewStdCommands();
Gui::CreateWindowStdCommands();
Gui::CreateStructureCommands();
Gui::CreateTestCommands();
Gui::CreateLinkCommands();
}
void Application::slotNewDocument(const App::Document& Doc, bool isMainDoc)
{
#ifdef FC_DEBUG
std::map<const App::Document*, Gui::Document*>::const_iterator it = d->documents.find(&Doc);
assert(it==d->documents.end());
#endif
Gui::Document* pDoc = new Gui::Document(const_cast<App::Document*>(&Doc),this);
d->documents[&Doc] = pDoc;
// connect the signals to the application for the new document
pDoc->signalNewObject.connect(std::bind(&Gui::Application::slotNewObject, this, sp::_1));
pDoc->signalDeletedObject.connect(std::bind(&Gui::Application::slotDeletedObject, this, sp::_1));
pDoc->signalChangedObject.connect(std::bind(&Gui::Application::slotChangedObject, this, sp::_1, sp::_2));
pDoc->signalRelabelObject.connect(std::bind(&Gui::Application::slotRelabelObject, this, sp::_1));
pDoc->signalActivatedObject.connect(std::bind(&Gui::Application::slotActivatedObject, this, sp::_1));
pDoc->signalInEdit.connect(std::bind(&Gui::Application::slotInEdit, this, sp::_1));
pDoc->signalResetEdit.connect(std::bind(&Gui::Application::slotResetEdit, this, sp::_1));
signalNewDocument(*pDoc, isMainDoc);
if (isMainDoc)
pDoc->createView(View3DInventor::getClassTypeId());
}
void Application::slotDeleteDocument(const App::Document& Doc)
{
std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
if (doc == d->documents.end()) {
Base::Console().Log("GUI document '%s' already deleted\n", Doc.getName());
return;
}
// Inside beforeDelete() a view provider may finish editing mode
// and therefore can alter the selection.
doc->second->beforeDelete();
// We must clear the selection here to notify all observers.
// And because of possible cross document link, better clear all selection
// to be safe
Gui::Selection().clearCompleteSelection();
doc->second->signalDeleteDocument(*doc->second);
signalDeleteDocument(*doc->second);
// If the active document gets destructed we must set it to 0. If there are further existing documents then the
// view that becomes active sets the active document again. So, we needn't worry about this.
if (d->activeDocument == doc->second)
setActiveDocument(nullptr);
d->viewproviderMap.deleteDocument(Doc);
// For exception-safety use a smart pointer
unique_ptr<Document> delDoc (doc->second);
d->documents.erase(doc);
}
void Application::slotRelabelDocument(const App::Document& Doc)
{
std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
#ifdef FC_DEBUG
assert(doc!=d->documents.end());
#endif
signalRelabelDocument(*doc->second);
doc->second->onRelabel();
}
void Application::slotRenameDocument(const App::Document& Doc)
{
std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
#ifdef FC_DEBUG
assert(doc!=d->documents.end());
#endif
signalRenameDocument(*doc->second);
}
void Application::slotShowHidden(const App::Document& Doc)
{
std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
#ifdef FC_DEBUG
assert(doc!=d->documents.end());
#endif
signalShowHidden(*doc->second);
}
void Application::slotActiveDocument(const App::Document& Doc)
{
std::map<const App::Document*, Gui::Document*>::iterator doc = d->documents.find(&Doc);
// this can happen when closing a document with two views opened
if (doc != d->documents.end()) {
// this can happen when calling App.setActiveDocument directly from Python
// because no MDI view will be activated
if (d->activeDocument != doc->second) {
d->activeDocument = doc->second;
if (d->activeDocument) {
Base::PyGILStateLocker lock;
Py::Object active(d->activeDocument->getPyObject(), true);
Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"),active);
auto view = getMainWindow()->activeWindow();
if(!view || view->getAppDocument()!=&Doc) {
Gui::MDIView* view = d->activeDocument->getActiveView();
getMainWindow()->setActiveWindow(view);
}
}
else {
Base::PyGILStateLocker lock;
Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"),Py::None());
}
}
signalActiveDocument(*doc->second);
updateActions();
}
}
void Application::slotNewObject(const ViewProvider& vp)
{
d->viewproviderMap.newObject(vp);
this->signalNewObject(vp);
}
void Application::slotDeletedObject(const ViewProvider& vp)
{
this->signalDeletedObject(vp);
d->viewproviderMap.deleteObject(vp);
}
void Application::slotChangedObject(const ViewProvider& vp, const App::Property& prop)
{
this->signalChangedObject(vp,prop);
updateActions(true);
}
void Application::slotRelabelObject(const ViewProvider& vp)
{
this->signalRelabelObject(vp);
}
void Application::slotActivatedObject(const ViewProvider& vp)
{
this->signalActivatedObject(vp);
updateActions();
}
void Application::slotInEdit(const Gui::ViewProviderDocumentObject& vp)
{
this->signalInEdit(vp);
}
void Application::slotResetEdit(const Gui::ViewProviderDocumentObject& vp)
{
this->signalResetEdit(vp);
}
void Application::onLastWindowClosed(Gui::Document* pcDoc)
{
try {
if (!d->isClosing && pcDoc) {
// Call the closing mechanism from Python. This also checks whether pcDoc is the last open document.
Command::doCommand(Command::Doc, "App.closeDocument(\"%s\")", pcDoc->getDocument()->getName());
if (!d->activeDocument && d->documents.size()) {
Document *gdoc = nullptr;
for(auto &v : d->documents) {
if (v.second->getDocument()->testStatus(App::Document::TempDoc))
continue;
else if (!gdoc)
gdoc = v.second;
Gui::MDIView* view = v.second->getActiveView();
if (view) {
setActiveDocument(v.second);
getMainWindow()->setActiveWindow(view);
return;
}
}
if (gdoc) {
setActiveDocument(gdoc);
activateView(View3DInventor::getClassTypeId(),true);
}
}
}
}
catch (const Base::Exception& e) {
e.ReportException();
}
catch (const Py::Exception&) {
Base::PyException e;
e.ReportException();
}
catch (const std::exception& e) {
Base::Console().Error("Unhandled std::exception caught in Application::onLastWindowClosed.\n"
"The error message is: %s\n", e.what());
}
catch (...) {
Base::Console().Error("Unhandled unknown exception caught in Application::onLastWindowClosed.\n");
}
}
/// send Messages to the active view
bool Application::sendMsgToActiveView(const char* pMsg, const char** ppReturn)
{
MDIView* pView = getMainWindow()->activeWindow();
bool res = pView ? pView->onMsg(pMsg,ppReturn) : false;
updateActions(true);
return res;
}
bool Application::sendHasMsgToActiveView(const char* pMsg)
{
MDIView* pView = getMainWindow()->activeWindow();
return pView ? pView->onHasMsg(pMsg) : false;
}
/// send Messages to the active view
bool Application::sendMsgToFocusView(const char* pMsg, const char** ppReturn)
{
MDIView* pView = getMainWindow()->activeWindow();
if(!pView)