Macro at Startup/it: Difference between revisions

From FreeCAD Documentation
No edit summary
(Updating to match new version of source page)
 
(20 intermediate revisions by 3 users not shown)
Line 1: Line 1:
<languages/>
<languages/>


<span id="Introduction"></span>
= Prefazione =
<div class="mw-translate-fuzzy">
==Introduzione==
</div>

{{TOCright}}


Questa documentazione spiega come impostare una macro in modo che venga eseguita automaticamente all'avvio di FreeCAD.
Questa documentazione spiega come impostare una macro in modo che venga eseguita automaticamente all'avvio di FreeCAD.


<div class="mw-translate-fuzzy">
Prima di iniziare, bisogna considerare le seguenti cose :
Prima di iniziare, bisogna considerare le seguenti cose :
* L'esecuzione automatica di macro all'avvio può essere considerata un rischio per la sicurezza. Si devono eseguire solo delle macro fidate e testate in precedenza.
* L'esecuzione automatica di macro all'avvio può essere considerata un rischio per la sicurezza. Si devono eseguire solo delle macro fidate e testate in precedenza.
Line 10: Line 16:
* Quando si fa riferimento a delle cartelle utente ('Mod', 'Macro', ...), esse si trovano nella cartella FreeCAD dell'utente. È possibile trovarle in Avvio e configurazione → [[Start up and Configuration/it#Informazioni relative all'utente|Informazioni relative all'utente]]
* Quando si fa riferimento a delle cartelle utente ('Mod', 'Macro', ...), esse si trovano nella cartella FreeCAD dell'utente. È possibile trovarle in Avvio e configurazione → [[Start up and Configuration/it#Informazioni relative all'utente|Informazioni relative all'utente]]
* Questo comportamento non dovrebbe essere utilizzato per le macro che si occupano della modellazione delle parti. Questo è più appropriato per le macro che aggiungono funzionalità, migliorano l'interfaccia utente, ...
* Questo comportamento non dovrebbe essere utilizzato per le macro che si occupano della modellazione delle parti. Questo è più appropriato per le macro che aggiungono funzionalità, migliorano l'interfaccia utente, ...
</div>


<span id="How_to"></span>
= How to =
<div class="mw-translate-fuzzy">
= Come fare =
</div>


<span id="Prepare_the_macro"></span>
== Prepare the macro ==
<div class="mw-translate-fuzzy">
== Preparare la macro ==
</div>


In genere, una macro non è pensata e fatta per essere eseguita all'avvio, quindi deve essere ottimizzata.
Generally, it will happen that a macro isn't directly compatible with a startup launch and shall be fine-tuned


<div class="mw-translate-fuzzy">
Consider the below macro that you downloaded from somewhere and is stored in your 'Macro' folder with name 'MySuperMacro.FCMacro' :
Prendere in considerazione la macro sottostante, memorizzata nella propria cartella 'Macro' con il nome 'MySuperMacro.FCMacro':
<pre>
</div>

{{Code|code=
## Import section ##
## Import section ##
from PySide import QtGui
from PySide import QtGui
Line 28: Line 44:
super(MyMsgBox, self).information(None, "MyTitle", "MyText")
super(MyMsgBox, self).information(None, "MyTitle", "MyText")


##Main instruction section
## Main instruction section
MyMsgBox()
MyMsgBox()
}}
</pre>

