/
Application.cpp
2081 lines (1869 loc) · 75.6 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 Juergen 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 "InventorAll.h"
# include <boost/signals.hpp>
# include <boost/bind.hpp>
# include <sstream>
# include <stdexcept>
# include <iostream>
# include <QCloseEvent>
# include <QDir>
# include <QFileInfo>
# include <QLocale>
# include <QMessageBox>
#if QT_VERSION >= 0x050000
# include <QMessageLogContext>
#endif
# include <QPointer>
# include <QSessionManager>
# include <QStatusBar>
# include <QTextStream>
# include <QTimer>
#endif
#include <boost/interprocess/sync/file_lock.hpp>
#include <QtOpenGL.h>
#if defined(HAVE_QT5_OPENGL)
#include <QWindow>
#endif
// FreeCAD Base header
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
#include <Base/Factory.h>
#include <Base/FileInfo.h>
#include <Base/Tools.h>
#include <Base/UnitsApi.h>
#include <App/Document.h>
#include <App/DocumentObjectPy.h>
#include "Application.h"
#include "AutoSaver.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "Document.h"
#include "View.h"
#include "View3DPy.h"
#include "WidgetFactory.h"
#include "Command.h"
#include "Macro.h"
#include "ProgressBar.h"
#include "Workbench.h"
#include "WorkbenchManager.h"
#include "ToolBoxManager.h"
#include "WaitCursor.h"
#include "MenuManager.h"
#include "Window.h"
#include "Selection.h"
#include "BitmapFactory.h"
#include "SoFCDB.h"
#include "PythonConsolePy.h"
#include "PythonDebugger.h"
#include "View3DPy.h"
#include "DlgOnlineHelpImp.h"
#include "SpaceballEvent.h"
#include "Control.h"
#include "DocumentRecovery.h"
#include "TransactionObject.h"
#include "FileDialog.h"
#include "SplitView3DInventor.h"
#include "View3DInventor.h"
#include "ViewProvider.h"
#include "ViewProviderExtension.h"
#include "ViewProviderExtern.h"
#include "ViewProviderFeature.h"
#include "ViewProviderPythonFeature.h"
#include "ViewProviderDocumentObjectGroup.h"
#include "ViewProviderDragger.h"
#include "ViewProviderGeometryObject.h"
#include "ViewProviderInventorObject.h"
#include "ViewProviderVRMLObject.h"
#include "ViewProviderAnnotation.h"
#include "ViewProviderMeasureDistance.h"
#include "ViewProviderPlacement.h"
#include "ViewProviderOriginFeature.h"
#include "ViewProviderPlane.h"
#include "ViewProviderLine.h"
#include "ViewProviderGeoFeatureGroup.h"
#include "ViewProviderOriginGroup.h"
#include "ViewProviderPart.h"
#include "ViewProviderOrigin.h"
#include "ViewProviderMaterialObject.h"
#include "ViewProviderTextDocument.h"
#include "ViewProviderGroupExtension.h"
#include "Language/Translator.h"
#include "TaskView/TaskView.h"
#include "TaskView/TaskDialogPython.h"
#include <Gui/Quarter/Quarter.h>
#include "View3DViewerPy.h"
#include <Gui/GuiInitScript.h>
using namespace Gui;
using namespace Gui::DockWnd;
using namespace std;
Application* Application::Instance = 0L;
namespace Gui {
// Pimpl class
struct ApplicationP
{
ApplicationP() :
activeDocument(0L),
isClosing(false),
startingUp(true)
{
// create the macro manager
macroMngr = new MacroManager();
}
~ApplicationP()
{
delete macroMngr;
}
/// list of all handled documents
std::map<const App::Document*, Gui::Document*> documents;
/// Active document
Gui::Document* activeDocument;
MacroManager* macroMngr;
/// List of all registered views
std::list<Gui::BaseView*> passive;
bool isClosing;
bool startingUp;
/// Handles all commands
CommandManager commandManager;
};
static PyObject *
FreeCADGui_subgraphFromObject(PyObject * /*self*/, PyObject *args)
{
PyObject *o;
if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type), &o))
return NULL;
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(o)->getDocumentObjectPtr();
std::string vp = obj->getViewProviderName();
SoNode* node = 0;
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);
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 type = "So";
type += node->getTypeId().getName().getString();
type += " *";
PyObject* proxy = 0;
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 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
FreeCADGui_getSoDBVersion(PyObject * /*self*/, PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return NULL;
#if PY_MAJOR_VERSION >= 3
return PyUnicode_FromString(SoDB::getVersion());
#else
return PyString_FromString(SoDB::getVersion());
#endif
}
// Copied from https://github.com/python/cpython/blob/master/Objects/moduleobject.c
#if PY_MAJOR_VERSION >= 3
#if PY_MINOR_VERSION <= 4
static int
_add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
{
PyObject *func;
PyMethodDef *fdef;
for (fdef = functions; fdef->ml_name != NULL; fdef++) {
if ((fdef->ml_flags & METH_CLASS) ||
(fdef->ml_flags & METH_STATIC)) {
PyErr_SetString(PyExc_ValueError,
"module functions cannot set"
" METH_CLASS or METH_STATIC");
return -1;
}
func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
if (func == NULL) {
return -1;
}
if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
Py_DECREF(func);
return -1;
}
Py_DECREF(func);
}
return 0;
}
int
PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
{
int res;
PyObject *name = PyModule_GetNameObject(m);
if (name == NULL) {
return -1;
}
res = _add_methods_to_object(m, name, functions);
Py_DECREF(name);
return res;
}
#endif
#endif
struct PyMethodDef FreeCADGui_methods[] = {
{"subgraphFromObject",FreeCADGui_subgraphFromObject,METH_VARARGS,
"subgraphFromObject(object) -> Node\n\n"
"Return the Inventor subgraph to an object"},
{"getSoDBVersion",FreeCADGui_getSoDBVersion,METH_VARARGS,
"getSoDBVersion() -> String\n\n"
"Return a text string containing the name\n"
"of the Coin library and version information"},
{NULL, NULL, 0, NULL} /* sentinel */
};
} // namespace Gui
Application::Application(bool GUIenabled)
{
//App::GetApplication().Attach(this);
if (GUIenabled) {
App::GetApplication().signalNewDocument.connect(boost::bind(&Gui::Application::slotNewDocument, this, _1));
App::GetApplication().signalDeleteDocument.connect(boost::bind(&Gui::Application::slotDeleteDocument, this, _1));
App::GetApplication().signalRenameDocument.connect(boost::bind(&Gui::Application::slotRenameDocument, this, _1));
App::GetApplication().signalActiveDocument.connect(boost::bind(&Gui::Application::slotActiveDocument, this, _1));
App::GetApplication().signalRelabelDocument.connect(boost::bind(&Gui::Application::slotRelabelDocument, this, _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::system().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::system().groupSeparator() == QLocale::system().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 = QLocale::system();
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 PY_MAJOR_VERSION >= 3
// 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,
NULL, NULL, NULL, NULL
};
module = PyModule_Create(&FreeCADGuiModuleDef);
PyDict_SetItemString(modules, "FreeCADGui", module);
}
else {
// extend the method list
PyModule_AddFunctions(module, Application::Methods);
}
#else
PyObject* module = Py_InitModule3("FreeCADGui", Application::Methods, FreeCADGui_doc);
#endif
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
PySideUicModule* pySide = new PySideUicModule();
Py_INCREF(pySide->module().ptr());
PyModule_AddObject(module, "PySideUic", pySide->module().ptr());
//insert Selection module
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef SelectionModuleDef = {
PyModuleDef_HEAD_INIT,
"Selection", "Selection module", -1,
SelectionSingleton::Methods,
NULL, NULL, NULL, NULL
};
PyObject* pSelectionModule = PyModule_Create(&SelectionModuleDef);
#else
PyObject* pSelectionModule = Py_InitModule3("Selection", SelectionSingleton::Methods,"Selection module");
#endif
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::PyGILStateLocker lock;
PyObject *module = PyImport_AddModule("FreeCADGui");
PyMethodDef *meth = FreeCADGui_methods;
PyObject *dict = PyModule_GetDict(module);
for (; meth->ml_name != NULL; meth++) {
PyObject *descr;
descr = PyCFunction_NewEx(meth,0,0);
if (descr == NULL)
break;
if (PyDict_SetItemString(dict, meth->ml_name, descr) != 0)
break;
Py_DECREF(descr);
}
// Python console binding
PythonDebugModule ::init_module();
PythonStdout ::init_type();
PythonStderr ::init_type();
OutputStdout ::init_type();
OutputStderr ::init_type();
PythonStdin ::init_type();
View3DInventorPy ::init_type();
View3DInventorViewerPy ::init_type();
AbstractSplitViewPy ::init_type();
d = new ApplicationP;
// global access
Instance = this;
// instantiate the workbench dictionary
_pcWorkbenchDictionary = PyDict_New();
if (GUIenabled) {
createStandardOperations();
MacroCommand::load();
}
}
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 = 0;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// 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());
// 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 != 0) {
// issue module loading
Command::doCommand(Command::App, "import %s", Module);
try {
// load the file with the module
Command::doCommand(Command::App, "%s.open(u\"%s\")", Module, unicodepath.c_str());
// ViewFit
if (!File.hasExtension("FCStd") && 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());
if (Module != 0) {
// issue module loading
Command::doCommand(Command::App, "import %s", Module);
try {
// 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 {
Command::doCommand(Command::App, "%s.insert(u\"%s\",\"%s\")"
, Module, unicodepath.c_str(), DocName);
ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath
("User parameter:BaseApp/Preferences/View");
if (hGrp->GetBool("AutoFitToView", true))
Command::doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewFit\")");
if (getDocument(DocName))
getDocument(DocName)->setModified(true);
}
// 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();
}
}
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());
if (Module != 0) {
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());
// 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();
}
void Application::slotNewDocument(const App::Document& Doc)
{
#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(boost::bind(&Gui::Application::slotNewObject, this, _1));
pDoc->signalDeletedObject.connect(boost::bind(&Gui::Application::slotDeletedObject, this, _1));
pDoc->signalChangedObject.connect(boost::bind(&Gui::Application::slotChangedObject, this, _1, _2));
pDoc->signalRelabelObject.connect(boost::bind(&Gui::Application::slotRelabelObject, this, _1));
pDoc->signalActivatedObject.connect(boost::bind(&Gui::Application::slotActivatedObject, this, _1));
signalNewDocument(*pDoc);
pDoc->createView(View3DInventor::getClassTypeId());
// FIXME: Do we really need this further? Calling processEvents() mixes up order of execution in an
// unpredicatable way. At least it seems that with Qt5 we don't need this any more.
#if QT_VERSION < 0x050000
qApp->processEvents(); // make sure to show the window stuff on the right place
#endif
}
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;
}
// We must clear the selection here to notify all observers
Gui::Selection().clearSelection(doc->second->getDocument()->getName());
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(0);
// 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::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);
}
else {
Base::PyGILStateLocker lock;
Py::Module("FreeCADGui").setAttr(std::string("ActiveDocument"),Py::None());
}
}
signalActiveDocument(*doc->second);
}
}
void Application::slotNewObject(const ViewProvider& vp)
{
this->signalNewObject(vp);
}
void Application::slotDeletedObject(const ViewProvider& vp)
{
this->signalDeletedObject(vp);
}
void Application::slotChangedObject(const ViewProvider& vp, const App::Property& prop)
{
this->signalChangedObject(vp,prop);
}
void Application::slotRelabelObject(const ViewProvider& vp)
{
this->signalRelabelObject(vp);
}
void Application::slotActivatedObject(const ViewProvider& vp)
{
this->signalActivatedObject(vp);
}
void Application::onLastWindowClosed(Gui::Document* pcDoc)
{
if (!d->isClosing && pcDoc) {
try {
// 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());
}
catch (const Base::Exception& e) {
e.ReportException();
}
catch (const Py::Exception&) {
Base::PyException e;
e.ReportException();
}
}
}
/// send Messages to the active view
bool Application::sendMsgToActiveView(const char* pMsg, const char** ppReturn)
{
MDIView* pView = getMainWindow()->activeWindow();
return pView ? pView->onMsg(pMsg,ppReturn) : false;
}
bool Application::sendHasMsgToActiveView(const char* pMsg)
{
MDIView* pView = getMainWindow()->activeWindow();
return pView ? pView->onHasMsg(pMsg) : false;
}
Gui::MDIView* Application::activeView(void) const
{
if (activeDocument())
return activeDocument()->getActiveView();
else
return NULL;
}
/**
* @brief Application::activateView
* Activates a view of the given type of the active document.
* If a view of this type doesn't exist and \a create is true
* a new view of this type will be created.
* @param type
* @param create
*/
void Application::activateView(const Base::Type& type, bool create)
{
Document* doc = activeDocument();
if (doc) {
MDIView* mdiView = doc->getActiveView();
if (mdiView && mdiView->isDerivedFrom(type))
return;
std::list<MDIView*> mdiViews = doc->getMDIViewsOfType(type);
if (!mdiViews.empty())
doc->setActiveWindow(mdiViews.back());
else if (create)
doc->createView(type);
}
}
/// Getter for the active view
Gui::Document* Application::activeDocument(void) const
{
return d->activeDocument;
}
void Application::setActiveDocument(Gui::Document* pcDocument)
{
if (d->activeDocument == pcDocument)
return; // nothing needs to be done
if (pcDocument) {
// This happens if a document with more than one view is about being
// closed and a second view is activated. The document is still not
// removed from the map.
App::Document* doc = pcDocument->getDocument();
if (d->documents.find(doc) == d->documents.end())
return;
}
d->activeDocument = pcDocument;
std::string nameApp, nameGui;
// This adds just a line to the macro file but does not set the active document
// Macro recording of this is problematic, thus it's written out as comment.
if (pcDocument){
nameApp += "App.setActiveDocument(\"";
nameApp += pcDocument->getDocument()->getName();
nameApp += "\")\n";
nameApp += "App.ActiveDocument=App.getDocument(\"";
nameApp += pcDocument->getDocument()->getName();
nameApp += "\")";
macroManager()->addLine(MacroManager::Cmt,nameApp.c_str());
nameGui += "Gui.ActiveDocument=Gui.getDocument(\"";
nameGui += pcDocument->getDocument()->getName();
nameGui += "\")";
macroManager()->addLine(MacroManager::Cmt,nameGui.c_str());
}
else {
nameApp += "App.setActiveDocument(\"\")\n";
nameApp += "App.ActiveDocument=None";
macroManager()->addLine(MacroManager::Cmt,nameApp.c_str());
nameGui += "Gui.ActiveDocument=None";
macroManager()->addLine(MacroManager::Cmt,nameGui.c_str());
}
// Sets the currently active document
try {
Base::Interpreter().runString(nameApp.c_str());
Base::Interpreter().runString(nameGui.c_str());
}
catch (const Base::Exception& e) {
Base::Console().Warning(e.what());
return;
}
#ifdef FC_DEBUG
// May be useful for error detection
if (d->activeDocument) {
App::Document* doc = d->activeDocument->getDocument();
Base::Console().Log("Active document is %s (at %p)\n",doc->getName(), doc);
}
else {
Base::Console().Log("No active document\n");
}
#endif
// notify all views attached to the application (not views belong to a special document)
for(list<Gui::BaseView*>::iterator It=d->passive.begin();It!=d->passive.end();++It)
(*It)->setDocument(pcDocument);
}
Gui::Document* Application::getDocument(const char* name) const
{
App::Document* pDoc = App::GetApplication().getDocument( name );
std::map<const App::Document*, Gui::Document*>::const_iterator it = d->documents.find(pDoc);
if ( it!=d->documents.end() )
return it->second;
else
return 0;
}
Gui::Document* Application::getDocument(const App::Document* pDoc) const
{
std::map<const App::Document*, Gui::Document*>::const_iterator it = d->documents.find(pDoc);
if ( it!=d->documents.end() )
return it->second;
else
return 0;
}
void Application::showViewProvider(const App::DocumentObject* obj)
{
ViewProvider* vp = getViewProvider(obj);
if (vp) vp->show();
}
void Application::hideViewProvider(const App::DocumentObject* obj)
{
ViewProvider* vp = getViewProvider(obj);
if (vp) vp->hide();
}
Gui::ViewProvider* Application::getViewProvider(const App::DocumentObject* obj) const
{
App::Document* doc = obj ? obj->getDocument() : 0;
if (doc) {
Gui::Document* gui = getDocument(doc);
if (gui) {
ViewProvider* vp = gui->getViewProvider(obj);
return vp;
}
}
return 0;
}
void Application::attachView(Gui::BaseView* pcView)
{
d->passive.push_back(pcView);
}
void Application::detachView(Gui::BaseView* pcView)
{
d->passive.remove(pcView);
}
void Application::onUpdate(void)
{
// update all documents
std::map<const App::Document*, Gui::Document*>::iterator It;
for (It = d->documents.begin();It != d->documents.end();++It)
It->second->onUpdate();
// update all the independent views
for (std::list<Gui::BaseView*>::iterator It2 = d->passive.begin();It2 != d->passive.end();++It2)
(*It2)->onUpdate();
}
/// Gets called if a view gets activated, this manages the whole activation scheme
void Application::viewActivated(MDIView* pcView)
{
#ifdef FC_DEBUG
// May be useful for error detection
Base::Console().Log("Active view is %s (at %p)\n",
(const char*)pcView->windowTitle().toUtf8(),pcView);
#endif
signalActivateView(pcView);
// Set the new active document which is taken of the activated view. If, however,
// this view is passive we let the currently active document unchanged as we would
// have no document active which is causing a lot of trouble.
if (!pcView->isPassive())
setActiveDocument(pcView->getGuiDocument());
}
void Application::updateActive(void)
{
activeDocument()->onUpdate();
}
void Application::tryClose(QCloseEvent * e)
{
if (d->documents.size() == 0) {
e->accept();