示例#1
0
    def run(self):

        "installs or updates the selected addon"

        git = None
        try:
            import git
        except Exception as e:
            self.info_label.emit("GitPython not found.")
            print(e)
            FreeCAD.Console.PrintWarning(
                translate(
                    "AddonsInstaller",
                    "GitPython not found. Using standard download instead.") +
                "\n")
            try:
                import zipfile
            except:
                self.info_label.emit("no zip support.")
                FreeCAD.Console.PrintError(
                    translate(
                        "AddonsInstaller",
                        "Your version of python doesn't appear to support ZIP files. Unable to proceed."
                    ) + "\n")
                return
            try:
                import StringIO as io
            except ImportError:  # StringIO is not available with python3
                import io
        if not isinstance(self.idx, list):
            self.idx = [self.idx]
        for idx in self.idx:
            if idx < 0:
                return
            if not self.repos:
                return
            if NOGIT:
                git = None
            basedir = FreeCAD.getUserAppDataDir()
            moddir = basedir + os.sep + "Mod"
            if not os.path.exists(moddir):
                os.makedirs(moddir)
            clonedir = moddir + os.sep + self.repos[idx][0]
            self.progressbar_show.emit(True)
            if os.path.exists(clonedir):
                self.info_label.emit("Updating module...")
                if sys.version_info.major > 2 and str(
                        self.repos[idx][0]) in PY2ONLY:
                    FreeCAD.Console.PrintWarning(
                        translate(
                            "AddonsInstaller",
                            "User requested updating a Python 2 workbench on a system running Python 3 - "
                        ) + str(self.repos[idx][0]) + "\n")
                if git:
                    if not os.path.exists(clonedir + os.sep + '.git'):
                        # Repair addon installed with raw download
                        bare_repo = git.Repo.clone_from(self.repos[idx][1],
                                                        clonedir + os.sep +
                                                        '.git',
                                                        bare=True)
                        try:
                            with bare_repo.config_writer() as cw:
                                cw.set('core', 'bare', False)
                        except AttributeError:
                            FreeCAD.Console.PrintWarning(
                                translate(
                                    "AddonsInstaller",
                                    "Outdated GitPython detected, consider upgrading with pip."
                                ) + "\n")
                            cw = bare_repo.config_writer()
                            cw.set('core', 'bare', False)
                            del cw
                        repo = git.Repo(clonedir)
                        repo.head.reset('--hard')
                    repo = git.Git(clonedir)
                    try:
                        answer = repo.pull() + "\n\n" + translate(
                            "AddonsInstaller",
                            "Workbench successfully updated. Please restart FreeCAD to apply the changes."
                        )
                    except:
                        print("Error updating module", self.repos[idx][1],
                              " - Please fix manually")
                        answer = repo.status()
                        print(answer)
                    else:
                        # Update the submodules for this repository
                        repo_sms = git.Repo(clonedir)
                        for submodule in repo_sms.submodules:
                            submodule.update(init=True, recursive=True)
                else:
                    answer = self.download(
                        self.repos[idx][1], clonedir
                    ) + "\n\n" + translate(
                        "AddonsInstaller",
                        "Workbench successfully updated. Please restart FreeCAD to apply the changes."
                    )
            else:
                self.info_label.emit("Checking module dependencies...")
                depsok, answer = self.checkDependencies(self.repos[idx][1])
                if depsok:
                    if sys.version_info.major > 2 and str(
                            self.repos[idx][0]) in PY2ONLY:
                        FreeCAD.Console.PrintWarning(
                            translate(
                                "AddonsInstaller",
                                "User requested installing a Python 2 workbench on a system running Python 3 - "
                            ) + str(self.repos[idx][0]) + "\n")
                    if git:
                        self.info_label.emit("Cloning module...")
                        repo = git.Repo.clone_from(self.repos[idx][1],
                                                   clonedir,
                                                   branch='master')

                        # Make sure to clone all the submodules as well
                        if repo.submodules:
                            repo.submodule_update(recursive=True)
                    else:
                        self.info_label.emit("Downloading module...")
                        self.download(self.repos[idx][1], clonedir)
                    answer = translate(
                        "AddonsInstaller",
                        "Workbench successfully installed. Please restart FreeCAD to apply the changes."
                    )
            # symlink any macro contained in the module to the macros folder
            macro_dir = FreeCAD.getUserMacroDir(True)
            if not os.path.exists(macro_dir):
                os.makedirs(macro_dir)
            if os.path.exists(clonedir):
                for f in os.listdir(clonedir):
                    if f.lower().endswith(".fcmacro"):
                        print("copying macro:", f)
                        utils.symlink(os.path.join(clonedir, f),
                                      os.path.join(macro_dir, f))
                        FreeCAD.ParamGet('User parameter:Plugins/' +
                                         self.repos[idx][0]).SetString(
                                             "destination", clonedir)
                        answer += "\n\n" + translate(
                            "AddonsInstaller",
                            "A macro has been installed and is available under Macro -> Macros menu"
                        ) + ":"
                        answer += "\n<b>" + f + "</b>"
            self.progressbar_show.emit(False)
            self.info_label.emit(answer)
            self.mark_recompute.emit(self.repos[idx][0])
        self.stop = True
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

__title__ = "FreeCAD Draft Workbench - Vector library"
__author__ = "Yorik van Havre, Werner Mayer, Martin Burbaum, Ken Cline"
__url__ = ["http://www.freecadweb.org"]

"a vector math library for FreeCAD"

import math, FreeCAD
from FreeCAD import Vector, Matrix

params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")


def precision():
    return params.GetInt("precision")


def typecheck(args_and_types, name="?"):
    for v, t in args_and_types:
        if not isinstance(v, t):
            FreeCAD.Console.PrintWarning("typecheck[" + str(name) + "]: " +
                                         str(v) + " is not " + str(t) + "\n")
            raise TypeError("fcvec." + str(name))


def toString(u):
示例#3
0
def onClose():
    """Remove system provided presets on FreeCAD close."""

    p = App.ParamGet("User parameter:Tux/PersistentToolbars")
    p.RemGroup("System")
示例#4
0
    def setup_working_dir(self, param_working_dir=None, create=False):
        """Set working dir for solver execution.

        Parameters
        ----------
        param_working_dir :  str, optional
            directory to be used for writing
        create : bool, optional
            Should the working directory be created if it does not exist
        """
        self.working_dir = ""
        # try to use given working dir or overwrite with solver working dir
        fem_general_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem/General")
        if param_working_dir is not None:
            self.working_dir = param_working_dir
            if femutils.check_working_dir(self.working_dir) is not True:
                if create is True:
                    FreeCAD.Console.PrintMessage(
                        "Dir given as parameter \'{}\' doesn't exist.\n".
                        format(self.working_dir))
                else:
                    FreeCAD.Console.PrintError(
                        "Dir given as parameter \'{}\' doesn't exist "
                        "and create parameter is set to False.\n".format(
                            self.working_dir))
                    self.working_dir = femutils.get_pref_working_dir(
                        self.solver)
                    FreeCAD.Console.PrintMessage(
                        "Dir \'{}\' will be used instead.\n".format(
                            self.working_dir))
        elif fem_general_prefs.GetBool("OverwriteSolverWorkingDirectory",
                                       True) is False:
            self.working_dir = self.solver.WorkingDir
            if femutils.check_working_dir(self.working_dir) is not True:
                if self.working_dir == '':
                    FreeCAD.Console.PrintError(
                        "Working Dir is set to be used from solver object "
                        "but Dir from solver object \'{}\' is empty.\n".format(
                            self.working_dir))
                else:
                    FreeCAD.Console.PrintError(
                        "Dir from solver object \'{}\' doesn't exist.\n".
                        format(self.working_dir))
                self.working_dir = femutils.get_pref_working_dir(self.solver)
                FreeCAD.Console.PrintMessage(
                    "Dir \'{}\' will be used instead.\n".format(
                        self.working_dir))
        else:
            self.working_dir = femutils.get_pref_working_dir(self.solver)

        # check working_dir exist, if not use a tmp dir and inform the user
        if femutils.check_working_dir(self.working_dir) is not True:
            FreeCAD.Console.PrintError(
                "Dir \'{}\' doesn't exist or cannot be created.\n".format(
                    self.working_dir))
            self.working_dir = femutils.get_temp_dir(self.solver)
            FreeCAD.Console.PrintMessage(
                "Dir \'{}\' will be used instead.\n".format(self.working_dir))

        # Update inp file name
        self.set_inp_file_name()
示例#5
0
    def onChanged(self, vobj, prop):

        if prop == "ShapeColor":
            if hasattr(vobj, "ShapeColor"):
                l = vobj.ShapeColor
                self.mat.diffuseColor.setValue([l[0], l[1], l[2]])
        elif prop == "LineWidth":
            if hasattr(vobj, "LineWidth"):
                self.dst.lineWidth = vobj.LineWidth
        elif prop == "FontName":
            if hasattr(vobj, "FontName"):
                if vobj.FontName:
                    if sys.version_info.major < 3:
                        self.fon.name = vobj.FontName.encode("utf8")
                    else:
                        self.fon.name = vobj.FontName
        elif prop in ["FontSize", "DisplayOffset", "OriginOffset"]:
            if hasattr(vobj, "FontSize") and hasattr(
                    vobj, "DisplayOffset") and hasattr(vobj, "OriginOffset"):
                fs = vobj.FontSize.Value
                if fs:
                    self.fon.size = fs
                    b = vobj.DisplayOffset.Base
                    self.tra.translation.setValue(
                        [b.x + fs / 8, b.y, b.z + fs / 8])
                    if vobj.OriginOffset:
                        self.lco.point.setValues([[b.x - fs, b.y, b.z],
                                                  [b.x + fs, b.y, b.z],
                                                  [b.x, b.y - fs, b.z],
                                                  [b.x, b.y + fs, b.z],
                                                  [b.x, b.y, b.z - fs],
                                                  [b.x, b.y, b.z + fs]])
                    else:
                        self.lco.point.setValues([[-fs, 0, 0], [fs, 0, 0],
                                                  [0, -fs, 0], [0, fs, 0],
                                                  [0, 0, -fs], [0, 0, fs]])
        elif prop in ["ShowLevel", "ShowLabel"]:
            if hasattr(vobj, "ShowLevel") and hasattr(vobj, "ShowLabel"):
                rn = vobj.RootNode
                if vobj.ShowLevel or vobj.ShowLabel:
                    if rn.findChild(self.sep) == -1:
                        rn.addChild(self.sep)
                    self.onChanged(vobj, "ShowUnit")
                else:
                    if rn.findChild(self.sep) != -1:
                        rn.removeChild(self.sep)
        elif prop in ["OverrideUnit", "ShowUnit"]:
            if hasattr(vobj, "OverrideUnit") and hasattr(vobj, "ShowUnit"):
                z = vobj.Object.Placement.Base.z + vobj.Object.LevelOffset.Value
                q = FreeCAD.Units.Quantity(z, FreeCAD.Units.Length)
                txt = ""
                if vobj.ShowLabel:
                    txt += vobj.Object.Label
                if vobj.ShowLevel:
                    if txt:
                        txt += " "
                    if z >= 0:
                        txt = "+"
                    if vobj.OverrideUnit:
                        u = vobj.OverrideUnit
                    else:
                        u = q.getUserPreferred()[2]
                    q = q.getValueAs(u)
                    d = FreeCAD.ParamGet(
                        "User parameter:BaseApp/Preferences/Units").GetInt(
                            "Decimals", 0)
                    fmt = "{0:." + str(d) + "f}"
                    if not vobj.ShowUnit:
                        u = ""
                    txt += fmt.format(float(q)) + str(u)
                if isinstance(txt, unicode):
                    txt = txt.encode("utf8")
                self.txt.string.setValue(txt)
