Erstellung von Arbeitsbereichen

From FreeCAD Documentation
Revision as of 20:57, 2 February 2016 by Ueisenb (talk | contribs) (Created page with "Sie können ein Lizenzmodell Ihrer Wahl für Ihren Arbeitsbereich wählen. Sie sollte sich jedoch darüber bewusst sein, dass ein Arbeitsbereich, der zu einem gewissen Zeitpun...")

Diese Seite zeigt, wie FreeCAD neue Arbeitsbereiche hinzugefügt werden. Arbeitsbereiche sind Container für FreeCAD Befehle. Sie können in Python, C++ oder in einer Mischung aus beiden programmiert werden. Letzteres hat den Vorteil, die Geschwindigkeit von C++ mit der Flexibilität von Python zu verbinden. In allen Fällen werden Arbeitsbereiche durch einen Satz von zwei Pythondateien gestartet.

Struktur eines Arbeitsbereichs

Das Vorgehen ist einfach: Sie brauchen einen Ordner mit einem Namen Ihrer Wahl, der im Mod Verzeichnis angelegt wird, und eine Init.py Datei sowie optional eine InitGui.py Datei. Die Init Datei wird immer ausgeführt, wenn FreeCAD startet gefolgt von der InitGui Datei, die nur ausgeführt wird, wenn sich FreeCAD im GUI Modus (nicht im Konsolenmodus) befindet. Dies ist alles, was nötig ist, damit FreeCAD Ihren Arbeitsbereich beim Start findet und ihn zum Interface hinzufügt.

Innerhalb dieser Dateien können Sie beliebige Dinge machen. Üblicherweise werden sie wie folgt verwendet:

  • In der Init.py Datei fügen Sie in der Regel verschiedene Dinge hinzu, die benutzt werden, auch wenn FreeCAD im Konsolenmodus arbeitet, z.B. Dateiimport- und Exportfilter.
  • In der InitGUI.py Datei definieren Sie üblicherweise einen Arbeitsbereich, der einen Namen, ein Symbol und eine Reihe von FreeCAD Befehlen (siehe unten) enthält. Der Arbeitsbereich definiert außerdem Funktionen, die ausgeführt werden, wenn FreeCAD geladen wird (hier sollte so wenig wie möglich getan werden, um das Starten nicht zu verlangsamen), der Arbeitsbereich aktiviert (hier wird die meiste Arbeit geleistet) sowie deaktiviert wird (hier können Dinge, wenn nötig, entfernt werden).

Struktur eines C++ Arbeitsbereichs

Wenn Sie einen Arbeitsbereich in Python programmieren, sind keine weiteren Dinge zu beachten und weitere Pythondateien können zusammen mit Init.py sowie InitGui.py gespeichert werden. Wenn Sie jedoch mit C++ arbeiten, sollten Sie besonders eine fundamentale Regel von FreeCAD beachten: Die Trennung des Arbeitsbereichs in einen Anwendungsteil (,der im Konsolenmodus ohne GUI Elemente laufen kann) und einen GUI Teil, der nur geladen wird, wenn FreeCAD in voller GUI Umgebung geladen wird. Wenn Sie also einen C++ Arbeitsbereich erstellen, werden Sie tatsächlich zwei Module erstellen (Applikation und GUI). Diese beiden Module müssen natürlich von Python aus aufrufbar sein. Jedes FreeCAD Modul (Applikation oder GUI) besteht zumindest aus einer Modul Init Datei. Dies ist eine typische AppMyModuleGui.cpp Datei:

extern "C" {
    void MyModuleGuiExport initMyModuleGui()  
    {
         if (!Gui::Application::Instance) {
            PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application.");
            return;
        }
        try {
            // import other modules this one depends on
            Base::Interpreter().runString("import PartGui");
            // run some python code in the console
            Base::Interpreter().runString("print('welcome to my module!')");
        }
        catch(const Base::Exception& e) {
            PyErr_SetString(PyExc_ImportError, e.what());
            return;
        }
        (void) Py_InitModule("MyModuleGui", MyModuleGui_Import_methods);   /* mod name, table ptr */
        Base::Console().Log("Loading GUI of MyModule... done\n");
    
        // initializes the FreeCAD commands (in another cpp file)
        CreateMyModuleCommands();
    
        // initializes workbench and object definitions
        MyModuleGui::Workbench::init();
        MyModuleGui::ViewProviderSomeCustomObject::init();
    
         // add resources and reloads the translators
        loadMyModuleResource();
    }
}

Die Init.py Datei

# FreeCAD init script of XXX module  

#***************************************************************************
#*   (c) John Doe john@doe.com 2015                                        *   
#*                                                                         *
#*   This file is part of the FreeCAD CAx development system.              *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   FreeCAD 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 for more details.                   *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with FreeCAD; if not, write to the Free Software        *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************/

FreeCAD.addImportType("My own format (*.own)","importOwn")
FreeCAD.addExportType("My own format (*.own)","importOwn")
print "I am executing some stuff here when FreeCAD starts!"

