File: application_bindings.cpp

package info (click to toggle)
camitk 6.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 389,496 kB
  • sloc: cpp: 103,476; sh: 2,448; python: 1,618; xml: 984; makefile: 128; perl: 84; sed: 20
file content (342 lines) | stat: -rw-r--r-- 14,689 bytes parent folder | download
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
/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK 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 Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include "core_bindings.h"
#include "core_utils.h"
#include "qt_bindings.h"
#include "docstrings.h"

#include <Core.h>
#include <Application.h>
#include <ExtensionManager.h>
#include <MainWindow.h>
#include <Action.h>
#include <Component.h>
#include <Viewer.h>
#include <TransformationManager.h>
#include <PythonManager.h>
#include <InteractiveViewer.h>
#include <Log.h>

#include <thread>
#include <chrono>

namespace camitk {

void refresh() {
    TransformationManager::cleanupFramesAndTransformations();
    Application::refresh();
}

void startApplication() {
    Log::getLogger()->setLogLevel(InterfaceLogger::INFO);
    Log::getLogger()->setMessageBoxLevel(InterfaceLogger::WARNING); // FIXME Cannot display widget, no event loop
    Log::getLogger()->setDebugInformation(true);

    int argc = 1;
    char* argv = (char*)"camitk-python-application";

    Application* a = new Application("Default Python Application", argc, &argv, false, false);

    // force no redirection to console (to see error message if they occur)
    a->getMainWindow()->redirectToConsole(false);

    ExtensionManager::autoload();

    Viewer* medicalImageViewer = Application::getViewer("Medical Image Viewer");
    if (medicalImageViewer != nullptr) {
        // add the default axial viewer to the default main window
        a->getMainWindow()->setCentralViewer(medicalImageViewer);
        a->getMainWindow()->show();
    }
    else {
        CAMITK_INFO_ALT("No viewer found");
    }
}

void applicationExec() {
    // Start periodic event processing (non-blocking)
    std::thread([&]() {
        while (true) {
            if (Application::instance()) {
                Application::processEvents();  // Process events without blocking
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(10));  // 10ms interval
        }
    }).detach();
}

void showMainWindow() {
    startApplication();
    Application::exec();
}

//
// -- action pipeline
//

Component* applyInPipeline(QString actionName, ComponentList inputComponents) {
    camitk::Action* action = camitk::Application::getAction(actionName);
    if (action != nullptr) {
        if (!inputComponents.empty()) {
            action->setInputComponents(inputComponents);
        }

        camitk::Action::ApplyStatus status = action->applyInPipeline();

        if (status == camitk::Action::SUCCESS) {
            ComponentList outputComponents = action->getOutputComponents();

            // get the first top level component created by the action that is not in the input list
            auto it = std::find_if(outputComponents.cbegin(), outputComponents.cend(), [inputComponents](camitk::Component * c) {
                bool topLevel = c->isTopLevel();
                bool notInput = !inputComponents.contains(c);
                return topLevel && notInput;
            });
            if (it != outputComponents.cend()) {
                // reset modification flags on output components to avoid mismatching it for output component when chaining applyAction
                (*it)->setModified(false);
                return (*it);
            }
            else {
                CAMITK_TRACE_ALT(QString("Action %1 produces no output, returning None").arg(action->getName()))
            }
        }
    }
    else {
        CAMITK_INFO_ALT(QString("Cannot find action '%1'. Check the spelling and the availability in the loaded action extensions. Returning None").arg(actionName))
    }
    return nullptr;
}

//
// -- viewer picking
//

// TODO add this as an Application member? Create a PythonApplication with all the binding methods/helpers above including this?

// stores (viewerName, callback_hash) → connection
static QMap<QPair<QString, unsigned long long>, QMetaObject::Connection> viewerConnections;

// connect and returns true if everything went well
bool connectViewerSelectionChanged(const QString& viewerName, py::function callback) {
    camitk::Viewer* viewer = camitk::Application::getViewer(viewerName);
    if (!viewer) {
        throw std::runtime_error("Viewer not found: " + viewerName.toStdString());
    }

    // Connect the Qt signal to the Python callback if not already connected
    QPair<QString, unsigned long long> key = qMakePair(viewerName, static_cast<unsigned long long>(py::hash(callback)));

    // Prevent duplicate connection
    if (viewerConnections.contains(key)) {
        CAMITK_TRACE_ALT(QString("Viewer '%1' already connected to this callback").arg(viewerName));
        return false;
    }

    // Connect the signal to the Python callback
    auto signalConnection = QObject::connect(
                                viewer,
                                QOverload<>::of(&Viewer::selectionChanged),
                                viewer,
    [callback]() {
        py::gil_scoped_acquire gil;
        try {
            callback();
        }
        catch (const py::error_already_set& e) {
            PyErr_Print();
        }
    },
    Qt::QueuedConnection
                            );

    viewerConnections.insert(key, signalConnection);
    return true;
}

inline bool disconnectViewerSelectionChanged(const QString& viewerName, py::function callback) {
    QPair<QString, unsigned long long> key = qMakePair(viewerName, static_cast<unsigned long long>(py::hash(callback)));

    if (!viewerConnections.contains(key)) {
        CAMITK_TRACE_ALT(QString("No connection found for viewer '%1' and given callback").arg(viewerName));
        return false;
    }

    bool ok = QObject::disconnect(viewerConnections.value(key));
    viewerConnections.remove(key);
    return ok;
}

} // namespace camitk