示例#6
0
#*   This program 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 program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

import os, FreeCAD, FreeCADGui

macrosList = []
macroPath = FreeCAD.ParamGet(
    "User parameter:BaseApp/Preferences/Macro").GetString("MacroPath")


class MacroCommand():
    "A template for macro commands"

    def __init__(self, macroname):
        self.macroname = macroname

    def GetResources(self):
        return {
            'Pixmap': 'Draft_Macro',
            'MenuText': self.macroname,
            'ToolTip': 'Executes the ' + self.macroname + ' macro'
        }
示例#7
0
def macroFilePath():
    grp = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macro")
    return grp.GetString("MacroPath", FreeCAD.getUserMacroDir())
示例#8
0
"""Provides the Draft Text viewprovider class."""
## @package view_text
# \ingroup DRAFT
# \brief Provides the Draft Text viewprovider class.

import pivy.coin as coin
import sys
from PySide.QtCore import QT_TRANSLATE_NOOP

import FreeCAD as App

import draftutils.utils as utils
from draftviewproviders.view_draft_annotation \
    import ViewProviderDraftAnnotation

param = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")


class ViewProviderText(ViewProviderDraftAnnotation):
    """Viewprovider for the Draft Text annotation."""
    def __init__(self, vobj):
        super(ViewProviderText, self).__init__(vobj)

        self.set_properties(vobj)
        self.Object = vobj.Object
        vobj.Proxy = self

    def set_properties(self, vobj):
        """Set the properties only if they don't already exist."""
        super(ViewProviderText, self).set_properties(vobj)
        properties = vobj.PropertiesList
示例#9
0
    def __init__(self):

        self.ac = "FreeCAD.DraftWorkingPlane.alignToPointAndAxis"
        self.param = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Draft")
        self.states = []
示例#10
0
def p_multmatrix_action(p):
    'multmatrix_action : multmatrix LPAREN matrix RPAREN OBRACE block_list EBRACE'
    if printverbose: print "MultMatrix"
    transform_matrix = FreeCAD.Matrix()
    if printverbose: print "Multmatrix"
    if printverbose: print p[3]
    m1l = sum(p[3], [])
    if any('x' in me for me in m1l):  #hexfloats
        m1l = [float.fromhex(me) for me in m1l]
        matrixisrounded = False
    elif max((len(me) for me in m1l)) >= 14:  #might have double precision
        m1l = [float(me) for me in m1l]  # assume precise output
        m1l = [(0 if (abs(me) < 1e-15) else me) for me in m1l]
        matrixisrounded = False
    else:  #trucanted numbers
        m1l = [round(float(me), 12) for me in m1l]  #round
        matrixisrounded = True
    transform_matrix = FreeCAD.Matrix(*tuple(m1l))
    if printverbose: print transform_matrix
    if printverbose: print "Apply Multmatrix"
    #   If more than one object on the stack for multmatrix fuse first
    if (len(p[6]) == 0):
        part = placeholder('group', [], '{}')
    elif (len(p[6]) > 1):
        part = fuse(p[6], "Matrix Union")
    else:
        part = p[6][0]
    if (isspecialorthogonalpython(fcsubmatrix(transform_matrix))):
        if printverbose: print "special orthogonal"
        if matrixisrounded:
            if printverbose: print "rotation rounded"
            plm = FreeCAD.Placement(transform_matrix)
            plm = FreeCAD.Placement(plm.Base, roundrotation(plm.Rotation))
            part.Placement = plm.multiply(part.Placement)
        else:
            part.Placement=FreeCAD.Placement(transform_matrix).multiply(\
                    part.Placement)
        new_part = part
    elif isrotoinversionpython(fcsubmatrix(transform_matrix)):
        if printverbose: print "orthogonal and inversion"
        cmat, axisvec = decomposerotoinversion(transform_matrix)
        new_part = doc.addObject("Part::Mirroring", 'mirr_%s' % part.Name)
        new_part.Source = part
        new_part.Normal = axisvec
        if matrixisrounded:
            if printverbose: print "rotation rounded"
            plm = FreeCAD.Placement(cmat)
            new_part.Placement = FreeCAD.Placement(plm.Base,
                                                   roundrotation(plm.Rotation))
        else:
            new_part.Placement = FreeCAD.Placement(cmat)
        new_part.Label = "mirrored %s" % part.Label
        if gui:
            part.ViewObject.hide()
    elif FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
        GetBool('useMultmatrixFeature'):
        from OpenSCADFeatures import MatrixTransform
        new_part = doc.addObject("Part::FeaturePython", 'Matrix Deformation')
        MatrixTransform(new_part, transform_matrix, part)
        if gui:
            if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
                GetBool('useViewProviderTree'):
                from OpenSCADFeatures import ViewProviderTree
                ViewProviderTree(new_part.ViewObject)
            else:
                new_part.ViewObject.Proxy = 0
            part.ViewObject.hide()
    else:
        if printverbose: print "Transform Geometry"
        #       Need to recompute to stop transformGeometry causing a crash
        doc.recompute()
        new_part = doc.addObject("Part::Feature", "Matrix Deformation")
        #  new_part.Shape = part.Base.Shape.transformGeometry(transform_matrix)
        new_part.Shape = part.Shape.transformGeometry(transform_matrix)
        if gui:
            part.ViewObject.hide()
    if False:
        #   Does not fix problemfile or beltTighener although later is closer
        newobj = doc.addObject("Part::FeaturePython", 'RefineMultMatrix')
        RefineShape(newobj, new_part)
        if gui:
            newobj.ViewObject.Proxy = 0
            new_part.ViewObject.hide()
        p[0] = [newobj]
    else:
        p[0] = [new_part]
    if printverbose: print "Multmatrix applied"
示例#11
0
def p_cylinder_action(p):
    'cylinder_action : cylinder LPAREN keywordargument_list RPAREN SEMICOL'
    if printverbose: print "Cylinder"
    tocenter = p[3]['center']
    h = float(p[3]['h'])
    r1 = float(p[3]['r1'])
    r2 = float(p[3]['r2'])
    n = int(p[3]['$fn'])
    fnmax = FreeCAD.ParamGet(\
        "User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
        GetInt('useMaxFN')
    if printverbose: print p[3]
    if h > 0:
        if (r1 == r2 and r1 > 0):
            if printverbose: print "Make Cylinder"
            if n < 3 or fnmax != 0 and n > fnmax:
                mycyl = doc.addObject("Part::Cylinder", p[1])
                mycyl.Height = h
                mycyl.Radius = r1
            else:
                if printverbose: print "Make Prism"
                if False:  #user Draft Polygon
                    mycyl = doc.addObject("Part::Extrusion", "prism")
                    mycyl.Dir = (0, 0, h)
                    try:
                        import Draft
                        mycyl.Base = Draft.makePolygon(n, r1, face=True)
                    except:
                        # If Draft can't import (probably due to lack of Pivy on Mac and
                        # Linux builds of FreeCAD), this is a fallback.
                        # or old level of FreeCAD
                        if printverbose:
                            print "Draft makePolygon Failed, falling back on manual polygon"
                        mycyl.Base = myPolygon(n, r1)
                        # mycyl.Solid = True

                    else:
                        pass
                    if gui:
                        mycyl.Base.ViewObject.hide()
                else:  #Use Part::Prism primitive
                    mycyl = doc.addObject("Part::Prism", "prism")
                    mycyl.Polygon = n
                    mycyl.Circumradius = r1
                    mycyl.Height = h

        elif (r1 != r2):
            if n < 3 or fnmax != 0 and n > fnmax:
                if printverbose: print "Make Cone"
                mycyl = doc.addObject("Part::Cone", p[1])
                mycyl.Height = h
                mycyl.Radius1 = r1
                mycyl.Radius2 = r2
            else:
                if printverbose: print "Make Frustum"
                mycyl = doc.addObject("Part::FeaturePython", 'frustum')
                Frustum(mycyl, r1, r2, n, h)
                if gui:
                    if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
                        GetBool('useViewProviderTree'):
                        from OpenSCADFeatures import ViewProviderTree
                        ViewProviderTree(mycyl.ViewObject)
                    else:
                        mycyl.ViewObject.Proxy = 0
        else:  # r1 == r2 == 0
            FreeCAD.Console.PrintWarning('cylinder with radius zero\n')
            mycyl = doc.addObject("Part::Feature", "emptycyl")
            mycyl.Shape = Part.Compound([])
    else:  # h == 0
        FreeCAD.Console.PrintWarning('cylinder with height <= zero\n')
        mycyl = doc.addObject("Part::Feature", "emptycyl")
        mycyl.Shape = Part.Compound([])
    if printverbose: print "Center = ", tocenter
    if tocenter == 'true':
        center(mycyl, 0, 0, h)
    if False:
        #   Does not fix problemfile or beltTighener although later is closer
        newobj = doc.addObject("Part::FeaturePython", 'RefineCylinder')
        RefineShape(newobj, mycyl)
        if gui:
            if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
                GetBool('useViewProviderTree'):
                from OpenSCADFeatures import ViewProviderTree
                ViewProviderTree(newobj.ViewObject)
            else:
                newobj.ViewObject.Proxy = 0
            mycyl.ViewObject.hide()
        p[0] = [newobj]
    else:
        p[0] = [mycyl]
    if printverbose: print "End Cylinder"
示例#12
0
import FreeCAD, os, sys
if FreeCAD.GuiUp:
    import FreeCADGui
    gui = True
else:
    if printverbose: print "FreeCAD Gui not present."
    gui = False

import ply.lex as lex
import ply.yacc as yacc
import Part

from OpenSCADFeatures import *
from OpenSCADUtils import *

params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD")
printverbose = params.GetBool('printVerbose', False)

if open.__module__ == '__builtin__':
    pythonopen = open  # to distinguish python built-in open function from the one declared here

# Get the token map from the lexer.  This is required.
import tokrules
from tokrules import tokens


def translate(context, text):
    "convenience function for Qt translator"
    from PySide import QtGui
    return QtGui.QApplication.translate(context, text, None, \
        QtGui.QApplication.UnicodeUTF8)
示例#13
0
def getParamRefine():
    return FreeCAD.ParamGet(
        "User parameter:BaseApp/Preferences/Mod/Part/Boolean").GetBool(
            "RefineModel")
示例#14
0
    def run(self):

        "populates the list of addons"

        self.progressbar_show.emit(True)
        u = utils.urlopen("https://github.com/FreeCAD/FreeCAD-addons")
        if not u:
            self.progressbar_show.emit(False)
            self.done.emit()
            self.stop = True
            return
        p = u.read()
        if sys.version_info.major >= 3 and isinstance(p, bytes):
            p = p.decode("utf-8")
        u.close()
        p = p.replace("\n", " ")
        p = re.findall("octicon-file-submodule(.*?)message", p)
        basedir = FreeCAD.getUserAppDataDir()
        moddir = basedir + os.sep + "Mod"
        repos = []
        # querying official addons
        for l in p:
            #name = re.findall("data-skip-pjax=\"true\">(.*?)<",l)[0]
            res = re.findall("title=\"(.*?) @", l)
            if res:
                name = res[0]
            else:
                print("AddonMananger: Debug: couldn't find title in", l)
                continue
            self.info_label.emit(name)
            #url = re.findall("title=\"(.*?) @",l)[0]
            url = utils.getRepoUrl(l)
            if url:
                addondir = moddir + os.sep + name
                #print ("found:",name," at ",url)
                if os.path.exists(addondir) and os.listdir(addondir):
                    # make sure the folder exists and it contains files!
                    state = 1
                else:
                    state = 0
                repos.append([name, url, state])
        # querying custom addons
        customaddons = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Addons").GetString(
                "CustomRepositories", "").split("\n")
        for url in customaddons:
            if url:
                name = url.split("/")[-1]
                if name.lower().endswith(".git"):
                    name = name[:-4]
                addondir = moddir + os.sep + name
                if not os.path.exists(addondir):
                    state = 0
                else:
                    state = 1
                repos.append([name, url, state])
        if not repos:
            self.info_label.emit(
                translate("AddonsInstaller", "Unable to download addon list."))
        else:
            repos = sorted(repos, key=lambda s: s[0].lower())
            for repo in repos:
                self.addon_repo.emit(repo)
            self.info_label.emit(
                translate("AddonsInstaller", "Workbenches list was updated."))
        self.progressbar_show.emit(False)
        self.done.emit()
        self.stop = True
