How to embed a Python code into the document?

Post here for help on using FreeCAD's graphical user interface (GUI).
Forum rules
and Helpful information
IMPORTANT: Please click here and read this first, before asking for help

Also, be nice to others! Read the FreeCAD code of conduct!
User avatar
ceremcem
Posts: 226
Joined: Sun Jan 07, 2018 11:10 am

How to embed a Python code into the document?

Post by ceremcem »

In order to follow a solution I need to write and embed a specific Python code into the document which will be run on:
  • Document initialization
  • Update (not necessary right now)
How can I embed and run a Python code on document open [and update]?
chrisb
Veteran
Posts: 54293
Joined: Tue Mar 17, 2015 9:14 am

Re: How to embed a Python code into the document?

Post by chrisb »

ceremcem wrote: Wed Sep 05, 2018 5:00 pm How can I embed and run a Python code on document open [and update]?
If this is possible it would be a serious security hole.
A Sketcher Lecture with in-depth information is available in English, auf Deutsch, en français, en español.
User avatar
ceremcem
Posts: 226
Joined: Sun Jan 07, 2018 11:10 am

Re: How to embed a Python code into the document?

Post by ceremcem »

chrisb wrote: Wed Sep 05, 2018 5:07 pm
ceremcem wrote: Wed Sep 05, 2018 5:00 pm How can I embed and run a Python code on document open [and update]?
If this is possible it would be a serious security hole.
Hmm. That might be the rationale why this "facility" doesn't exist in Spreadsheet in the first place.

I would provide some objections on that, like, how browsers handle Javascript engine, but let's focus how we could make it possible. Should I create a Workbench to provide a custom object which will provide a text editor to write Python code, a memory to hold the code and run the code on startup?

...or a Macro that reads the code from a Spreadsheet cell and evaluates it? But this wouldn't run on startup.

...or another approach (which would be a feature request) to ask Spreadsheet provide some constants (like document name) and a regex engine.

...or another approach would be running FreeCAD within a script and make it:
  • open the document
  • run the explicitly provided script
  • save the document
Bance
Veteran
Posts: 4274
Joined: Wed Feb 11, 2015 3:00 pm
Location: London

Re: How to embed a Python code into the document?

Post by Bance »

Slightly off topic, but have you investigated Kicad stepup project....

https://forum.freecadweb.org/viewtopic.php?t=14276

Steve.
User avatar
ceremcem
Posts: 226
Joined: Sun Jan 07, 2018 11:10 am

Re: How to embed a Python code into the document?

Post by ceremcem »

Bance wrote: Wed Sep 05, 2018 5:38 pm Slightly off topic, but have you investigated Kicad stepup project....

https://forum.freecadweb.org/viewtopic.php?t=14276

Steve.
I was aware of the existence of the StepUp Project, but when I looked at it again, I see that the outputs are generated from source models, which is much like what I want to achieve, only for FreeCAD models.
User avatar
DeepSOIC
Veteran
Posts: 7896
Joined: Fri Aug 29, 2014 12:45 am
Location: used to be Saint-Petersburg, Russia

Re: How to embed a Python code into the document?

Post by DeepSOIC »

ceremcem wrote: Wed Sep 05, 2018 5:14 pm Should I create a Workbench to provide a custom object which will provide a text editor to write Python code, a memory to hold the code and run the code on startup?
You certainly can, and in itself it is very easy. But you then have to put an explicit warning that by installing your workbench, one opens a huge security hole. I doubt your workbench will be accepted into addon installer, unless you carefully design your workbench to never run code from untrusted FCStd files.
User avatar
DeepSOIC
Veteran
Posts: 7896
Joined: Fri Aug 29, 2014 12:45 am
Location: used to be Saint-Petersburg, Russia

Re: How to embed a Python code into the document?

Post by DeepSOIC »

ceremcem wrote: Wed Sep 05, 2018 5:14 pm I would provide some objections on that, like, how browsers handle Javascript engine, but let's focus how we could make it possible.
It may be possible to restrict python enough to turn it into javascript. But I don't know if it is, and it is probably a lot of work. Python is a very general-purpose programming language, which can read/write/delete arbitrary files, connect to internet, run executable files, call OS API, and so on. While it might be challenging to damage operating system or install a virus (depends on OS), user data (which is much more valuable) is readily available and unprotected.
User avatar
ceremcem
Posts: 226
Joined: Sun Jan 07, 2018 11:10 am