void add_application_bindings(py::module_& m) {

    // --------------- Application ---------------
    // TODO should we simplify all Application actions to remove the .Application. layer?
    // For instance python developers would then use:
    // image = camitk.open("name.mha")
    // instead of:
    // image = camitk.Application.open("name.mha")

    py::class_<camitk::Application> application(m, "Application", DOC(camitk_Application));

    application.def_static("getAction", &camitk::Application::getAction,
                           py::return_value_policy::reference,
                           DOC(camitk_Application_getAction));

    application.def_static("getActions",
    []() {
        // TODO write a type_caster<camitk::ActionList> similar to type_caster<camitk::ComponentList>, see in core_utils
        camitk::ActionList actionList = camitk::Application::getActions();
        std::vector<camitk::Action*> stdActionList(actionList.constBegin(), actionList.constEnd());
        return stdActionList;
    },
    py::return_value_policy::reference,
    DOC(camitk_Application_getActions_1));

    application.def_static("getTopLevelComponents", &camitk::Application::getTopLevelComponents,
                           py::return_value_policy::reference,
                           DOC(camitk_Application_getTopLevelComponents));

    application.def_static("open", &camitk::Application::open,
                           py::return_value_policy::reference,
                           py::arg("fileName"),
                           py::arg("blockRefresh") = false,
                           DOC(camitk_Application_open));

    application.def_static("save", [](camitk::Component * c) {
        // Note: using the action instead of the Application method so that it will be registered
        // in history
        camitk::ComponentList componentToSave({c});
        camitk::applyInPipeline("Save", componentToSave);
    },
    DOC(camitk_Application_save));

    application.def_static("saveAs", [](camitk::Component * c) {
        // Note: using the action instead of the Application method so that it will be registered
        // in history
        camitk::ComponentList componentToSave({c});
        camitk::applyInPipeline("Save As", componentToSave);
    },
    R"doc(Saves the given Component by prompting the user for a file name.
This method uses the 'Save As' Action to save the given Component, which will prompt the user for a file name.)doc");

    application.def_static("close", [](camitk::Component & c, bool forceClose) {
        // if forceClose is true, the modified flag is reset so that the user is not asked to save
        if (forceClose) {
            c.setModified(false);
        }
        camitk::Application::close(&c, true);
    },
    DOC(camitk_Application_close));

    application.def_static("closeAll",
    []() {
        return (camitk::Application::getAction("Close All")->apply() == camitk::Action::SUCCESS);
    },
    R"doc(Closes all opened Components, prompting the user to save modified ones.
This method uses the 'Close All' Action to close all opened Components.)doc");

    // as the isAlive method is overloaded, we must be explicit to define
    // which one is to be called.
    // see https://pybind11.readthedocs.io/en/stable/classes.html#overloaded-methods
    // + as the user should be able to send a None/nullptr instead of a
    // valid pointer as the parameter, we must add a specific param name and set
    // its `none(...)` flag to true
    // see https://pybind11.readthedocs.io/en/stable/advanced/functions.html#allow-prohibiting-none-arguments
    // for `static bool isAlive(Component*)`
    application.def_static("isAlive",
                           py::overload_cast<camitk::Component*>(&camitk::Application::isAlive),
                           py::arg("component").none(true),
                           DOC(camitk_Application_isAlive_1));

    // for `static bool isAlive(Action*)`
    application.def_static("isAlive",
                           py::overload_cast<camitk::Action*>(&camitk::Application::isAlive),
                           py::arg("action").none(true),
                           DOC(camitk_Application_isAlive_2));

    application.def_static("applyAction", [](QString & name) -> camitk::Component* {
        return applyInPipeline(name, camitk::ComponentList());
    },
    py::return_value_policy::reference,
    R"doc(Applies the action of the given name and returns the top-level output Component created by it if any or None if there is no output component. The given action must require no input component)doc");

    application.def_static("applyAction", [](QString & name, camitk::Component & targetComp) -> camitk::Component* {
        camitk::ComponentList inputComponents;
        inputComponents.append(&targetComp);
        return applyInPipeline(name, inputComponents);
    },
    py::return_value_policy::reference,
    R"doc(Applies the action of the given name that takes the given component as input and returns the top-level output Component created by it if any or None if there is no output component. The given action must require one and only one input component)doc");

    application.def_static("applyAction", [](QString & name, camitk::ComponentList & targetList) -> camitk::Component* {
        return applyInPipeline(name, targetList);
    },
    py::return_value_policy::reference,
    R"doc(Applies the action of the given name that takes the given list of components as input and returns the top-level output Component created by it if any or None if there is no output component. The given action must require a list of input components)doc");

    application.def_static("connectViewerSelectionChanged", &camitk::connectViewerSelectionChanged,
                           py::arg("viewerName"),
                           py::arg("callback"),
                           R"doc(Connects a Python callback to a Viewer's selectionChanged() signal by name (if not already connected).)doc");

    application.def_static("disconnectViewerSelectionChanged", &camitk::disconnectViewerSelectionChanged,
                           py::arg("viewerName"),
                           py::arg("callback"),
                           "Disconnects a Python callback from a Viewer's selectionChanged() signal by name (if already connected).");

    application.def_static("update3DClippingPlanes", []() {
        camitk::InteractiveViewer* default3DViewer = dynamic_cast<camitk::InteractiveViewer*>(camitk::Application::getViewer("3D Viewer"));

        if (default3DViewer != nullptr) {
            default3DViewer->getRendererWidget()->resetClippingPlanes();
        }
    },
    R"doc(Updates the clipping planes of the default 3D Viewer.
    This might be required when the working space volume changes rapidly, for instance in navigation system where the tracker moves some mesh in real 3D space or for RV application).)doc");

    // --------------- Utils ---------------
    // util functions directly linked to the Application class

    m.def("startApplication", &camitk::startApplication,
          R"doc(Starts a default CamiTK Application with the default main window and event loop.
          This function is experimental and is still not entirely functional nor stable.
          Use at your own risks and only if you know what your doing.
          
          You have been warned!)doc");

    m.def("show", &camitk::showMainWindow,
          R"doc(Starts a default CamiTK Application with the default main window and event loop, and shows the main window.
          This function is experimental and is still not entirely functional nor stable.
          Use at your own risks and only if you know what your doing.
          
          You have been warned!)doc");

    m.def("refresh", &camitk::refresh,
          R"doc(Refreshes the application, including the transformation manager and all registered viewers.)doc");
}