示例#15
0
def getInfo(filename):

    "returns available file information"

    global iconbank, tempfolder

    tformat = FreeCAD.ParamGet(
        "User parameter:BaseApp/Preferences/Mod/Start").GetString(
            "TimeFormat", "%m/%d/%Y %H:%M:%S")

    def getLocalTime(timestamp):
        "returns a local time from a timestamp"
        return time.strftime(tformat, time.localtime(timestamp))

    def getSize(size):
        "returns a human-readable size"
        if size > 1024 * 1024:
            hsize = str(int(size / (1024 * 1024))) + "Mb"
        elif size > 1024:
            hsize = str(int(size / 1024)) + "Kb"
        else:
            hsize = str(int(size)) + "b"
        return hsize

    def getFreeDesktopThumbnail(filename):
        "if we have gnome libs available, try to find a system-generated thumbnail"
        try:
            import gnome.ui
            import gnomevfs
        except:
            return None

        path = os.path.abspath(filename)
        uri = gnomevfs.get_uri_from_local_path(path)
        thumb = gnome.ui.thumbnail_path_for_uri(uri, "normal")
        if os.path.exists(thumb):
            return thumb
        return None

    if os.path.exists(filename):

        if os.path.isdir(filename):
            return None

        # get normal file info
        s = os.stat(filename)
        size = getSize(s.st_size)
        ctime = getLocalTime(s.st_ctime)
        mtime = getLocalTime(s.st_mtime)
        author = ""
        company = TranslationTexts.T_UNKNOWN
        lic = TranslationTexts.T_UNKNOWN
        image = None
        descr = ""

        # get additional info from fcstd files
        if filename.lower().endswith(".fcstd"):
            try:
                zfile = zipfile.ZipFile(filename)
            except:
                print("Cannot read file: ", filename)
                return None
            files = zfile.namelist()
            # check for meta-file if it's really a FreeCAD document
            if files[0] == "Document.xml":
                doc = str(zfile.read(files[0]))
                doc = doc.replace("\n", " ")
                r = re.findall(
                    "Property name=\"CreatedBy.*?String value=\"(.*?)\"\/>",
                    doc)
                if r:
                    author = r[0]
                    # remove email if present in author field
                    if "&lt;" in author:
                        author = author.split("&lt;")[0].strip()
                r = re.findall(
                    "Property name=\"Company.*?String value=\"(.*?)\"\/>", doc)
                if r:
                    company = r[0]
                r = re.findall(
                    "Property name=\"License.*?String value=\"(.*?)\"\/>", doc)
                if r:
                    lic = r[0]
                r = re.findall(
                    "Property name=\"Comment.*?String value=\"(.*?)\"\/>", doc)
                if r:
                    descr = r[0]
                if "thumbnails/Thumbnail.png" in files:
                    if filename in iconbank:
                        image = iconbank[filename]
                    else:
                        imagedata = zfile.read("thumbnails/Thumbnail.png")
                        image = tempfile.mkstemp(dir=tempfolder,
                                                 suffix='.png')[1]
                        thumb = open(image, "wb")
                        thumb.write(imagedata)
                        thumb.close()
                        iconbank[filename] = image

        # use image itself as icon if it's an image file
        if os.path.splitext(filename)[1].lower() in [
                ".jpg", ".jpeg", ".png", ".svg"
        ]:
            image = filename
            iconbank[filename] = image

        # use freedesktop thumbnail if available
        fdthumb = getFreeDesktopThumbnail(filename)
        if fdthumb:
            image = fdthumb
            iconbank[filename] = fdthumb

        # retrieve default mime icon if needed
        if not image:
            i = QtCore.QFileInfo(filename)
            t = iconprovider.type(i)
            if not t:
                t = "Unknown"
            if t in iconbank:
                image = iconbank[t]
            else:
                icon = iconprovider.icon(i)
                if icon.availableSizes():
                    preferred = icon.actualSize(QtCore.QSize(128, 128))
                    px = icon.pixmap(preferred)
                    image = tempfile.mkstemp(dir=tempfolder, suffix='.png')[1]
                    px.save(image)
                else:
                    image = getDefaultIcon()
                iconbank[t] = image
        return [image, size, author, ctime, mtime, descr, company, lic]

    return None
示例#16
0
def render(project, prefix, external, output, width, height):
    """Run Luxrender

    Params:
    - project:  the project to render
    - prefix:   a prefix string for call (will be inserted before path to Lux)
    - external: a boolean indicating whether to call UI (true) or console
                (false) version of Lux
    - width:    rendered image width, in pixels
    - height:   rendered image height, in pixels

    Return: void
    """
    # Here you trigger a render by firing the renderer
    # executable and passing it the needed arguments, and
    # the file it needs to render

    # change image size in template
    with open(project.PageResult, "r") as f:
        template = f.read()

    res = re.findall("integer xresolution", template)
    if res:
        template = re.sub(r'"integer xresolution".*?\[.*?\]',
                          '"integer xresolution" [{}]'.format(width), template)

    res = re.findall("integer yresolution", template)
    if res:
        template = re.sub(r'"integer yresolution".*?\[.*?\]',
                          '"integer yresolution" [{}]'.format(height),
                          template)

    if res:
        f_handle, f_path = mkstemp(prefix=project.Name,
                                   suffix=os.path.splitext(
                                       project.Template)[-1])
        os.close(f_handle)
        with open(f_path, "w") as f:
            f.write(template)
        project.PageResult = f_path
        os.remove(f_path)
        App.ActiveDocument.recompute()

    params = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Render")
    args = params.GetString("LuxParameters", "")
    rpath = params.GetString("LuxRenderPath" if external else "LuxConsolePath",
                             "")
    if not rpath:
        App.Console.PrintError("Unable to locate renderer executable. "
                               "Please set the correct path in "
                               "Edit -> Preferences -> Render\n")
        return

    # Call Luxrender
    cmd = prefix + rpath + " " + args + " " + project.PageResult + "\n"
    App.Console.PrintMessage(cmd)
    try:
        Popen(shlex.split(cmd))
    except OSError as err:
        msg = "Luxrender call failed: '" + err.strerror + "'\n"
        App.Console.PrintError(msg)

    return