Sie können ein Lizenzmodell Ihrer Wahl für Ihren Arbeitsbereich wählen. Sie sollte sich jedoch darüber bewusst sein, dass ein Arbeitsbereich, der zu einem gewissen Zeitpunkt in FreeCAD integriert und mit dem Quellcode veröffentlicht werden soll, der LPGL2+ Lizenz unterliegen muss. Die Funktionen FreeCAD.addImportType() und addEXportType() ermöglichen die Vergabe eines Namens und einer Dateiendung sowie ein Pythonmodul, das für diesen Import zuständig ist. Im obigen Beispiel ist importOwn.py für den Umgang mit .own Dateien verantwortlich. Schauen Sie unter Codeschnipsel nach weiteren Beispielen.

Python workbenches

class MyWorkbench (Workbench):

    MenuText = "My Workbench"
    ToolTip = "A description of my workbench"
    Icon = """paste here the contents of a 16x16 xpm icon"""

    def Initialize(self):
        "This function is executed when FreeCAD starts"
        import MyModuleA, MyModuleB # import here all the needed files that create your FreeCAD commands
        self.list = ["MyCommand1, MyCommand2"] # A list of command names created in the line above
        self.appendToolbar("My Commands",self.list) # creates a new toolbar with your commands
        self.appendMenu("My New Menu",self.list) # creates a new menu
        self.appendMenu(["An existing Menu","My submenu"],self.list) # appends a submenu to an existing menu

    def Activated(self):
        "This function is executed when the workbench is activated"
        return

    def Deactivated(self):
        "This function is executed when the workbench is deactivated"
        return

    def ContextMenu(self, recipient):
        "This is executed whenever the user right-clicks on screen"
        # "recipient" will be either "view" or "tree"
        self.appendContextMenu("My commands",self.list) # add commands to the context menu

    def GetClassName(self): 
        # this function is mandatory if this is a full python workbench
        return "Gui::PythonWorkbench"
       
Gui.addWorkbench(MyWorkbench())

Other than that, you can do anything you want: You could put your whole workbench code inside the InitGui.py if you want, but it is usually more convenient to place the different functions of your workbench in separate files. So those files are smaller and easier to read. Then you import those files into your InitGui.py file. You can organize those files the way you want, a good example is one for each FreeCAD command you add.

C++ workbenches

If you are going to code your workbench in C++, you will probably want to code the workbench definition itself in C++ too (although it is not necessary: You could also code only the tools in C++, and leave the workbench definition in python). In that case, the InitGui.py file becomes very simple: It might contain just one line:

import MyModuleGui

where MyModule is your complete C++ workbench, including the commands and workbench definition.

Coding C++ workbenches works in a pretty similar way. This is a typical Workbench.cpp file to include in the Gui part of your module:

namespace MyModuleGui {
    class MyModuleGuiExport Workbench : public Gui::StdWorkbench
    {
        TYPESYSTEM_HEADER();

    public:
        Workbench();
        virtual ~Workbench();

        virtual void activated();
        virtual void deactivated();

    protected:
        Gui::ToolBarItem* setupToolBars() const;
        Gui::MenuItem*    setupMenuBar() const;
    };
}

FreeCAD commands

FreeCAD commands are the basic building block of the FreeCAD interface. They can appear as a button on toolbars, and as a menu entry in menus. But it is the same command. A command is a simple python class, that must contain a couple of predefined attributes and functions, that define the name of the command, its icon, and what to do when the command is activated.

Python command definition

class My_Command_Class():
    """My new command"""

    def GetResources(self):
        return {'Pixmap'  : 'My_Command_Icon', # the name of a svg file available in the resources
                'Accel' : "Shift+S", # a default shortcut (optional)
                'MenuText': "My New Command"
                'ToolTip' : "What my new command does"}

    def Activated(self):
        "Do something here"
        return

    def IsActive(self):
        """Here you can define if the command must be active or not (greyed) if certain conditions
        are met or not. This function is optional."""
        return True

FreeCADGui.addCommand('My_Command',My_Command_Class())

C++ command definition

Similarly, you can code your commands in C++, typically have a Commands.cpp file in your Gui module. This is a typical Commands.cpp file:

DEF_STD_CMD_A(CmdMyCommand);

CmdMyCommand::CmdMyCommand()
  :Command("My_Command")
{
  sAppModule    = "MyModule";
  sGroup        = QT_TR_NOOP("MyModule");
  sMenuText     = QT_TR_NOOP("Runs my command...");
  sToolTipText  = QT_TR_NOOP("Describes what my command does");
  sWhatsThis    = QT_TR_NOOP("Describes what my command does");
  sStatusTip    = QT_TR_NOOP("Describes what my command does");
  sPixmap       = "some_svg_icon_from_my_resource";
}

void CmdMyCommand::activated(int iMsg)
{
    openCommand("My Command");
    doCommand(Doc,"print('Hello, world!')");
    commitCommand();
    updateActive();
}

bool CmdMyCommand::isActive(void)
{
  if( getActiveGuiDocument() )
    return true;
  else
    return false;
}

void CreateMyModuleCommands(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
    rcCmdMgr.addCommand(new CmdMyCommand());
}