All macros will generally present a similar structure with first import section, then definition section and finally main instruction section.
<div class="mw-translate-fuzzy">
We will focus on this latter because main instructions (they are quite easy to spot because they start at the full beginning of the line) are actually the ones that 'execute' the macro.
Tutte le macro presentano generalmente una struttura simile con prima sezione di importazione, quindi una sezione di definizione e infine una sezione di istruzione principale.
For later step, we'll need to programmatically import the macro then execute it. This can't be done with the actual structure of the macro. To be able to do so, we need to enclose the main instructions in a function --eg. run()-- then ensure this function is still called when the macro is manually run by the user.
Ci concentreremo su quest'ultima sezione perché le istruzioni principali sono in realtà quelle che 'eseguono' la macro (sono abbastanza facili da individuare perché cominciano all'inizio della riga).
If you're not totally sure of what you're doing, it is advised to work on a copy of the macro (or you may just want to keep the original macro as is).
Nel passaggio successivo, bisogna importare la macro a livello di codice, quindi eseguirla. Questo non può essere fatto con la struttura effettiva della macro. Per poterlo fare, bisogna racchiudere le istruzioni principali in una funzione --eg. run()-- quindi assicurarsi che questa funzione sia ancora chiamata quando la macro viene eseguita manualmente dall'utente.
The original file shall be modified as follow :
Se non si è completamente sicuri di ciò che si sta facendo, è meglio lavorare su una copia della macro (anche per conservare l'originale della macro).
<pre>
Il file originale deve essere modificato come segue:
</div>

{{Code|code=
from PySide import QtGui
from PySide import QtGui
##The 2 below lines shall be added if not already present to ensure FreeCAD modules are imported
## The 2 below lines shall be added if not already present to ensure FreeCAD modules are imported
import FreeCAD as App
import FreeCAD as App
import FreeCADGui as Gui
import FreeCADGui as Gui
Line 47: Line 67:
super(MyMsgBox, self).information(None, "MyTitle", "MyText")
super(MyMsgBox, self).information(None, "MyTitle", "MyText")


##Enclose the main instructions in a function
## Enclose the main instructions in a function
def run():
def run():
MyMsgBox()
MyMsgBox()


##Ensure main instructions are still called in case of manal run
## Ensure main instructions are still called in case of manual run
if __name__ == '__main__':
if __name__ == '__main__':
run()
run()
}}
</pre>
Of course if the function 'run()' already exists in the macro, you can choose any other convenient name
Now the macro is ready to be integrated in FreeCAD startup.


Ovviamente se la funzione 'run()' esiste già nella macro, si può usare qualsiasi altro nome.
== Integrate into FreeCAD startup ==
Ora la macro è pronta per essere integrata nell'avvio di FreeCAD.


<span id="Integrate_into_FreeCAD_startup"></span>
First create a new folder in your user 'Mod' folder, let's say called 'MacroStartup'.
<div class="mw-translate-fuzzy">
Copy the modified macro into this newly created folder.
== Integrare la macro nell'avvio di FreeCAD ==
Finally create in the same folder a file called 'InitGui.py' which contains the following code :
<pre>
</div>

def runMacroStartup(name):
<div class="mw-translate-fuzzy">
#Do not run when NoneWorkbench is activated because UI isn't yet completely there
Innanzitutto creare una nuova cartella nella cartella "Mod" dell'utente, ad esempio "MacroStartup".
Copiare la macro modificata in questa cartella appena creata e rinominala con un'estensione '.py' se questo non è ancora il caso (nota che se sviluppi la macro da solo, può essere nominata con l'estensione ".py" anche in la cartella "Macro" in modo che non sia necessario rinominare durante la copia).
Infine, creare nella stessa cartella un file chiamato "InitGui.py" in cui inserire il seguente codice:
</div>

{{Code|code=
def runStartupMacros(name):
# Do not run when NoneWorkbench is activated because UI isn't yet completely there
if name != "NoneWorkbench":
if name != "NoneWorkbench":
#Run macro only once by disconnecting the signal at first call
# Run macro only once by disconnecting the signal at first call
FreeCADGui.getMainWindow().workbenchActivated.disconnect(runMacroStartup)
FreeCADGui.getMainWindow().workbenchActivated.disconnect(runStartupMacros)

##Following 2 lines shall be duplicated for each macro to run
# Following 2 lines shall be duplicated for each macro to run
import MySuperMacro
import MySuperMacro
MySuperMacro.run()
MySuperMacro.run()
##Eg. if a second macro shall be launched at startup
#import MyWonderfulMacro
#MyWonderfulMacro.run()


# Eg. if a second macro shall be launched at startup
##The following 2 lines are important because InitGui.py files are passed to the exec() function...
# import MyWonderfulMacro
##...and the runMacro wouldn't be visible outside. So explicitly add it to __main__
# MyWonderfulMacro.run()

# The following 2 lines are important because InitGui.py files are passed to the exec() function...
# ...and the runMacro wouldn't be visible outside. So explicitly add it to __main__
import __main__
import __main__
__main__.runMacro = runMacro
__main__.runStartupMacros = runStartupMacros

# Connect the function that runs the macro to the appropriate signal
FreeCADGui.getMainWindow().workbenchActivated.connect(runStartupMacros)
}}