示例#17
0
def getSVG(section,
           renderMode="Wireframe",
           allOn=False,
           showHidden=False,
           scale=1,
           rotation=0,
           linewidth=1,
           lineColor=(0.0, 0.0, 0.0),
           fontsize=1,
           showFill=False,
           fillColor=(0.8, 0.8, 0.8),
           techdraw=False):
    """getSVG(section, [renderMode, allOn, showHidden, scale, rotation,
              linewidth, lineColor, fontsize, showFill, fillColor, techdraw]):

    returns an SVG fragment from an Arch section plane. If
    allOn is True, all cut objects are shown, regardless if they are visible or not.
    renderMode can be Wireframe (default) or Solid to use the Arch solid renderer. If
    showHidden is True, the hidden geometry above the section plane is shown in dashed line.
    If showFill is True, the cut areas get filled with a pattern.
    lineColor -- Color of lines for the renderMode "Wireframe".
    fillColor -- If showFill is True and renderMode is "Wireframe",
                 the cut areas are filled with fillColor.
    """

    if not section.Objects:
        return ""
    import Part, DraftGeomUtils
    p = FreeCAD.Placement(section.Placement)
    direction = p.Rotation.multVec(FreeCAD.Vector(0, 0, 1))
    objs = Draft.getGroupContents(section.Objects, walls=True, addgroups=True)
    if not allOn:
        objs = Draft.removeHidden(objs)

    # separate spaces and Draft objects
    spaces = []
    nonspaces = []
    drafts = []
    windows = []
    cutface = None
    for o in objs:
        if Draft.getType(o) == "Space":
            spaces.append(o)
        elif Draft.getType(o) in ["Dimension", "Annotation", "Label"]:
            drafts.append(o)
        elif o.isDerivedFrom("Part::Part2DObject"):
            drafts.append(o)
        elif looksLikeDraft(o):
            drafts.append(o)
        else:
            nonspaces.append(o)
        if Draft.getType(o) == "Window":
            windows.append(o)
    objs = nonspaces

    archUserParameters = FreeCAD.ParamGet(
        "User parameter:BaseApp/Preferences/Mod/Arch")
    scaledLineWidth = linewidth / scale
    svgLineWidth = str(scaledLineWidth) + 'px'
    st = archUserParameters.GetFloat("CutLineThickness", 2)
    svgCutLineWidth = str(scaledLineWidth * st) + 'px'
    yt = archUserParameters.GetFloat("SymbolLineThickness", 0.6)
    svgSymbolLineWidth = str(linewidth * yt)
    hiddenPattern = archUserParameters.GetString("archHiddenPattern", "30,10")
    svgHiddenPattern = hiddenPattern.replace(" ", "")
    fillpattern = '<pattern id="sectionfill" patternUnits="userSpaceOnUse" patternTransform="matrix(5,0,0,5,0,0)"'
    fillpattern += ' x="0" y="0" width="10" height="10">'
    fillpattern += '<g>'
    fillpattern += '<rect width="10" height="10" style="stroke:none; fill:#ffffff" /><path style="stroke:#000000; stroke-width:1" d="M0,0 l10,10" /></g></pattern>'
    svgLineColor = Draft.getrgb(lineColor)
    svg = ''

    # reading cached version
    svgcache = None
    if hasattr(section.Proxy, "svgcache") and section.Proxy.svgcache:
        svgcache = section.Proxy.svgcache[0]
        if section.Proxy.svgcache[1] != renderMode:
            svgcache = None
        if section.Proxy.svgcache[2] != showHidden:
            svgcache = None
        if section.Proxy.svgcache[3] != showFill:
            svgcache = None

    # generating SVG
    if renderMode in ["Solid", 1]:
        if not svgcache:
            svgcache = ''
            # render using the Arch Vector Renderer
            import ArchVRM, WorkingPlane
            wp = WorkingPlane.plane()
            wp.setFromPlacement(section.Placement)
            #wp.inverse()
            render = ArchVRM.Renderer()
            render.setWorkingPlane(wp)
            render.addObjects(objs)
            if showHidden:
                render.cut(section.Shape, showHidden)
            else:
                render.cut(section.Shape)
            svgcache += '<g transform="scale(1,-1)">\n'
            svgcache += render.getViewSVG(linewidth="SVGLINEWIDTH")
            svgcache += fillpattern
            svgcache += render.getSectionSVG(linewidth="SVGCUTLINEWIDTH",
                                             fillpattern="sectionfill")
            if showHidden:
                svgcache += render.getHiddenSVG(linewidth="SVGLINEWIDTH")
            svgcache += '</g>\n'
            # print(render.info())
            section.Proxy.svgcache = [
                svgcache, renderMode, showHidden, showFill
            ]
    else:
        shapes, hshapes, sshapes, cutface, cutvolume, invcutvolume = getCutShapes(
            objs, section, showHidden)

        if not svgcache:
            svgcache = ""
            # render using the Drawing module
            import Drawing, Part
            if shapes:
                baseshape = Part.makeCompound(shapes)
                style = {
                    'stroke': "SVGLINECOLOR",
                    'stroke-width': "SVGLINEWIDTH"
                }
                svgcache += Drawing.projectToSVG(baseshape,
                                                 direction,
                                                 hStyle=style,
                                                 h0Style=style,
                                                 h1Style=style,
                                                 vStyle=style,
                                                 v0Style=style,
                                                 v1Style=style)
            if hshapes:
                hshapes = Part.makeCompound(hshapes)
                style = {
                    'stroke': "SVGLINECOLOR",
                    'stroke-width': "SVGLINEWIDTH",
                    'stroke-dasharray': "SVGHIDDENPATTERN"
                }
                svgcache += Drawing.projectToSVG(hshapes,
                                                 direction,
                                                 hStyle=style,
                                                 h0Style=style,
                                                 h1Style=style,
                                                 vStyle=style,
                                                 v0Style=style,
                                                 v1Style=style)
            if sshapes:
                if showFill:
                    #svgcache += fillpattern
                    svgcache += '<g transform="rotate(180)">\n'
                    for s in sshapes:
                        if s.Edges:
                            #svg += Draft.getSVG(s,direction=direction.negative(),linewidth=0,fillstyle="sectionfill",color=(0,0,0))
                            # temporarily disabling fill patterns
                            svgcache += Draft.getSVG(
                                s,
                                direction=direction.negative(),
                                linewidth=0,
                                fillstyle=Draft.getrgb(fillColor),
                                color=lineColor)
                    svgcache += "</g>\n"
                sshapes = Part.makeCompound(sshapes)
                style = {
                    'stroke': "SVGLINECOLOR",
                    'stroke-width': "SVGCUTLINEWIDTH"
                }
                svgcache += Drawing.projectToSVG(sshapes,
                                                 direction,
                                                 hStyle=style,
                                                 h0Style=style,
                                                 h1Style=style,
                                                 vStyle=style,
                                                 v0Style=style,
                                                 v1Style=style)
            section.Proxy.svgcache = [
                svgcache, renderMode, showHidden, showFill
            ]
    svgcache = svgcache.replace("SVGLINECOLOR", svgLineColor)
    svgcache = svgcache.replace("SVGLINEWIDTH", svgLineWidth)
    svgcache = svgcache.replace("SVGHIDDENPATTERN", svgHiddenPattern)
    svgcache = svgcache.replace("SVGCUTLINEWIDTH", svgCutLineWidth)
    svg += svgcache

    if drafts:
        if not techdraw:
            svg += '<g transform="scale(1,-1)">'
        for d in drafts:
            svg += Draft.getSVG(d,
                                scale=scale,
                                linewidth=svgSymbolLineWidth,
                                fontsize=fontsize,
                                direction=direction,
                                color=lineColor,
                                techdraw=techdraw,
                                rotation=rotation)
        if not techdraw:
            svg += '</g>'

    # filter out spaces not cut by the section plane
    if cutface and spaces:
        spaces = [
            s for s in spaces if s.Shape.BoundBox.intersect(cutface.BoundBox)
        ]
    if spaces:
        if not techdraw:
            svg += '<g transform="scale(1,-1)">'
        for s in spaces:
            svg += Draft.getSVG(s,
                                scale=scale,
                                linewidth=svgSymbolLineWidth,
                                fontsize=fontsize,
                                direction=direction,
                                color=lineColor,
                                techdraw=techdraw,
                                rotation=rotation)
        if not techdraw:
            svg += '</g>'

    # add additional edge symbols from windows
    cutwindows = []
    if cutface and windows:
        cutwindows = [
            w.Name for w in windows
            if w.Shape.BoundBox.intersect(cutface.BoundBox)
        ]
    if windows:
        sh = []
        for w in windows:
            if not hasattr(w.Proxy, "sshapes"):
                w.Proxy.execute(w)
            if hasattr(w.Proxy, "sshapes"):
                if w.Proxy.sshapes and (w.Name in cutwindows):
                    c = Part.makeCompound(w.Proxy.sshapes)
                    c.Placement = w.Placement
                    sh.append(c)
            # buggy for now...
            #if hasattr(w.Proxy,"vshapes"):
            #    if w.Proxy.vshapes:
            #        c = Part.makeCompound(w.Proxy.vshapes)
            #        c.Placement = w.Placement
            #        sh.append(c)
        if sh:
            if not techdraw:
                svg += '<g transform="scale(1,-1)">'
            for s in sh:
                svg += Draft.getSVG(s,
                                    scale=scale,
                                    linewidth=svgSymbolLineWidth,
                                    fontsize=fontsize,
                                    fillstyle="none",
                                    direction=direction,
                                    color=lineColor,
                                    techdraw=techdraw,
                                    rotation=rotation)
            if not techdraw:
                svg += '</g>'

    return svg
示例#18
0
    def __init__(self):
        super().__init__()
        """Initialize Draft_Edit Command."""
        self.running = False
        self.trackers = {'object': []}
        self.overNode = None  # preselected node with mouseover
        self.edited_objects = []
        self.obj = None
        self.editing = None

        # event callbacks
        self.selection_callback = None
        self._keyPressedCB = None
        self._mouseMovedCB = None
        self._mousePressedCB = None

        # this stores the DisplayMode of the object to restore it after editing
        # only used by Arch Structure
        self.objs_formats = {}

        # settings
        param = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
        self.maxObjects = param.GetInt("DraftEditMaxObjects", 5)
        self.pick_radius = param.GetInt("DraftEditPickRadius", 20)

        self.alt_edit_mode = 0  # default edit mode for objects

        # preview
        self.ghost = None

        # setup gui_tools for every supported object
        self.gui_tools_repository = GuiToolsRepository()

        self.gui_tools_repository.add('Wire', edit_draft.DraftWireGuiTools())
        self.gui_tools_repository.add('BSpline',
                                      edit_draft.DraftBSplineGuiTools())
        self.gui_tools_repository.add('BezCurve',
                                      edit_draft.DraftBezCurveGuiTools())
        self.gui_tools_repository.add('Circle',
                                      edit_draft.DraftCircleGuiTools())
        self.gui_tools_repository.add('Rectangle',
                                      edit_draft.DraftRectangleGuiTools())
        self.gui_tools_repository.add('Polygon',
                                      edit_draft.DraftPolygonGuiTools())
        self.gui_tools_repository.add('Ellipse',
                                      edit_draft.DraftEllipseGuiTools())
        self.gui_tools_repository.add(
            'Dimension',
            edit_draft.DraftDimensionGuiTools())  # Backward compatibility
        self.gui_tools_repository.add('LinearDimension',
                                      edit_draft.DraftDimensionGuiTools())

        self.gui_tools_repository.add('Wall', edit_arch.ArchWallGuiTools())
        self.gui_tools_repository.add('Window', edit_arch.ArchWindowGuiTools())
        self.gui_tools_repository.add('Structure',
                                      edit_arch.ArchStructureGuiTools())
        self.gui_tools_repository.add('Space', edit_arch.ArchSpaceGuiTools())
        self.gui_tools_repository.add('PanelCut',
                                      edit_arch.ArchPanelCutGuiTools())
        self.gui_tools_repository.add('PanelSheet',
                                      edit_arch.ArchPanelSheetGuiTools())

        self.gui_tools_repository.add('Part::Line',
                                      edit_part.PartLineGuiTools())
        self.gui_tools_repository.add('Part::Box', edit_part.PartBoxGuiTools())
        self.gui_tools_repository.add('Part::Cylinder',
                                      edit_part.PartCylinderGuiTools())
        self.gui_tools_repository.add('Part::Cone',
                                      edit_part.PartConeGuiTools())
        self.gui_tools_repository.add('Part::Sphere',
                                      edit_part.PartSphereGuiTools())

        self.gui_tools_repository.add(
            'Sketcher::SketchObject',
            edit_sketcher.SketcherSketchObjectGuiTools())