Re: How to embed a Python code into the document?

Post by ceremcem »

DeepSOIC wrote: Wed Sep 05, 2018 8:03 pm
ceremcem wrote: Wed Sep 05, 2018 5:14 pm I would provide some objections on that, like, how browsers handle Javascript engine, but let's focus how we could make it possible.
It may be possible to restrict python enough to turn it into javascript. But I don't know if it is, and it is probably a lot of work. Python is a very general-purpose programming language, which can read/write/delete arbitrary files, connect to internet, run executable files, call OS API, and so on. While it might be challenging to damage operating system or install a virus (depends on OS), user data (which is much more valuable) is readily available and unprotected.
I disagree here, because there are limited number of attractions that should be restricted, like you said, filesystem access and network access. I remember that there are readily available Python sandboxes for similar purposes. I mean, the engine might be specifically trimmed to allow only current project's directory, no network access, and maybe a few more things I can't think of right now. I'm also a heavy Javascript user (on browser and server side via NodeJS) and I can say that Javascript has the same same abilities, which in turns, if Javascript can be safe, then Python might be too. Amount of work might be trivial to complex, but I guess it shouldn't be that hard if we could benefit from already available tools.
TheMarkster
Veteran
Posts: 5513
Joined: Thu Apr 05, 2018 1:53 am

Re: How to embed a Python code into the document?

Post by TheMarkster »

You can execute a macro on the command line as an argument, example:

FreeCAD.exe c:\path\to\my\macro.py

macro.py could contain the class definition of your feature python object. Use another macro to create the feature python object (or from the python console), then save the document. Now the feature python object is part of the document, and since you loaded the class definition during startup, the onChanged(), execute(), and onDocumentRestored() methods would be executed as the FP object needs recomputing, etc.

Something like this could be a starting point for macro.py:

Code: Select all

import FreeCAD as App
import FreeCAD

class FPObject:
    def __init__(self, obj):
        obj.Proxy = self
   
    def onChanged(self, fp, prop):
        '''Do something when a property has changed'''
        FreeCAD.Console.PrintMessage("onchanged\n")

 
    def execute(self, fp):
        '''Do something when doing a recomputation, this method is mandatory'''
        FreeCAD.Console.PrintMessage("execute\n")

    def onDocumentRestored(self, fp):
        FreeCAD.Console.PrintMessage("onDocumentRestored()\n")


FreeCAD.Console.PrintMessage("macro.py loaded\n")
Create a new document, then add the FP object to it:

Code: Select all

from macro import FPObject
m = App.ActiveDocument.addObject("App::FeaturePython","FP")
FPObject(m)
The FP object doesn't really do anything yet, but you could add properties to it and respond to the events as the properties change or when the FP object gets recomputed, etc. Save the document, close it, and reload it. The FP object should be able to use the code contained in macro.py after closing and reloading.

Some ideas: add a property of type App::PropertyLink and link a spreadsheet to it, then play with modifying the cells in the spreadsheet from the FP object. I think it would be fairly easy to set the cell to the name of the active document.

Take the text from one cell, evaluate it, and set another cell based on that evaluation using eval(). This would enable you to potentially run arbitrary python code from the spreadsheet. Take care you don't run afoul of cyclic dependencies.

Obviously, as has been stated there are security matters to be mindful of... And a workbench might be better than this method if this turns out to be too limiting.
User avatar
DeepSOIC
Veteran
Posts: 7896
Joined: Fri Aug 29, 2014 12:45 am
Location: used to be Saint-Petersburg, Russia

Re: How to embed a Python code into the document?

Post by DeepSOIC »

ceremcem wrote: Wed Sep 05, 2018 8:17 pm I remember that there are readily available Python sandboxes for similar purposes.
Hmm, then I guess you get my consent to go ahead :mrgreen: (which wasn't necessary after all :mrgreen: :mrgreen: ).
Post Reply