Notare che viene eseguita solo una volta. Se si vuole eseguire più di una macro, bisogna semplicemente aggiungere le altre nello stesso file (guardare i commenti sul codice precedente).

<div class="mw-translate-fuzzy">
Il lavoro è finito. La macro dovrebbe essere eseguita automaticamente al prossimo avvio di FreeCAD.
</div>

Notare che se la macro originale è stata scaricata tramite Addon Manager, nel caso di aggiornamento essa viene sovrascritta e quindi è necessario eseguire di nuovo questi passaggi.

==General Notes==

* In the example 'InitGui.py' script above, the function named 'runStartupMacros()' may be changed, so long as you also change the other four references to it, so they all match.
* This script will be run prior to the auto loading of your desired startup workbench in the FreeCAD Preferences, [[Preferences_Editor#General_settings|General settings]].

===Linux===


===MacOS===
##Connect the function that runs the macro to the appropriate signal
FreeCADGui.getMainWindow().workbenchActivated.connect(runMacro)
</pre>
Notice that it shall be done only once. If you want to run more than one macro, you can just add the others in the same file (look at the comments on the above code).


===Windows===
We are over. Your macro should automatically run at next FreeCAD launch.


* In the above example, you may place the 'MacroStartup' folder within the 'Mod' folder of your FreeCAD root directory (whether installed version or portable version), or you may create a 'Mod' folder along side the 'Macro' folder in '%USERPROFILE%\AppData\Roaming\FreeCAD\', and place the 'MacroStartup' folder there.
Notice that if the original macro was downloaded through the Addon Manager, it will be overwritten on update and thus you have to follow again the steps here.
* From observation, the workbenches found within either 'Mod' folder are loaded alphabetically. Those in the FreeCAD root 'Mod' folder are loaded first, then FreeCAD scans the '%USERPROFILE%\AppData\Roaming\FreeCAD\Mod' folder for additional workbenches.


== Related ==


* [[Extra_python_modules#LazyLoader|LazyLoader]] is a Python module that allows deferred loading.
{{Userdocnavi/it}}




{{Powerdocnavi{{#translation:}}}}
[[Category:Poweruser Documentation/it]]
[[Category:Developer Documentation{{#translation:}}]]
[[Category:Python Code{{#translation:}}]]
[[Category:Macros{{#translation:}}]]

Latest revision as of 17:19, 6 March 2023

Other languages:

Introduzione

Questa documentazione spiega come impostare una macro in modo che venga eseguita automaticamente all'avvio di FreeCAD.

Prima di iniziare, bisogna considerare le seguenti cose :

  • L'esecuzione automatica di macro all'avvio può essere considerata un rischio per la sicurezza. Si devono eseguire solo delle macro fidate e testate in precedenza.
  • Per seguire questa procedura bisogna avere alcune nozioni di Python e di codifica.
  • Quando si fa riferimento a delle cartelle utente ('Mod', 'Macro', ...), esse si trovano nella cartella FreeCAD dell'utente. È possibile trovarle in Avvio e configurazione → Informazioni relative all'utente
  • Questo comportamento non dovrebbe essere utilizzato per le macro che si occupano della modellazione delle parti. Questo è più appropriato per le macro che aggiungono funzionalità, migliorano l'interfaccia utente, ...

Come fare

Preparare la macro

In genere, una macro non è pensata e fatta per essere eseguita all'avvio, quindi deve essere ottimizzata.

Prendere in considerazione la macro sottostante, memorizzata nella propria cartella 'Macro' con il nome 'MySuperMacro.FCMacro':

## Import section ##
from PySide import QtGui

## Definition section (classes, functions, ...)
class MyMsgBox(QtGui.QMessageBox):

    def __init__(self):
        super(MyMsgBox, self).information(None, "MyTitle", "MyText")

## Main instruction section
MyMsgBox()

Tutte le macro presentano generalmente una struttura simile con prima sezione di importazione, quindi una sezione di definizione e infine una sezione di istruzione principale. Ci concentreremo su quest'ultima sezione perché le istruzioni principali sono in realtà quelle che 'eseguono' la macro (sono abbastanza facili da individuare perché cominciano all'inizio della riga). Nel passaggio successivo, bisogna importare la macro a livello di codice, quindi eseguirla. Questo non può essere fatto con la struttura effettiva della macro. Per poterlo fare, bisogna racchiudere le istruzioni principali in una funzione --eg. run()-- quindi assicurarsi che questa funzione sia ancora chiamata quando la macro viene eseguita manualmente dall'utente. Se non si è completamente sicuri di ciò che si sta facendo, è meglio lavorare su una copia della macro (anche per conservare l'originale della macro). Il file originale deve essere modificato come segue:

from PySide import QtGui
## The 2 below lines shall be added if not already present to ensure FreeCAD modules are imported
import FreeCAD as App
import FreeCADGui as Gui

class MyMsgBox(QtGui.QMessageBox):

    def __init__(self):
        super(MyMsgBox, self).information(None, "MyTitle", "MyText")

## Enclose the main instructions in a function
def run():
    MyMsgBox()

## Ensure main instructions are still called in case of manual run
if __name__ == '__main__':
    run()

Ovviamente se la funzione 'run()' esiste già nella macro, si può usare qualsiasi altro nome. Ora la macro è pronta per essere integrata nell'avvio di FreeCAD.

Integrare la macro nell'avvio di FreeCAD

Innanzitutto creare una nuova cartella nella cartella "Mod" dell'utente, ad esempio "MacroStartup". Copiare la macro modificata in questa cartella appena creata e rinominala con un'estensione '.py' se questo non è ancora il caso (nota che se sviluppi la macro da solo, può essere nominata con l'estensione ".py" anche in la cartella "Macro" in modo che non sia necessario rinominare durante la copia). Infine, creare nella stessa cartella un file chiamato "InitGui.py" in cui inserire il seguente codice:

def runStartupMacros(name):
    # Do not run when NoneWorkbench is activated because UI isn't yet completely there
    if name != "NoneWorkbench":
        # Run macro only once by disconnecting the signal at first call
        FreeCADGui.getMainWindow().workbenchActivated.disconnect(runStartupMacros)

        # Following 2 lines shall be duplicated for each macro to run
        import MySuperMacro
        MySuperMacro.run()

        # Eg. if a second macro shall be launched at startup
        # import MyWonderfulMacro
        # MyWonderfulMacro.run()

# The following 2 lines are important because InitGui.py files are passed to the exec() function...
# ...and the runMacro wouldn't be visible outside. So explicitly add it to __main__
import __main__
__main__.runStartupMacros = runStartupMacros

# Connect the function that runs the macro to the appropriate signal
FreeCADGui.getMainWindow().workbenchActivated.connect(runStartupMacros)

Notare che viene eseguita solo una volta. Se si vuole eseguire più di una macro, bisogna semplicemente aggiungere le altre nello stesso file (guardare i commenti sul codice precedente).

Il lavoro è finito. La macro dovrebbe essere eseguita automaticamente al prossimo avvio di FreeCAD.

Notare che se la macro originale è stata scaricata tramite Addon Manager, nel caso di aggiornamento essa viene sovrascritta e quindi è necessario eseguire di nuovo questi passaggi.

General Notes

  • In the example 'InitGui.py' script above, the function named 'runStartupMacros()' may be changed, so long as you also change the other four references to it, so they all match.
  • This script will be run prior to the auto loading of your desired startup workbench in the FreeCAD Preferences, General settings.

Linux

MacOS

Windows

  • In the above example, you may place the 'MacroStartup' folder within the 'Mod' folder of your FreeCAD root directory (whether installed version or portable version), or you may create a 'Mod' folder along side the 'Macro' folder in '%USERPROFILE%\AppData\Roaming\FreeCAD\', and place the 'MacroStartup' folder there.
  • From observation, the workbenches found within either 'Mod' folder are loaded alphabetically. Those in the FreeCAD root 'Mod' folder are loaded first, then FreeCAD scans the '%USERPROFILE%\AppData\Roaming\FreeCAD\Mod' folder for additional workbenches.

Related

  • LazyLoader is a Python module that allows deferred loading.