示例#19
0
import FreeCAD, FreeCADGui, sys
rf = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/RecentFiles")
FreeCAD.loadFile(rf.GetString("MRU1"))
    def __init__(self, solver_runner_obj):
        ui_path = os.path.dirname(
            __file__) + os.path.sep + "TaskPanelCfdSolverControl.ui"
        self.form = FreeCADGui.PySideUic.loadUi(ui_path)
        self.fem_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem")

        self.analysis_object = FemGui.getActiveAnalysis()

        self.solver_runner = solver_runner_obj
        self.solver_object = solver_runner_obj.solver

        self.SolverProcess = QtCore.QProcess()
        self.Timer = QtCore.QTimer()
        self.Timer.start(3000)  # may not enough for CFD

        # update UI
        self.fem_console_message = ''

        #======================================================================================================
        #
        # Code associated with running solver from GUI
        #
        #======================================================================================================
        self.solver_run_process = QtCore.QProcess()

        QtCore.QObject.connect(self.solver_run_process,
                               QtCore.SIGNAL("started()"),
                               self.solverProcessStarted)
        #QtCore.QObject.connect(self.solver_run_process, QtCore.SIGNAL("stateChanged(QProcess::ProcessState)"), self.solverProcessStateChanged)
        QtCore.QObject.connect(self.solver_run_process,
                               QtCore.SIGNAL("finished(int)"),
                               self.solverProcessFinished)
        QtCore.QObject.connect(self.solver_run_process,
                               QtCore.SIGNAL("error(QProcess::ProcessError)"),
                               self.solverProcessError)
        #self.solver_run_process.readyReadStandardOutput.connect(self.stdoutReady)
        QtCore.QObject.connect(self.solver_run_process,
                               QtCore.SIGNAL("readyReadStandardOutput()"),
                               self.plotResiduals)
        #======================================================================================================

        # Connect Signals and Slots
        QtCore.QObject.connect(self.form.tb_choose_working_dir,
                               QtCore.SIGNAL("clicked()"),
                               self.chooseWorkingDir)
        QtCore.QObject.connect(self.form.pb_write_inp,
                               QtCore.SIGNAL("clicked()"),
                               self.writeSolverInput)
        QtCore.QObject.connect(self.form.pb_edit_inp,
                               QtCore.SIGNAL("clicked()"),
                               self.editSolverInput)
        QtCore.QObject.connect(self.form.pb_run_solver,
                               QtCore.SIGNAL("clicked()"),
                               self.runSolverProcess)
        QtCore.QObject.connect(self.form.pb_terminate_solver,
                               QtCore.SIGNAL("clicked()"),
                               self.killSolverProcess)
        QtCore.QObject.connect(self.form.pb_show_result,
                               QtCore.SIGNAL("clicked()"), self.showResult)
        QtCore.QObject.connect(self.form.pb_view_externally,
                               QtCore.SIGNAL("clicked()"),
                               self.viewResultExternally)
        self.form.pb_terminate_solver.setEnabled(False)
        self.form.pb_show_result.setEnabled(False)
        self.form.pb_view_externally.setEnabled(False)

        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"),
                               self.updateText)
        self.form.pb_show_result.setEnabled(
            True)  # delete this once finished signal is correctly managed
        if self.solver_object.ResultObtained:
            self.form.pb_show_result.setEnabled(True)
            self.form.pb_view_externally.setEnabled(True)
        self.Start = time.time(
        )  #debug tobe removed, it is not used in this taskpanel
        self.update()  # update UI from FemSolverObject, like WorkingDir
示例#21
0
def preferences():
    return FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Path")
示例#22
0
    def __init__(self, obj):
        self.Type = "FemSolverCalculix"
        self.Object = obj  # keep a ref to the DocObj for nonGui usage
        obj.Proxy = self  # link between App::DocumentObject to  this object

        obj.addProperty("App::PropertyString", "SolverType", "Base",
                        "Type of the solver",
                        1)  # the 1 set the property to ReadOnly
        obj.SolverType = str(self.Type)

        # fem_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/General")  # not needed ATM
        ccx_prefs = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem/Ccx")

        obj.addProperty(
            "App::PropertyPath", "WorkingDir", "Fem",
            "Working directory for calculations, will only be used it is left blank in preferences"
        )
        # the working directory is not set, the solver working directory is only used if the preferences working directory is left blank

        obj.addProperty("App::PropertyEnumeration", "AnalysisType", "Fem",
                        "Type of the analysis")
        obj.AnalysisType = FemToolsCcx.FemToolsCcx.known_analysis_types
        analysis_type = ccx_prefs.GetInt("AnalysisType", 0)
        obj.AnalysisType = FemToolsCcx.FemToolsCcx.known_analysis_types[
            analysis_type]

        choices_geom_nonlinear = ["linear", "nonlinear"]
        obj.addProperty("App::PropertyEnumeration", "GeometricalNonlinearity",
                        "Fem", "Set geometrical nonlinearity")
        obj.GeometricalNonlinearity = choices_geom_nonlinear
        nonlinear_geom = ccx_prefs.GetBool("NonlinearGeometry", False)
        if nonlinear_geom is True:
            obj.GeometricalNonlinearity = choices_geom_nonlinear[
                1]  # nonlinear
        else:
            obj.GeometricalNonlinearity = choices_geom_nonlinear[0]  # linear

        choices_material_nonlinear = ["linear", "nonlinear"]
        obj.addProperty(
            "App::PropertyEnumeration", "MaterialNonlinearity", "Fem",
            "Set material nonlinearity (needs geometrical nonlinearity)")
        obj.MaterialNonlinearity = choices_material_nonlinear
        obj.MaterialNonlinearity = choices_material_nonlinear[0]

        obj.addProperty("App::PropertyIntegerConstraint", "EigenmodesCount",
                        "Fem", "Number of modes for frequency calculations")
        noe = ccx_prefs.GetInt("EigenmodesCount", 10)
        obj.EigenmodesCount = (noe, 1, 100, 1)

        obj.addProperty("App::PropertyFloatConstraint", "EigenmodeLowLimit",
                        "Fem",
                        "Low frequency limit for eigenmode calculations")
        ell = ccx_prefs.GetFloat("EigenmodeLowLimit", 0.0)
        obj.EigenmodeLowLimit = (ell, 0.0, 1000000.0, 10000.0)

        obj.addProperty("App::PropertyFloatConstraint", "EigenmodeHighLimit",
                        "Fem",
                        "High frequency limit for eigenmode calculations")
        ehl = ccx_prefs.GetFloat("EigenmodeHighLimit", 1000000.0)
        obj.EigenmodeHighLimit = (ehl, 0.0, 1000000.0, 10000.0)

        obj.addProperty(
            "App::PropertyIntegerConstraint", "IterationsThermoMechMaximum",
            "Fem",
            "Maximum Number of thermo mechanical iterations in each time step before stopping jobs"
        )
        niter = ccx_prefs.GetInt("AnalysisMaxIterations", 200)
        obj.IterationsThermoMechMaximum = niter

        obj.addProperty("App::PropertyFloatConstraint", "TimeInitialStep",
                        "Fem", "Initial time steps")
        ini = ccx_prefs.GetFloat("AnalysisTimeInitialStep", 1.0)
        obj.TimeInitialStep = ini

        obj.addProperty("App::PropertyFloatConstraint", "TimeEnd", "Fem",
                        "End time analysis")
        eni = ccx_prefs.GetFloat("AnalysisTime", 1.0)
        obj.TimeEnd = eni

        obj.addProperty(
            "App::PropertyBool", "ThermoMechSteadyState", "Fem",
            "Choose between steady state thermo mech or transient thermo mech analysis"
        )
        sted = ccx_prefs.GetBool("StaticAnalysis", True)
        obj.ThermoMechSteadyState = sted

        obj.addProperty(
            "App::PropertyBool", "IterationsControlParameterTimeUse", "Fem",
            "Use the user defined time incrementation control parameter")
        use_non_ccx_iterations_param = ccx_prefs.GetInt(
            "UseNonCcxIterationParam", False)
        obj.IterationsControlParameterTimeUse = use_non_ccx_iterations_param

        obj.addProperty("App::PropertyBool", "SplitInputWriter", "Fem",
                        "Split writing of ccx input file")
        split = ccx_prefs.GetBool("SplitInputWriter", False)
        obj.SplitInputWriter = split

        ccx_default_time_incrementation_control_parameter = {
            # iteration parameter
            'I_0': 4,
            'I_R': 8,
            'I_P': 9,
            'I_C': 200,  # ccx default = 16
            'I_L': 10,
            'I_G': 400,  # ccx default = 4
            'I_S': None,
            'I_A': 200,  # ccx default = 5
            'I_J': None,
            'I_T': None,
            # cutback parameter
            'D_f': 0.25,
            'D_C': 0.5,
            'D_B': 0.75,
            'D_A': 0.85,
            'D_S': None,
            'D_H': None,
            'D_D': 1.5,
            'W_G': None
        }
        p = ccx_default_time_incrementation_control_parameter
        p_iter = '{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}'.format(
            p['I_0'], p['I_R'], p['I_P'], p['I_C'], p['I_L'], p['I_G'], '',
            p['I_A'], '', '')
        p_cutb = '{0},{1},{2},{3},{4},{5},{6},{7}'.format(
            p['D_f'], p['D_C'], p['D_B'], p['D_A'], '', '', p['D_D'], '')
        obj.addProperty(
            "App::PropertyString", "IterationsControlParameterIter", "Fem",
            "User defined time incrementation iterations control parameter")
        obj.IterationsControlParameterIter = p_iter
        obj.addProperty(
            "App::PropertyString", "IterationsControlParameterCutb", "Fem",
            "User defined time incrementation cutbacks control parameter")
        obj.IterationsControlParameterCutb = p_cutb

        obj.addProperty(
            "App::PropertyBool", "IterationsUserDefinedIncrementations", "Fem",
            "Set to True to switch off the ccx automatic incrementation completely (ccx parameter DIRECT). Use with care. Analysis may not converge!"
        )
        obj.IterationsUserDefinedIncrementations = False

        obj.addProperty(
            "App::PropertyBool", "IterationsUserDefinedTimeStepLength", "Fem",
            "Set to True to use the user defined time steps. The time steps are set with TimeInitialStep and TimeEnd"
        )
        obj.IterationsUserDefinedTimeStepLength = False

        known_ccx_solver_types = [
            "default", "spooles", "iterativescaling", "iterativecholesky"
        ]
        obj.addProperty("App::PropertyEnumeration", "MatrixSolverType", "Fem",
                        "Type of solver to use")
        obj.MatrixSolverType = known_ccx_solver_types
        solver_type = ccx_prefs.GetInt("Solver", 0)
        obj.MatrixSolverType = known_ccx_solver_types[solver_type]

        obj.addProperty("App::PropertyBool", "BeamShellResultOutput3D", "Fem",
                        "Output 3D results for 1D and 2D anlysis ")
        dimout = ccx_prefs.GetBool("BeamShellOutput", False)
        obj.BeamShellResultOutput3D = dimout
