File size: 13,072 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: LGPL-2.1-or-later

/***************************************************************************
 *   Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net>              *
 *                                                                         *
 *   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 <QDir>
#include <QFileInfo>


#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObjectPy.h>

#include <Base/FileInfo.h>
#include <Base/Interpreter.h>
#include <Gui/Command.h>
#include <Gui/WaitCursor.h>

#include "DlgProcessorChooser.h"
#include "ui_DlgProcessorChooser.h"


namespace PathGui
{
class Module: public Py::ExtensionModule<Module>
{
public:
    Module()
        : Py::ExtensionModule<Module>("PathGui")
    {
        add_varargs_method("open", &Module::open, "open(filename): Opens a GCode file as a new document");
        add_varargs_method(
            "insert",
            &Module::insert,
            "insert(filename,docname): Imports a given GCode file into the given document"
        );
        add_varargs_method(
            "export",
            &Module::exporter,
            "export(objectslist,filename): Exports a given list of Path objects to a GCode file"
        );
        initialize("This module is the PathGui module.");  // register with Python
    }

    ~Module() override
    {}

private:
    Py::Object open(const Py::Tuple& args)
    {
        char* Name;
        if (!PyArg_ParseTuple(args.ptr(), "et", "utf-8", &Name)) {
            throw Py::Exception();
        }
        std::string EncodedName = std::string(Name);
        PyMem_Free(Name);
        Base::FileInfo fi(EncodedName);
        if (!fi.exists()) {
            throw Py::RuntimeError("File not found");
        }

        Gui::WaitCursor wc;
        wc.restoreCursor();

        try {
            std::string path = App::Application::getHomePath();
            path += "Mod/CAM/Path/Post/scripts/";
            QDir dir1(QString::fromUtf8(path.c_str()), QStringLiteral("*_pre.py"));
            std::string cMacroPath
                = App::GetApplication()
                      .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
                      ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str());
            QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QStringLiteral("*_pre.py"));
            QFileInfoList list = dir1.entryInfoList();
            list << dir2.entryInfoList();
            std::vector<std::string> scripts;
            for (int i = 0; i < list.size(); ++i) {
                QFileInfo fileInfo = list.at(i);
                scripts.push_back(fileInfo.baseName().toStdString());
            }
            std::string processor;
            PathGui::DlgProcessorChooser Dlg(scripts);
            if (Dlg.exec() != QDialog::Accepted) {
                return Py::None();
            }
            processor = Dlg.getProcessor();

            std::ostringstream pre;
            std::ostringstream cmd;
            if (processor.empty()) {
                App::Document* pcDoc = App::GetApplication().newDocument();
                Gui::Command::runCommand(Gui::Command::Gui, "import Path");
                cmd << "Path.read(\"" << EncodedName << "\",\"" << pcDoc->getName() << "\")";
                Gui::Command::runCommand(Gui::Command::Gui, cmd.str().c_str());
            }
            else {
                for (int i = 0; i < list.size(); ++i) {
                    QFileInfo fileInfo = list.at(i);
                    if (fileInfo.baseName().toStdString() == processor) {
                        if (fileInfo.absoluteFilePath().contains(QStringLiteral("scripts"))) {
                            pre << "from Path.Post.scripts import " << processor;
                        }
                        else {
                            pre << "import " << processor;
                        }
                        Gui::Command::runCommand(Gui::Command::Gui, pre.str().c_str());
                        cmd << processor << ".open(\"" << EncodedName << "\")";
                        Gui::Command::runCommand(Gui::Command::Gui, cmd.str().c_str());
                    }
                }
            }
        }
        catch (const Base::Exception& e) {
            throw Py::RuntimeError(e.what());
        }

        return Py::None();
    }

    Py::Object insert(const Py::Tuple& args)
    {
        char* Name;
        char* DocName = nullptr;
        if (!PyArg_ParseTuple(args.ptr(), "et|s", "utf-8", &Name, &DocName)) {
            throw Py::Exception();
        }

        std::string EncodedName = std::string(Name);
        PyMem_Free(Name);
        Base::FileInfo fi(EncodedName);
        if (!fi.exists()) {
            throw Py::RuntimeError("File not found");
        }

        Gui::WaitCursor wc;
        wc.restoreCursor();

        try {
            std::string path = App::Application::getHomePath();
            path += "Mod/CAM/Path/Post/scripts/";
            QDir dir1(QString::fromUtf8(path.c_str()), QStringLiteral("*_pre.py"));
            std::string cMacroPath
                = App::GetApplication()
                      .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
                      ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str());
            QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QStringLiteral("*_pre.py"));
            QFileInfoList list = dir1.entryInfoList();
            list << dir2.entryInfoList();
            std::vector<std::string> scripts;
            for (int i = 0; i < list.size(); ++i) {
                QFileInfo fileInfo = list.at(i);
                scripts.push_back(fileInfo.baseName().toStdString());
            }
            std::string processor;
            PathGui::DlgProcessorChooser Dlg(scripts);
            if (Dlg.exec() != QDialog::Accepted) {
                return Py::None();
            }
            processor = Dlg.getProcessor();

            App::Document* pcDoc = nullptr;
            if (DocName) {
                pcDoc = App::GetApplication().getDocument(DocName);
            }
            else {
                pcDoc = App::GetApplication().getActiveDocument();
            }

            if (!pcDoc) {
                pcDoc = App::GetApplication().newDocument(DocName);
            }

            std::ostringstream pre;
            std::ostringstream cmd;
            if (processor.empty()) {
                Gui::Command::runCommand(Gui::Command::Gui, "import Path");
                cmd << "Path.read(\"" << EncodedName << "\",\"" << pcDoc->getName() << "\")";
                Gui::Command::runCommand(Gui::Command::Gui, cmd.str().c_str());
            }
            else {
                for (int i = 0; i < list.size(); ++i) {
                    QFileInfo fileInfo = list.at(i);
                    if (fileInfo.baseName().toStdString() == processor) {
                        if (fileInfo.absoluteFilePath().contains(QStringLiteral("scripts"))) {
                            pre << "from Path.Post.scripts import " << processor;
                        }
                        else {
                            pre << "import " << processor;
                        }
                        Gui::Command::runCommand(Gui::Command::Gui, pre.str().c_str());
                        cmd << processor << ".insert(\"" << EncodedName << "\",\""
                            << pcDoc->getName() << "\")";
                        Gui::Command::runCommand(Gui::Command::Gui, cmd.str().c_str());
                    }
                }
            }
        }
        catch (const Base::Exception& e) {
            throw Py::RuntimeError(e.what());
        }

        return Py::None();
    }

    Py::Object exporter(const Py::Tuple& args)
    {
        PyObject* object;
        char* Name;
        if (!PyArg_ParseTuple(args.ptr(), "Oet", &object, "utf-8", &Name)) {
            throw Py::Exception();
        }

        std::string EncodedName = std::string(Name);
        PyMem_Free(Name);
        Gui::WaitCursor wc;
        wc.restoreCursor();

        try {
            Py::Sequence objlist(object);
            if (objlist.size() == 0) {
                throw Py::RuntimeError("No object to export");
            }

            std::string path = App::Application::getHomePath();
            path += "Mod/CAM/Path/Post/scripts/";
            QDir dir1(QString::fromUtf8(path.c_str()), QStringLiteral("*_post.py"));
            std::string cMacroPath
                = App::GetApplication()
                      .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
                      ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str());
            QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QStringLiteral("*_post.py"));
            QFileInfoList list = dir1.entryInfoList();
            list << dir2.entryInfoList();
            std::vector<std::string> scripts;
            for (int i = 0; i < list.size(); ++i) {
                QFileInfo fileInfo = list.at(i);
                scripts.push_back(fileInfo.baseName().toStdString());
            }
            PathGui::DlgProcessorChooser Dlg(scripts, true);
            if (Dlg.exec() != QDialog::Accepted) {
                return Py::None();
            }
            std::string processor = Dlg.getProcessor();
            std::string arguments = Dlg.getArguments();

            std::ostringstream pre;
            std::ostringstream cmd;
            if (processor.empty()) {
                if (objlist.size() > 1) {
                    throw Py::RuntimeError(
                        "Cannot export more than one object without using a post script"
                    );
                }
                PyObject* item = objlist[0].ptr();
                if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
                    App::DocumentObject* obj
                        = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
                    App::Document* doc = obj->getDocument();
                    Gui::Command::runCommand(Gui::Command::Gui, "import Path");
                    cmd << "Path.write(FreeCAD.getDocument(\"" << doc->getName() << "\").getObject(\""
                        << obj->getNameInDocument() << "\"),\"" << EncodedName << "\")";
                    Gui::Command::runCommand(Gui::Command::Gui, cmd.str().c_str());
                }
                else {
                    return Py::None();
                }
            }
            else {
                for (int i = 0; i < list.size(); ++i) {
                    QFileInfo fileInfo = list.at(i);
                    if (fileInfo.baseName().toStdString() == processor) {
                        if (fileInfo.absoluteFilePath().contains(QStringLiteral("scripts"))) {
                            pre << "from Path.Post.scripts import " << processor;
                        }
                        else {
                            pre << "import " << processor;
                        }
                        Gui::Command::runCommand(Gui::Command::Gui, pre.str().c_str());
                        cmd << processor << ".export(__objs__,\"" << EncodedName << "\",\""
                            << arguments << "\")";
                        Gui::Command::runCommand(Gui::Command::Gui, cmd.str().c_str());
                    }
                }
            }
        }
        catch (const Base::Exception& e) {
            throw Py::RuntimeError(e.what());
        }

        return Py::None();
    }
};

PyObject* initModule()
{
    return Base::Interpreter().addModule(new Module);
}

}  // namespace PathGui