示例#23
0
    def setup_ccx(self, ccx_binary=None, ccx_binary_sig="CalculiX"):
        """Set Calculix binary path and validate its execution.

        Parameters
        ----------
        ccx_binary : str, optional
            It defaults to `None`. The path to the `ccx` binary. If it is `None`,
            the path is guessed.
        ccx_binary_sig : str, optional
            Defaults to 'CalculiX'. Expected output from `ccx` when run empty.

        Raises
        ------
        Exception
        """
        error_title = "No CalculiX binary ccx"
        error_message = ""
        from platform import system
        ccx_std_location = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem/Ccx").GetBool(
                "UseStandardCcxLocation", True)
        if ccx_std_location:
            if system() == "Windows":
                ccx_path = FreeCAD.getHomePath() + "bin/ccx.exe"
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"
                ).SetString("ccxBinaryPath", ccx_path)
                self.ccx_binary = ccx_path
            elif system() in ("Linux", "Darwin"):
                p1 = subprocess.Popen(["which", "ccx"], stdout=subprocess.PIPE)
                if p1.wait() == 0:
                    if sys.version_info.major >= 3:
                        ccx_path = p1.stdout.read().decode("utf8").split(
                            "\n")[0]
                    else:
                        ccx_path = p1.stdout.read().split("\n")[0]
                elif p1.wait() == 1:
                    error_message = (
                        "FEM: CalculiX binary ccx not found in "
                        "standard system binary path. "
                        "Please install ccx or set path to binary "
                        "in FEM preferences tab CalculiX.\n")
                    if FreeCAD.GuiUp:
                        QtGui.QMessageBox.critical(None, error_title,
                                                   error_message)
                    raise Exception(error_message)
                self.ccx_binary = ccx_path
        else:
            if not ccx_binary:
                self.ccx_prefs = FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Fem/Ccx")
                ccx_binary = self.ccx_prefs.GetString("ccxBinaryPath", "")
                if not ccx_binary:
                    FreeCAD.ParamGet(
                        "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"
                    ).SetBool("UseStandardCcxLocation", True)
                    error_message = (
                        "FEM: CalculiX binary ccx path not set at all. "
                        "The use of standard path was activated in "
                        "FEM preferences tab CalculiX. Please try again!\n")
                    if FreeCAD.GuiUp:
                        QtGui.QMessageBox.critical(None, error_title,
                                                   error_message)
                    raise Exception(error_message)
            self.ccx_binary = ccx_binary

        startup_info = None
        if system() == "Windows":
            # Windows workaround to avoid blinking terminal window
            startup_info = subprocess.STARTUPINFO()
            startup_info.dwFlags = subprocess.STARTF_USESHOWWINDOW
        ccx_stdout = None
        ccx_stderr = None
        try:
            p = subprocess.Popen([self.ccx_binary],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=False,
                                 startupinfo=startup_info)
            ccx_stdout, ccx_stderr = p.communicate()
            if ccx_binary_sig in str(ccx_stdout):
                self.ccx_binary_present = True
            else:
                raise Exception("FEM: wrong ccx binary")
                # since we raise an exception the try will fail and
                # the exception later with the error popup will be raised
                # TODO: I'm still able to break it.
                # If user doesn't give a file but a path without a file or
                # a file which is not a binary no exception at all is raised.
        except OSError as e:
            FreeCAD.Console.PrintError("{}\n".format(e))
            if e.errno == 2:
                error_message = (
                    "FEM: CalculiX binary ccx \'{}\' not found. "
                    "Please set the CalculiX binary ccx path in "
                    "FEM preferences tab CalculiX.\n".format(ccx_binary))
                if FreeCAD.GuiUp:
                    QtGui.QMessageBox.critical(None, error_title,
                                               error_message)
                raise Exception(error_message)
        except Exception as e:
            FreeCAD.Console.PrintError("{}\n".format(e))
            error_message = (
                "FEM: CalculiX ccx \'{}\' output \'{}\' doesn't "
                "contain expected phrase \'{}\'. "
                "There are some problems when running the ccx binary. "
                "Check if ccx runs standalone without FreeCAD.\n".format(
                    ccx_binary, ccx_stdout, ccx_binary_sig))
            if FreeCAD.GuiUp:
                QtGui.QMessageBox.critical(None, error_title, error_message)
            raise Exception(error_message)
示例#24
0
def genresult(w=None, fn='/home/thomas/Bilder/bp_325.png', s=150, mode='grey'):
    from . import cv2
    import numpy as np
    fn = FreeCAD.ParamGet('User parameter:Plugins/reconstruction').GetString(
        "Document")
    print(("genresult", fn))
    fcupd = w != None and w.computef.isChecked()
    debug = w != None and w.debugf.isChecked()
    '''
	fn='/home/thomas/Dokumente/freecad_buch/b244_perspective_transform.py/Prozessmodell.jpg'
	fn='/home/thomas/Bilder/122_PANA/P1220700.JPG'
	fn='/home/thomas/Bilder/122_PANA/P1220701.JPG'
	fn='/home/thomas/Bilder/122_PANA/P1220702.JPG'
	fn='/home/thomas/Bilder/122_PANA/P1220703.JPG'
	#fn=
	'''
    img = cv2.imread(fn, 0)
    imgr = cv2.imread(fn)
    try:
        imgr = cv2.cvtColor(imgr, cv2.COLOR_GRAY2RGB)
    except:
        pass
    hsv = cv2.cvtColor(imgr, cv2.COLOR_BGR2HSV)

    print(imgr.shape)
    shx, shy, _t = imgr.shape
    # img ist sw

    im3 = cv2.resize(img, (800, 800))
    if debug: cv2.imshow("image", im3)

    print(("berechne img2 nach mode", mode))
    # schwellwert 110
    img2 = img

    if mode == 'grey': img2 = img
    elif mode == 'r': img2 = imgr[:, :, 0]
    elif mode == 'g': img2 = imgr[:, :, 1]
    elif mode == 'b': img2 = imgr[:, :, 2]
    elif mode == 'h': img2 = hsv[:, :, 0]
    elif mode == 's': img2 = hsv[:, :, 1]
    elif mode == 'v': img2 = hsv[:, :, 2]

    img2 = (img2 > s) * 240
    img2 = np.array(img2, dtype=np.uint8)

    ks = 50
    kernel = np.ones((ks, ks), np.uint8)

    closing = img2

    closing = cv2.morphologyEx(img2, cv2.MORPH_CLOSE, kernel)
    closing = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)

    edges = cv2.Canny(closing, 100, 200)
    print(("size edges", edges.shape))

    t = np.where(edges == 255)

    pts = []
    for i in range(len(t[0])):
        pts.append(FreeCAD.Vector(t[0][i], t[1][i], 0))

    print("hah")
    edges2 = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
    edges2 *= 0

    #lines = cv2.HoughLinesP(edges,1,np.pi/180,100, minLineLength = 20, maxLineGap = 100)[0]
    lines = cv2.HoughLinesP(edges,
                            1,
                            np.pi / 180,
                            100,
                            minLineLength=20,
                            maxLineGap=20)[0]

    if lines != None:
        print("huhu")
        #		print lines
        FreeCAD.ll = np.array(lines)
        ll = np.array(lines).swapaxes(0, 1)

        #		print ll[0]
        #		xm=0.5*(ll[0].mean()+ll[2].mean())
        #		ym=0.5*(ll[1].mean()+ll[3].mean())

        for x1, y1, x2, y2 in lines:
            cv2.line(edges2, (x1, y1), (x2, y2), (0, 255, 255, 255), 1)

        for x1, y1, x2, y2 in lines:
            cv2.line(imgr, (x1, y1), (x2, y2), (0, 255, 255, 255), 15)
            cv2.line(imgr, (x1, y1), (x2, y2), (0, 0, 255, 255), 5)

        print("directionsa ")
        dirs = []
        plines = []
        xm = 0
        ym = 0
        for x1, y1, x2, y2 in lines:
            p1 = FreeCAD.Vector(x1, -y1 + shx, 10)
            p2 = FreeCAD.Vector(x2, -y2 + shx, 10)

            plines.append(Part.makePolygon([p1, p2]))

            #			pts += [FreeCAD.Vector(x,y,0),FreeCAD.Vector(x+y,y-x,0)]
            d = FreeCAD.Vector().projectToLine(p1 + 1000000 * (p2 - p1),
                                               p2 + 1000000 * (p1 - p2))
            alpha = np.arctan2(x2 - x1, y2 - y1)
            print((round(d.Length, 1), round(alpha / np.pi * 180, 1)))
            #d.normalize()
            #print (d.normalize(),(p1-p2).normalize())
            dirs.append([round(d.Length, 1), round(alpha / np.pi * 180, 1)])
            FreeCAD.dirs = dirs

        p1 = FreeCAD.Vector(0, 0, 10)
        p2 = FreeCAD.Vector(shy, shx, 10)
        plines.append(Part.makePolygon([p1, p2]))
        if fcupd:
            Part.show(Part.Compound(plines))
            App.ActiveDocument.ActiveObject.Label = "dir 345 obhj"
            App.ActiveDocument.ActiveObject.ViewObject.LineColor = (1.0, 0.,
                                                                    0.)

    print("b")

    # schnittpunkte berechnen
    if lines != None:
        maxx, maxy = img.shape
        apts = [FreeCAD.Vector(x1, y1, 0) for x1, y1, x2, y2 in lines]
        dirs = [
            FreeCAD.Vector(x2 - x1, y2 - y1, 0) for x1, y1, x2, y2 in lines
        ]

        ptsq = []
        for i, h in enumerate(apts):
            for j in range(i):
                p = RayIntersection(apts[i], dirs[i], apts[j], dirs[j])
                if p != None:
                    if p.x > -maxx and p.x < 2 * maxx and p.y > -maxy and p.y < 2 * maxy:
                        ptsq.append(FreeCAD.Vector(p[0], 1500 - p[1], 0))
                        print(p)

        import Points
        FreeCAD.ptsq = ptsq
        if fcupd:
            Points.show(Points.Points(ptsq))
            App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (1.0, 0.,
                                                                     0.)
            App.ActiveDocument.ActiveObject.ViewObject.PointSize = 5

        print("hone")

        # define criteria and apply kmeans()
        '''
		Z=[[p.x,p.y,0] for p in ptsq]
		criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 3.0)
		Z2=np.float32(Z)
		ret,label,center=cv2.kmeans(Z2, 4, criteria, 10, 0)
		ptsc=[FreeCAD.Vector(p) for p in center]
		Points.show(Points.Points(ptsc))
		App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(1.0,0.,0.)
		App.ActiveDocument.ActiveObject.ViewObject.PointSize=10

		print ret
		print label
		print "center"
		print center
		'''

        import Points

        dist = {}
        # ptsq=FreeCAD.ptsq
        for i, p in enumerate(ptsq):
            ds = 0
            for j, q in enumerate(ptsq):
                if i != j:
                    ds += 1.0 / (1 + (p - q).Length)
            print(ds)
            dist[i] = ds

        vs = list(dist.values())
        vs.sort()

        its = [i for i in dist if dist[i] in vs[-70:-1]]
        cpis = [ptsq[i] for i in its]
        if fcupd:
            Points.show(Points.Points(cpis))
            App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (1.0, 1.,
                                                                     0.)
            App.ActiveDocument.ActiveObject.ViewObject.PointSize = 12

    edges3 = cv2.resize(edges2, (800, 800))
    if debug: cv2.imshow("cont", edges3)

    imgr = cv2.resize(imgr, (640, 480))
    if debug: cv2.imshow("imgr", imgr)
    cv2.imwrite('/tmp/result.png', imgr)

    if w != None and w.computef.isChecked():
        showborders(shx)

    return
    if 0:
        import Points
        Points.show(Points.Points(pts))

        ctn = np.array([[p.x, p.y] for p in pts], dtype=np.float32)
        ch = cv2.convexHull(np.array(ctn))

        ptsc = [FreeCAD.Vector(c[0, 0], c[0, 1], 0) for c in ch]

        import Draft
        Draft.makeWire(ptsc, closed=True)
示例#25
0
 def run(self):
     prefs = FreeCAD.ParamGet(
         "User parameter:BaseApp/Preferences/Mod/Fem/General")
     if not prefs.GetBool("KeepResultsOnReRun", False):
         self.purge_results()
     self.load_results()
示例#26
0
def run():
    fna = '/home/thomas/Bilder/122_PANA/P1220703.JPG'
    fna = FreeCAD.ParamGet('User parameter:Plugins/reconstruction').GetString(
        "Document", fna)
    genpics(None, fna)
    dialog(fna)
示例#27
0
def onSave():
    """Save current workbench toolbars position."""

    tb = mw.findChildren(QtGui.QToolBar)
    active = Gui.activeWorkbench().__class__.__name__
    p = App.ParamGet("User parameter:Tux/PersistentToolbars/User")
    group = p.GetGroup(active)

    top = []
    left = []
    right = []
    bottom = []

    for i in tb:
        if i.objectName() and i.isVisible() and not i.isFloating():

            area = mw.toolBarArea(i)

            x = i.geometry().x()
            y = i.geometry().y()
            b = mw.toolBarBreak(i)
            n = i.objectName()

            if area == QtCore.Qt.ToolBarArea.TopToolBarArea:
                top.append([x, y, b, n])
            elif area == QtCore.Qt.ToolBarArea.LeftToolBarArea:
                left.append([x, y, b, n])
            elif area == QtCore.Qt.ToolBarArea.RightToolBarArea:
                right.append([-x, y, b, n])
            elif area == QtCore.Qt.ToolBarArea.BottomToolBarArea:
                bottom.append([x, -y, b, n])
            else:
                pass
        else:
            pass

    top = sorted(top, key=operator.itemgetter(1, 0))
    left = sorted(left, key=operator.itemgetter(0, 1))
    right = sorted(right, key=operator.itemgetter(0, 1))
    bottom = sorted(bottom, key=operator.itemgetter(1, 0))

    topSave = []
    leftSave = []
    rightSave = []
    bottomSave = []

    for i in top:
        if i[2] is True:
            topSave.append("Break")
            topSave.append(i[3])
        else:
            topSave.append(i[3])

    for i in left:
        if i[2] is True:
            leftSave.append("Break")
            leftSave.append(i[3])
        else:
            leftSave.append(i[3])

    for i in right:
        if i[2] is True:
            rightSave.append("Break")
            rightSave.append(i[3])
        else:
            rightSave.append(i[3])

    for i in bottom:
        if i[2] is True:
            bottomSave.append("Break")
            bottomSave.append(i[3])
        else:
            bottomSave.append(i[3])

    group.SetBool("Saved", 1)
    group.SetString("Top", ",".join(topSave))
    group.SetString("Left", ",".join(leftSave))
    group.SetString("Right", ",".join(rightSave))
    group.SetString("Bottom", ",".join(bottomSave))
示例#28
0
def handle():

    "builds the HTML code of the start page"

    global iconbank, tempfolder

    # reuse stuff from previous runs to reduce temp dir clutter

    import Start
    if hasattr(Start, "iconbank"):
        iconbank = Start.iconbank
    if hasattr(Start, "tempfolder"):
        tempfolder = Start.tempfolder
    else:
        tempfolder = tempfile.mkdtemp(prefix="FreeCADStartThumbnails")

    # build the html page skeleton

    resources_dir = os.path.join(FreeCAD.getResourceDir(), "Mod", "Start",
                                 "StartPage")
    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start")
    template = p.GetString("Template", "")
    if template:
        html_filename = template
    else:
        html_filename = os.path.join(resources_dir, "StartPage.html")
    js_filename = os.path.join(resources_dir, "StartPage.js")
    css_filename = os.path.join(resources_dir, "StartPage.css")
    with open(html_filename, 'r') as f:
        HTML = f.read()
    with open(js_filename, 'r') as f:
        JS = f.read()
    with open(css_filename, 'r') as f:
        CSS = f.read()
    HTML = HTML.replace("JS", JS)
    HTML = HTML.replace("CSS", CSS)
    HTML = encode(HTML)

    # get the stylesheet if we are using one

    if FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Start").GetBool(
                "UseStyleSheet", False):
        qssfile = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/MainWindow").GetString(
                "StyleSheet", "")
        if qssfile:
            # Search for stylesheet in user, system and resources locations
            user = os.path.join(FreeCAD.getUserAppDataDir(), "Gui",
                                "Stylesheets")
            system = os.path.join(FreeCAD.getResourceDir(), "Gui",
                                  "Stylesheets")
            resources = ":/stylesheets"

            res = False
            if QtCore.QFile.exists(os.path.join(user, qssfile)):
                path = os.path.join(user, qssfile)
            elif QtCore.QFile.exists(os.path.join(system, qssfile)):
                path = os.path.join(system, qssfile)
            elif QtCore.QFile.exists(os.path.join(resources, qssfile)):
                res = True
                path = os.path.join(resources, qssfile)
            else:
                path = None

            if path:
                if res:
                    f = QtCore.QFile(path)
                    if f.open(QtCore.QIODevice.ReadOnly | QtCore.QFile.Text):
                        ALTCSS = encode(QtCore.QTextStream(f).readAll())
                        HTML = HTML.replace(
                            "<!--QSS-->",
                            "<style type=\"text/css\">" + ALTCSS + "</style>")
                else:
                    with open(path, 'r') as f:
                        ALTCSS = encode(f.read())
                        HTML = HTML.replace(
                            "<!--QSS-->",
                            "<style type=\"text/css\">" + ALTCSS + "</style>")

    # turn tips off if needed

    if not FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start"
                            ).GetBool("ShowTips", True):
        HTML = HTML.replace("display: block; /* footnote tips display */",
                            "display: none; /* footnote tips display */")

    # get FreeCAD version

    v = FreeCAD.Version()
    VERSIONSTRING = encode(TranslationTexts.T_VERSION + " " + v[0] + "." +
                           v[1] + " " + TranslationTexts.T_BUILD + " " + v[2])
    HTML = HTML.replace("VERSIONSTRING", VERSIONSTRING)

    # translate texts

    texts = [t for t in dir(TranslationTexts) if t.startswith("T_")]
    for text in texts:
        HTML = HTML.replace(text, encode(getattr(TranslationTexts, text)))

    # build a "create new" icon with the FreeCAD background color gradient

    if not "createimg" in iconbank:
        p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/View")
        c1 = gethexcolor(p.GetUnsigned("BackgroundColor2"))
        c2 = gethexcolor(p.GetUnsigned("BackgroundColor3"))
        gradient = QtGui.QLinearGradient(0, 0, 0, 128)
        gradient.setColorAt(0.0, QtGui.QColor(c1))
        gradient.setColorAt(1.0, QtGui.QColor(c2))
        i = QtGui.QImage(128, 128, QtGui.QImage.Format_RGB16)
        pa = QtGui.QPainter(i)
        pa.fillRect(i.rect(), gradient)
        pa.end()
        createimg = tempfile.mkstemp(dir=tempfolder, suffix='.png')[1]
        i.save(createimg)
        iconbank["createimg"] = createimg

    # build SECTION_RECENTFILES

    SECTION_RECENTFILES = encode("")
    rf = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/RecentFiles")
    rfcount = rf.GetInt("RecentFiles", 0)
    SECTION_RECENTFILES = encode("<h2>" + TranslationTexts.T_RECENTFILES +
                                 "</h2>")
    SECTION_RECENTFILES += "<ul>"
    SECTION_RECENTFILES += '<a href="LoadNew.py" title="' + encode(
        TranslationTexts.T_CREATENEW) + '">'
    SECTION_RECENTFILES += '<li class="icon">'
    if FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Start").GetBool(
                "NewFileGradient", False):
        SECTION_RECENTFILES += '<img src="file:///' + encode(
            iconbank["createimg"]) + '">'
    else:
        SECTION_RECENTFILES += '<img src="file:///' + os.path.join(
            resources_dir, "images/new_file_thumbnail.svg") + '">'
    SECTION_RECENTFILES += '<div class="caption">'
    SECTION_RECENTFILES += '<h4>' + encode(
        TranslationTexts.T_CREATENEW) + '</h4>'
    SECTION_RECENTFILES += '</div>'
    SECTION_RECENTFILES += '</li>'
    SECTION_RECENTFILES += '</a>'
    for i in range(rfcount):
        filename = rf.GetString("MRU%d" % (i))
        SECTION_RECENTFILES += encode(
            buildCard(filename, method="LoadMRU.py?MRU=", arg=str(i)))
    SECTION_RECENTFILES += '</ul>'
    HTML = HTML.replace("SECTION_RECENTFILES", SECTION_RECENTFILES)

    # build SECTION_EXAMPLES

    SECTION_EXAMPLES = encode("")
    if FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Start").GetBool(
                "ShowExamples", True):
        SECTION_EXAMPLES = encode("<h2>" + TranslationTexts.T_EXAMPLES +
                                  "</h2>")
        SECTION_EXAMPLES += "<ul>"
        examples_path = FreeCAD.getResourceDir() + "examples"
        if os.path.exists(examples_path):
            examples = os.listdir(examples_path)
            for basename in examples:
                filename = FreeCAD.getResourceDir(
                ) + "examples" + os.sep + basename
                SECTION_EXAMPLES += encode(
                    buildCard(filename, method="LoadExample.py?filename="))
        SECTION_EXAMPLES += "</ul>"
    HTML = HTML.replace("SECTION_EXAMPLES", SECTION_EXAMPLES)

    # build SECTION_CUSTOM

    SECTION_CUSTOM = encode("")
    cfolder = FreeCAD.ParamGet(
        "User parameter:BaseApp/Preferences/Mod/Start").GetString(
            "ShowCustomFolder", "")
    if cfolder:
        if not os.path.isdir(cfolder):
            cfolder = os.path.dirname(cfolder)
        SECTION_CUSTOM = encode("<h2>" +
                                os.path.basename(os.path.normpath(cfolder)) +
                                "</h2>")
        SECTION_CUSTOM += "<ul>"
        for basename in os.listdir(cfolder):
            filename = os.path.join(cfolder, basename)
            SECTION_CUSTOM += encode(
                buildCard(filename, method="LoadCustom.py?filename="))
        SECTION_CUSTOM += "</ul>"
        # hide the custom section tooltip if custom section is set (users know about it if they enabled it)
        HTML = HTML.replace("id=\"customtip\"",
                            "id=\"customtip\" style=\"display:none;\"")
    HTML = HTML.replace("SECTION_CUSTOM", SECTION_CUSTOM)

    # build IMAGE_SRC paths

    HTML = HTML.replace(
        "IMAGE_SRC_USERHUB",
        'file:///' + os.path.join(resources_dir, 'images/userhub.png'))
    HTML = HTML.replace(
        "IMAGE_SRC_POWERHUB",
        'file:///' + os.path.join(resources_dir, 'images/poweruserhub.png'))
    HTML = HTML.replace(
        "IMAGE_SRC_DEVHUB",
        'file:///' + os.path.join(resources_dir, 'images/developerhub.png'))
    HTML = HTML.replace(
        "IMAGE_SRC_MANUAL",
        'file:///' + os.path.join(resources_dir, 'images/manual.png'))
    HTML = HTML.replace(
        "IMAGE_SRC_SETTINGS",
        'file:///' + os.path.join(resources_dir, 'images/settings.png'))
    imagepath = 'file:///' + os.path.join(resources_dir,
                                          'images/installed.png')
    imagepath = imagepath.replace(
        '\\', '/'
    )  # replace Windows backslash with slash to make the path javascript compatible
    HTML = HTML.replace("IMAGE_SRC_INSTALLED", imagepath)

    # build UL_WORKBENCHES

    wblist = []
    UL_WORKBENCHES = '<ul class="workbenches">'
    FreeCAD.getResourceDir()
    for wb in sorted(FreeCADGui.listWorkbenches().keys()):
        if wb.endswith("Workbench"):
            wn = wb[:-9]
        else:
            wn = wb
        # fixes for non-standard names
        if wn == "flamingoTools":
            wn = "flamingo"
        elif wn == "Geodat":
            wn = "geodata"
        elif wn == "a2p":
            wn = "A2plus"
        elif wn == "ArchTexture":
            wn = "ArchTextures"
        elif wn == "CadQuery":
            wn = "cadquery_module"
        elif wn == "DefeaturingWB":
            wn = "Defeaturing"
        elif wn == "ksuWB":
            wn = "kicadStepUp"
        elif wn == "ManipulatorWB":
            wn = "Manipulator"
        elif wn == "PartOMagic":
            wn = "Part-o-magic"
        elif wn == "SM":
            wn = "sheetmetal"
        elif wn == "gear":
            wn = "FCGear"
        elif wn == "frame_":
            wn = "frame"
        elif wn == "None":
            continue
        wblist.append(wn.lower())
        if wb in iconbank:
            img = iconbank[wb]
        else:
            img = os.path.join(FreeCAD.getResourceDir(), "Mod", wn,
                               "Resources", "icons", wn + "Workbench.svg")
            if not os.path.exists(img):
                w = FreeCADGui.listWorkbenches()[wb]
                if hasattr(w, "Icon"):
                    xpm = w.Icon
                    if "XPM" in xpm:
                        xpm = xpm.replace(
                            "\n        ", "\n"
                        )  # some XPMs have some indent that QT doesn't like
                        r = [
                            s[:-1].strip('"') for s in re.findall(
                                "(?s)\{(.*?)\};", xpm)[0].split("\n")[1:]
                        ]
                        p = QtGui.QPixmap(r)
                        p = p.scaled(24, 24)
                        img = tempfile.mkstemp(dir=tempfolder,
                                               suffix='.png')[1]
                        p.save(img)
                    else:
                        img = xpm
                else:
                    img = os.path.join(resources_dir, "images/freecad.png")
            iconbank[wb] = img
        UL_WORKBENCHES += '<li>'
        UL_WORKBENCHES += '<img src="file:///' + iconbank[wb] + '">&nbsp;'
        UL_WORKBENCHES += '<a href="https://www.freecadweb.org/wiki/' + wn + '_Workbench">' + wn.replace(
            "ReverseEngineering", "ReverseEng") + '</a>'
        UL_WORKBENCHES += '</li>'
    UL_WORKBENCHES += '</ul>'
    HTML = HTML.replace("UL_WORKBENCHES", encode(UL_WORKBENCHES))

    # Detect additional addons that are not a workbench

    try:
        import dxfLibrary
    except:
        pass
    else:
        wblist.append("dxf-library")
    try:
        import RebarTools
    except:
        pass
    else:
        wblist.append("reinforcement")
    try:
        import CADExchangerIO
    except:
        pass
    else:
        wblist.append("cadexchanger")
    HTML = HTML.replace("var wblist = [];",
                        "var wblist = " + str(wblist) + ";")

    # set and replace colors and font settings

    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start")
    if p.GetString("BackgroundImage", ""):
        BACKGROUND = gethexcolor(p.GetUnsigned(
            "BackgroundColor1", 1331197183)) + " url(" + p.GetString(
                "BackgroundImage", "") + ")"
    else:
        BACKGROUND = gethexcolor(p.GetUnsigned("BackgroundColor1", 1331197183))
        # linear gradient not supported by QT "linear-gradient("+gethexcolor(p.GetUnsigned("BackgroundColor1",1331197183))+","+gethexcolor(p.GetUnsigned("BackgroundColor2",2141107711))+")"
    LINKCOLOR = gethexcolor(p.GetUnsigned("LinkColor", 65535))
    BASECOLOR = gethexcolor(p.GetUnsigned("PageColor", 4294967295))
    BOXCOLOR = gethexcolor(p.GetUnsigned("BoxColor", 3722305023))
    TEXTCOLOR = gethexcolor(p.GetUnsigned("PageTextColor", 255))
    BGTCOLOR = gethexcolor(p.GetUnsigned("BackgroundTextColor", 4294703103))
    SHADOW = "#888888"
    if QtGui.QColor(BASECOLOR).valueF(
    ) < 0.5:  # dark page - we need to make darker shadows
        SHADOW = "#000000"
    FONTFAMILY = encode(p.GetString("FontFamily", "Arial,Helvetica,sans"))
    if not FONTFAMILY:
        FONTFAMILY = "Arial,Helvetica,sans"
    FONTSIZE = p.GetInt("FontSize", 13)
    HTML = HTML.replace("BASECOLOR", BASECOLOR)
    HTML = HTML.replace("BOXCOLOR", BOXCOLOR)
    HTML = HTML.replace("LINKCOLOR", LINKCOLOR)
    HTML = HTML.replace("TEXTCOLOR", TEXTCOLOR)
    HTML = HTML.replace("BGTCOLOR", BGTCOLOR)
    HTML = HTML.replace("BACKGROUND", BACKGROUND)
    HTML = HTML.replace("FONTFAMILY", FONTFAMILY)
    HTML = HTML.replace("FONTSIZE", str(FONTSIZE) + "px")

    # enable web access if permitted

    if FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Start").GetBool(
                "AllowDownload", False):
        HTML = HTML.replace("var allowDownloads = 0;",
                            "var allowDownloads = 1;")

    # enable or disable forum

    if FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Start").GetBool(
                "ShowForum", False):
        HTML = HTML.replace("var showForum = 0;", "var showForum = 1;")
        HTML = HTML.replace("display: none; /* forum display */",
                            "display: block; /* forum display */")

    # enable or disable notepad

    if FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Start").GetBool(
                "ShowNotes", False):
        HTML = HTML.replace("display: none; /* notes display */",
                            "display: block; /* notes display */")
        HTML = HTML.replace("width: 100%; /* thumbs display */",
                            "width: 70%; /* thumbs display */")

    # store variables for further use

    Start.iconbank = iconbank
    Start.tempfolder = tempfolder

    # make sure we are always returning unicode
    # HTML should be a str-object and therefore:
    # - for py2 HTML is a bytes object and has to be decoded to unicode
    # - for py3 HTML is already a unicode object and the next 2 lines can be removed
    #    once py2-support is removed.

    if isinstance(HTML, bytes):
        HTML = HTML.decode("utf8")

    return HTML
示例#29
0
def onRestore(active):
    """Restore current workbench toolbars position."""

    toolbars = {}
    tb = mw.findChildren(QtGui.QToolBar)
    pUser = App.ParamGet("User parameter:Tux/PersistentToolbars/User")
    pSystem = App.ParamGet("User parameter:Tux/PersistentToolbars/System")

    for i in tb:

        isConnected(i)

        if i.objectName() and not i.isFloating():
            toolbars[i.objectName()] = i
        else:
            pass

    if pUser.GetGroup(active).GetBool("Saved"):
        group = pUser.GetGroup(active)
    elif pSystem.GetGroup(active).GetBool("Saved"):
        group = pSystem.GetGroup(active)
    else:
        group = None

    if group:
        topRestore = group.GetString("Top").split(",")
        leftRestore = group.GetString("Left").split(",")
        rightRestore = group.GetString("Right").split(",")
        bottomRestore = group.GetString("Bottom").split(",")

        # Reduce flickering.
        for i in toolbars:
            if (i not in topRestore and i not in leftRestore
                    and i not in rightRestore and i not in bottomRestore):

                area = mw.toolBarArea(toolbars[i])

                if area == QtCore.Qt.ToolBarArea.LeftToolBarArea:
                    leftRestore.append(i)
                elif area == QtCore.Qt.ToolBarArea.RightToolBarArea:
                    rightRestore.append(i)
                elif area == QtCore.Qt.ToolBarArea.BottomToolBarArea:
                    bottomRestore.append(i)
                else:
                    topRestore.append(i)
            else:
                pass

        for i in topRestore:
            if i == "Break":
                mw.addToolBarBreak(QtCore.Qt.TopToolBarArea)
            elif i in toolbars:
                mw.addToolBar(QtCore.Qt.TopToolBarArea, toolbars[i])
            else:
                pass

        for i in leftRestore:
            if i == "Break":
                mw.addToolBarBreak(QtCore.Qt.LeftToolBarArea)
            elif i in toolbars:
                mw.addToolBar(QtCore.Qt.LeftToolBarArea, toolbars[i])
            else:
                pass

        for i in rightRestore:
            if i == "Break":
                mw.addToolBarBreak(QtCore.Qt.RightToolBarArea)
            elif i in toolbars:
                mw.addToolBar(QtCore.Qt.RightToolBarArea, toolbars[i])
            else:
                pass

        for i in bottomRestore:
            if i == "Break":
                mw.addToolBarBreak(QtCore.Qt.BottomToolBarArea)
            elif i in toolbars:
                mw.addToolBar(QtCore.Qt.BottomToolBarArea, toolbars[i])
            else:
                pass
    else:
        pass
示例#30
0
def setFoamDir(installation_path):
    prefs = getPreferencesLocation()
    # Set OpenFOAM install path in parameters
    FreeCAD.ParamGet(prefs).SetString("InstallationPath", installation_path)