示例#1
1
 def Activated(self):
     sel = FreeCADGui.Selection.getSelection()
     FreeCAD.ActiveDocument.openTransaction("Section Plane")
     obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Section")
     _SectionPlane(obj)
     _ViewProviderSectionPlane(obj.ViewObject)
     FreeCAD.ActiveDocument.commitTransaction()
     g = []
     for o in sel:
         if o.isDerivedFrom("Part::Feature"):
             g.append(o)
     obj.Objects = g
     page = FreeCAD.ActiveDocument.addObject("Drawing::FeaturePage", "Page")
     template = Draft.getParam("template")
     if not template:
         template = FreeCAD.getResourceDir() + "Mod/Drawing/Templates/A3_Landscape.svg"
     page.ViewObject.HintOffsetX = 200
     page.ViewObject.HintOffsetY = 100
     page.ViewObject.HintScale = 20
     page.Template = template
     view = FreeCAD.ActiveDocument.addObject("Drawing::FeatureViewPython", "View")
     page.addObject(view)
     _ArchDrawingView(view)
     view.Source = obj
     FreeCAD.ActiveDocument.recompute()
示例#2
0
def makeCSteelTest():
    xmlFiles = [
        FreeCAD.getResourceDir() + "/Xmls/it-Panel_1.xml",
        FreeCAD.getResourceDir() + "/Xmls/it-Floor_1.xml",
        FreeCAD.getResourceDir() + "/Xmls/it-Truss.1.xml"
    ]
    for xmlFile in xmlFiles:
        _mackeCSteelByXmlFile(xmlFile)
示例#3
0
    def import_materials(self):
        self.materials = {}
        self.pathList = []
        self.form.cb_materials.clear()
        self.fem_preferences = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/Fem")
        use_built_in_materials = self.fem_preferences.GetBool(
            "UseBuiltInMaterials", True)
        if use_built_in_materials:
            system_mat_dir = FreeCAD.getResourceDir(
            ) + "/Mod/Material/StandardMaterial"
            self.add_mat_dir(system_mat_dir, ":/icons/freecad.svg")

        use_mat_from_config_dir = self.fem_preferences.GetBool(
            "UseMaterialsFromConfigDir", True)
        if use_mat_from_config_dir:
            user_mat_dirname = FreeCAD.getUserAppDataDir() + "Materials"
            self.add_mat_dir(user_mat_dirname,
                             ":/icons/preferences-general.svg")

        use_mat_from_custom_dir = self.fem_preferences.GetBool(
            "UseMaterialsFromCustomDir", True)
        if use_mat_from_custom_dir:
            custom_mat_dir = self.fem_preferences.GetString(
                "CustomMaterialsDir", "")
            self.add_mat_dir(custom_mat_dir, ":/icons/user.svg")
 def Activated(self):
     sel = FreeCADGui.Selection.getSelection()
     FreeCAD.ActiveDocument.openTransaction("Section Plane")
     obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",
                                            "Section")
     _SectionPlane(obj)
     _ViewProviderSectionPlane(obj.ViewObject)
     FreeCAD.ActiveDocument.commitTransaction()
     g = []
     for o in sel:
         if o.isDerivedFrom("Part::Feature"):
             g.append(o)
     obj.Objects = g
     page = FreeCAD.ActiveDocument.addObject("Drawing::FeaturePage", "Page")
     template = FreeCAD.getResourceDir(
     ) + 'Mod/Drawing/Templates/A3_Landscape.svg'
     page.ViewObject.HintOffsetX = 200
     page.ViewObject.HintOffsetY = 100
     page.ViewObject.HintScale = 20
     page.Template = template
     view = FreeCAD.ActiveDocument.addObject("Drawing::FeatureViewPython",
                                             "View")
     page.addObject(view)
     _ArchDrawingView(view)
     view.Source = obj
     FreeCAD.ActiveDocument.recompute()
    def test_material_card_quantities(
        self
    ):
        # test the value and unit of known quantity parameter
        # from solid build in material cards
        # keep in mind only if FreeCAD is installed all materials are copied
        # TODO Fluid materials (are they installed?)

        # get build in materials
        builtin_solid_mat_dir = join(
            FreeCAD.getResourceDir(),
            "Mod",
            "Material",
            "StandardMaterial"
        )
        fcc_print('{}'.format(builtin_solid_mat_dir))
        from materialtools.cardutils import add_cards_from_a_dir as addmats
        materials, cards, icons = addmats({}, {}, {}, builtin_solid_mat_dir, '')

        # get known material quantity parameter
        from materialtools.cardutils import get_known_material_quantity_parameter as knownquant
        known_quantities = knownquant()

        # check param, value pairs
        from materialtools.cardutils import check_value_unit as checkvalueunit
        for mat in materials:
            fcc_print('{}'.format(mat))
            for param, value in materials[mat].items():
                if param in known_quantities:
                    # fcc_print('    {} --> {}'.format(param, value))
                    self.assertTrue(
                        checkvalueunit(param, value),
                        'Unit of quantity {} from material parameter {} is wrong.'
                        .format(value, param)
                    )
示例#6
0
    def test_draft_to_drawing(self):
        """Create a solid, and then a projected view in a Drawing page."""
        operation = "Draft Drawing"
        _msg("  Test '{}'".format(operation))
        _wrn("  The Drawing Workbench is obsolete since 0.17,")
        _wrn("  consider using the TechDraw Workbench instead")
        prism = App.ActiveDocument.addObject("Part::Prism")
        prism.Polygon = 5
        # Rotate the prism 45 degrees around the Y axis
        prism.Placement.Rotation.Axis = Vector(0, 1, 0)
        prism.Placement.Rotation.Angle = 45 * (3.14159/180)
        _msg("  Prism")
        _msg("  n_sides={}".format(prism.Polygon))
        _msg("  placement={}".format(prism.Placement))

        svg_template = 'Mod/Drawing/Templates/A3_Landscape.svg'
        template = Draft.getParam("template",
                                  App.getResourceDir() + svg_template)
        page = App.ActiveDocument.addObject('Drawing::FeaturePage')
        page.Template = template
        _msg("  Drawing view")
        _msg("  page={}".format(page.TypeId))
        _msg("  template={}".format(page.Template))
        obj = Draft.makeDrawingView(prism, page, otherProjection=None)
        self.assertTrue(obj, "'{}' failed".format(operation))
示例#7
0
 def getMaterialResources(self):
     self.fem_prefs = FreeCAD.ParamGet(
         "User parameter:BaseApp/Preferences/Mod/Material/Resources")
     use_built_in_materials = self.fem_prefs.GetBool(
         "UseBuiltInMaterials", True)
     use_mat_from_config_dir = self.fem_prefs.GetBool(
         "UseMaterialsFromConfigDir", True)
     use_mat_from_custom_dir = self.fem_prefs.GetBool(
         "UseMaterialsFromCustomDir", True)
     if use_mat_from_custom_dir:
         custom_mat_dir = self.fem_prefs.GetString("CustomMaterialsDir", "")
     # later found cards with same name will override cards
     # FreeCAD returns paths with / at the end, thus not os.sep is needed on first +
     self.resources = []
     if use_built_in_materials:
         self.resources.append(FreeCAD.getResourceDir() + "Mod" + os.sep +
                               "Material" + os.sep + "StandardMaterial")
     if use_mat_from_config_dir:
         self.resources.append(
             FreeCAD.ConfigGet("UserAppData") + "Material")
     if use_mat_from_custom_dir:
         custom_mat_dir = self.fem_prefs.GetString("CustomMaterialsDir", "")
         if os.path.exists(custom_mat_dir):
             self.resources.append(custom_mat_dir)
     self.outputResources()
示例#8
0
    def test_material_card_quantities(
        self
    ):
        # test the value and unit of known quantity parameter
        # from solid build in material cards
        # keep in mind only if FreeCAD is installed all materials are copied
        # TODO Fluid materials (are they installed?)

        # get build in materials
        builtin_solid_mat_dir = join(
            FreeCAD.getResourceDir(),
            "Mod",
            "Material",
            "StandardMaterial"
        )
        fcc_print("{}".format(builtin_solid_mat_dir))
        from materialtools.cardutils import add_cards_from_a_dir as addmats
        materials, cards, icons = addmats({}, {}, {}, builtin_solid_mat_dir, "")

        # get known material quantity parameter
        from materialtools.cardutils import get_known_material_quantity_parameter as knownquant
        known_quantities = knownquant()

        # check param, value pairs
        from materialtools.cardutils import check_value_unit as checkvalueunit
        for mat in materials:
            fcc_print("{}".format(mat))
            for param, value in materials[mat].items():
                if param in known_quantities:
                    # fcc_print("    {} --> {}".format(param, value))
                    self.assertTrue(
                        checkvalueunit(param, value),
                        "Unit of quantity {} from material parameter {} is wrong."
                        .format(value, param)
                    )
示例#9
0
 def __init__(self):
     self.__class__.Icon = FreeCAD.getResourceDir() + "Mod/OpenSCAD/Resources/icons/OpenSCADWorkbench.svg"
     self.__class__.MenuText = "OpenSCAD"
     self.__class__.ToolTip = (
         "OpenSCAD is an application for creating solid 3D CAD.\n"
         "FreeCAD utizes OpenSCAD's capability as a script-only based modeller that uses its own description language\n"
         "Note: the Mesh workbench heavily uses the boolean operations of this workbench because they are quite robust"
     )
示例#10
0
文件: InitGui.py 项目: WuYanJ/FreeCAD
    def __init__(self):
        def QT_TRANSLATE_NOOP(context, text):
            return text

        __dirname__ = os.path.join(FreeCAD.getResourceDir(), "Mod", "Draft")
        _tooltip = "The Draft workbench is used for 2D drafting on a grid"
        self.__class__.Icon = os.path.join(__dirname__, "Resources", "icons",
                                           "DraftWorkbench.svg")
        self.__class__.MenuText = QT_TRANSLATE_NOOP("draft", "Draft")
        self.__class__.ToolTip = QT_TRANSLATE_NOOP("draft", _tooltip)
示例#11
0
    def __init__(self):
        def QT_TRANSLATE_NOOP(context, text):
            return text

        __dirname__ = os.path.join(FreeCAD.getResourceDir(), "Mod", "Arch")
        _tooltip = ("The Arch workbench is used to model "
                    "architectural components, and entire buildings")
        self.__class__.Icon = os.path.join(__dirname__, "Resources", "icons",
                                           "ArchWorkbench.svg")
        self.__class__.MenuText = QT_TRANSLATE_NOOP("Arch", "Arch")
        self.__class__.ToolTip = QT_TRANSLATE_NOOP("Arch", _tooltip)
示例#12
0
 def createDefaultPage(self):
     """Create a default Drawing Workbench page."""
     _t = App.getResourceDir() + 'Mod/Drawing/Templates/A3_Landscape.svg'
     template = utils.getParam("template", _t)
     page = self.doc.addObject('Drawing::FeaturePage', 'Page')
     page.ViewObject.HintOffsetX = 200
     page.ViewObject.HintOffsetY = 100
     page.ViewObject.HintScale = 2
     page.Template = template
     self.doc.recompute()
     return page
示例#13
0
 def fillMaterialCombo(self):
     import glob
     import os
     mat_file_extension = ".FCMat"
     dirname =  FreeCAD.getResourceDir()+"/Mod/Material/StandardMaterial"
     self.pathList = glob.glob(dirname + '/*' + mat_file_extension)
     self.form.comboBox_MaterialsInDir.clear()
     l = len(mat_file_extension)
     for i in self.pathList:
         material_name = os.path.basename(i[:-l])
         self.form.comboBox_MaterialsInDir.addItem(material_name)
示例#14
0
def get_material_resources(category='Solid'):

    resources = {}  # { resource_path: icon_path, ... }

    # TODO: move GUI preferences from FEM to a new side tab Material
    # https://forum.freecadweb.org/viewtopic.php?f=10&t=35515
    mat_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Material/Resources")
    use_built_in_materials = mat_prefs.GetBool("UseBuiltInMaterials", True)
    use_mat_from_config_dir = mat_prefs.GetBool("UseMaterialsFromConfigDir", True)
    use_mat_from_custom_dir = mat_prefs.GetBool("UseMaterialsFromCustomDir", True)

    if use_built_in_materials:
        if category == 'Fluid':
            builtin_mat_dir = join(
                FreeCAD.getResourceDir(), "Mod", "Material", "FluidMaterial"
            )

        else:
            builtin_mat_dir = join(
                FreeCAD.getResourceDir(), "Mod", "Material", "StandardMaterial"
            )
        resources[builtin_mat_dir] = ":/icons/freecad.svg"

    if use_mat_from_config_dir:
        config_mat_dir = join(
            FreeCAD.ConfigGet("UserAppData"), "Material"
        )
        resources[config_mat_dir] = ":/icons/preferences-general.svg"

    if use_mat_from_custom_dir:
        custom_mat_dir = mat_prefs.GetString("CustomMaterialsDir", "")
        if os.path.exists(custom_mat_dir):
            resources[custom_mat_dir] = ":/icons/user.svg"
        # fail silently
        # else:
        #     FreeCAD.Console.PrintError(
        #         'Custom material directory set by user: {} does not exist.\n'
        #         .format(custom_mat_dir)
        #     )

    return resources
def getFont(props):
    fontdir = FreeCAD.getResourceDir(
    ) + "Mod/TechDraw/Resources/fonts/"  #"/usr/share/fonts/truetype/dejavu/"
    font = "osifont-lgpl3fe.ttf"  # "DejaVuSans-Bold.ttf"
    if not props.ttfFontPath is None:
        if exists(props.ttfFontPath):
            font = basename(props.ttfFontPath)
            fontdir = join(dirname(props.ttfFontPath),
                           '')  # Part.makeWireString wants trailing slash
        else:
            print("No Font found at path in TrayProps: " + props.ttfFontPath)
    return fontdir, font
示例#16
0
    def test_export_airfoildat(self):
        """Create some figures and export them to an airfoil DAT file."""
        operation = "importAirfoilDAT.export"
        _msg("  Test '{}'".format(operation))

        file = 'Mod/Draft/drafttest/out_test.dat'
        out_file = os.path.join(App.getResourceDir(), file)
        _msg("  file={}".format(out_file))
        _msg("  exists={}".format(os.path.exists(out_file)))

        Draft.export_importAirfoilDAT = _fake_function
        obj = Draft.export_importAirfoilDAT(out_file)
        self.assertTrue(obj, "'{}' failed".format(operation))
示例#17
0
    def test_export_svg(self):
        """Create some figures and export them to an SVG file."""
        operation = "importSVG.export"
        _msg("  Test '{}'".format(operation))

        file = 'Mod/Draft/drafttest/out_test.svg'
        out_file = os.path.join(App.getResourceDir(), file)
        _msg("  file={}".format(out_file))
        _msg("  exists={}".format(os.path.exists(out_file)))

        Draft.export_svg = aux.fake_function
        obj = Draft.export_svg(out_file)
        self.assertTrue(obj, "'{}' failed".format(operation))
示例#18
0
    def test_read_svg(self):
        """Read an SVG file and import its elements as Draft objects."""
        operation = "importSVG.import"
        _msg("  Test '{}'".format(operation))
        _msg("  This test requires an SVG file to read.")

        file = 'Mod/Draft/drafttest/test.svg'
        in_file = os.path.join(App.getResourceDir(), file)
        _msg("  file={}".format(in_file))
        _msg("  exists={}".format(os.path.exists(in_file)))

        Draft.import_svg = aux.fake_function
        obj = Draft.import_svg(in_file)
        self.assertTrue(obj, "'{}' failed".format(operation))
示例#19
0
    def test_read_airfoildat(self):
        """Read an airfoil DAT file and import its elements as objects."""
        operation = "importAirfoilDAT.import"
        _msg("  Test '{}'".format(operation))
        _msg("  This test requires a DAT file with airfoil data to read.")

        file = 'Mod/Draft/drafttest/test.dat'
        in_file = os.path.join(App.getResourceDir(), file)
        _msg("  file={}".format(in_file))
        _msg("  exists={}".format(os.path.exists(in_file)))

        Draft.import_AirfoilDAT = _fake_function
        obj = Draft.import_AirfoilDAT(in_file)
        self.assertTrue(obj, "'{}' failed".format(operation))
示例#20
0
 def fillMaterialCombo(self):
     "fills the combo with the existing FCMat cards"
     # look for cards in both resources dir and user folder. 
     # User cards with same name will override system cards
     paths = [FreeCAD.getResourceDir() + os.sep + "Mod" + os.sep + "Material" + os.sep + "StandardMaterial"]
     paths.append(FreeCAD.ConfigGet("UserAppData"))
     self.cards = {}
     for p in paths:
         for f in os.listdir(p):
             b,e = os.path.splitext(f)
             if e.upper() == ".FCMAT":
                 self.cards[b] = p + os.sep + f
     if self.cards:
         for k in sorted(self.cards.keys()):
             self.form.comboBox_MaterialsInDir.addItem(k)
示例#21
0
class SurfaceWorkbench(Gui.Workbench):
    """Surface workbench object."""

    Icon = os.path.join(App.getResourceDir(), "Mod", "Surface", "Resources",
                        "icons", "Surface_Workbench.svg")
    MenuText = "Surface"
    ToolTip = "Surface workbench: Create and edit complex surfaces"

    def Initialize(self):
        """Initialize the module."""
        import Surface
        import SurfaceGui

    def GetClassName(self):
        return "SurfaceGui::Workbench"
    def import_fluid_materials(self):
        # use_built_in_materials = self.fem_prefs.GetBool("UseBuiltInMaterials", True)
        # if use_built_in_materials:
        system_mat_dir = FreeCAD.getResourceDir() + "/Mod/Material/FluidMaterial"
        self.add_cards_from_a_dir(system_mat_dir, ":/icons/freecad.svg")

        use_mat_from_config_dir = self.fem_prefs.GetBool("UseMaterialsFromConfigDir", True)
        if use_mat_from_config_dir:
            user_mat_dirname = FreeCAD.getUserAppDataDir() + "FluidMaterial"
            self.add_cards_from_a_dir(user_mat_dirname, ":/icons/preferences-general.svg")

        use_mat_from_custom_dir = self.fem_prefs.GetBool("UseMaterialsFromCustomDir", True)
        if use_mat_from_custom_dir:
            custom_mat_dir = self.fem_prefs.GetString("CustomMaterialsDir", "")
            self.add_cards_from_a_dir(custom_mat_dir, ":/icons/user.svg")
示例#23
0
 def fillMaterialCombo(self):
     "fills the combo with the existing FCMat cards"
     # look for cards in both resources dir and a Materials sub-folder in the user folder.
     # User cards with same name will override system cards
     paths = [FreeCAD.getResourceDir() + os.sep + "Mod" + os.sep + "Material" + os.sep + "StandardMaterial"]
     paths.append(FreeCAD.ConfigGet("UserAppData") + os.sep + "Materials")
     self.cards = {}
     for p in paths:
         for f in os.listdir(p):
             b,e = os.path.splitext(f)
             if e.upper() == ".FCMAT":
                 self.cards[b] = p + os.sep + f
     if self.cards:
         for k in sorted(self.cards.keys()):
             self.form.comboBox_MaterialsInDir.addItem(k)
示例#24
0
    def import_fluid_materials(self):
        #use_built_in_materials = self.fem_prefs.GetBool("UseBuiltInMaterials", True)
        #if use_built_in_materials:
        system_mat_dir = FreeCAD.getResourceDir() + "/Mod/Material/FluidMaterial"
        self.add_mat_dir(system_mat_dir, ":/icons/freecad.svg")

        use_mat_from_config_dir = self.fem_prefs.GetBool("UseMaterialsFromConfigDir", True)
        if use_mat_from_config_dir:
            user_mat_dirname = FreeCAD.getUserAppDataDir() + "FluidMaterial"
            self.add_mat_dir(user_mat_dirname, ":/icons/preferences-general.svg")

        use_mat_from_custom_dir = self.fem_prefs.GetBool("UseMaterialsFromCustomDir", True)
        if use_mat_from_custom_dir:
            custom_mat_dir = self.fem_prefs.GetString("CustomMaterialsDir", "")
            self.add_mat_dir(custom_mat_dir, ":/icons/user.svg")
示例#25
0
 def fillMaterialCombo(self):
     import glob,os
     matmap = self.obj.Material
     dirname =  FreeCAD.getResourceDir()+"/Mod/Material/StandardMaterial"
     self.pathList = glob.glob(dirname + '/*.FCMat')
     self.form.comboBox_MaterialsInDir.clear()
     '''if(matmap.has_key('General_name')):
         self.form.comboBox_MaterialsInDir.addItem(matmap['General_name'])
     else:
         self.form.comboBox_MaterialsInDir.addItem('-> choose Material')
     '''    
     # workaraound: since material data is not loaded into spinBoxes the user has  
     # to choose the material every time the MechanincalMaterialWidget is opened
     self.form.comboBox_MaterialsInDir.addItem('-> choose Material')  
     for i in self.pathList:
         self.form.comboBox_MaterialsInDir.addItem(os.path.basename(i) )
 def fillMaterialCombo(self):
     import glob, os
     matmap = self.obj.Material
     dirname = FreeCAD.getResourceDir() + "/Mod/Material/StandardMaterial"
     self.pathList = glob.glob(dirname + '/*.FCMat')
     self.form.comboBox_MaterialsInDir.clear()
     '''if(matmap.has_key('General_name')):
         self.form.comboBox_MaterialsInDir.addItem(matmap['General_name'])
     else:
         self.form.comboBox_MaterialsInDir.addItem('-> choose Material')
     '''
     # workaraound: since material data is not loaded into spinBoxes the user has
     # to choose the material every time the MechanincalMaterialWidget is opened
     self.form.comboBox_MaterialsInDir.addItem('-> choose Material')
     for i in self.pathList:
         self.form.comboBox_MaterialsInDir.addItem(os.path.basename(i))
示例#27
0
def load_svg_patterns():
    """Load the default Draft SVG patterns and user defined patterns.

    The SVG patterns are added as a dictionary to the `App.svgpatterns`
    attribute.
    """
    import importSVG
    App.svgpatterns = {}

    # Get default patterns in the resource file
    patfiles = QtCore.QDir(":/patterns").entryList()
    for fn in patfiles:
        file = ":/patterns/" + str(fn)
        f = QtCore.QFile(file)
        f.open(QtCore.QIODevice.ReadOnly)
        p = importSVG.getContents(str(f.readAll()), 'pattern', True)
        if p:
            for k in p:
                p[k] = [p[k], file]
            App.svgpatterns.update(p)

    # Get patterns in a user defined file
    altpat = getParam("patternFile", "")
    if os.path.isdir(altpat):
        for f in os.listdir(altpat):
            if f[-4:].upper() == ".SVG":
                file = os.path.join(altpat, f)
                p = importSVG.getContents(file, 'pattern')
                if p:
                    for k in p:
                        p[k] = [p[k], file]
                    App.svgpatterns.update(p)

    # Get TechDraw patterns
    altpat = os.path.join(App.getResourceDir(), "Mod", "TechDraw", "Patterns")
    if os.path.isdir(altpat):
        for f in os.listdir(altpat):
            if f[-4:].upper() == ".SVG":
                file = os.path.join(altpat, f)
                p = importSVG.getContents(file, 'pattern')
                if p:
                    for k in p:
                        p[k] = [p[k], file]
                else:
                    # some TD pattern files have no <pattern> definition but can still be used by Draft
                    p = {f[:-4]: ["<pattern></pattern>", file]}
                    App.svgpatterns.update(p)
示例#28
0
文件: ArchPanel.py 项目: OLGGL/Model
def makePanelView(panel,page=None,name="PanelView"):
    """makePanelView(panel,[page]) : Creates a Drawing view of the given panel
    in the given or active Page object (a new page will be created if none exists)."""
    if not page:
        for o in FreeCAD.ActiveDocument.Objects:
            if o.isDerivedFrom("Drawing::FeaturePage"):
                page = o
                break
        if not page:
            page = FreeCAD.ActiveDocument.addObject("Drawing::FeaturePage",translate("Arch","Page"))
            page.Template = Draft.getParam("template",FreeCAD.getResourceDir()+'Mod/Drawing/Templates/A3_Landscape.svg')
    view = FreeCAD.ActiveDocument.addObject("Drawing::FeatureViewPython",name)
    page.addObject(view)
    _PanelView(view)
    view.Source = panel
    view.Label = translate("Arch","View of")+" "+panel.Name
    return view
示例#29
0
 def updateCards(self):
     "updates the contents of the materials combo with existing material cards"
     # look for cards in both resources dir and user folder. 
     # User cards with same name will override system cards
     paths = [FreeCAD.getResourceDir() + os.sep + "Mod" + os.sep + "Material" + os.sep + "StandardMaterial"]
     paths.append(FreeCAD.ConfigGet("UserAppData"))
     self.cards = {}
     for p in paths:
         for f in os.listdir(p):
             b,e = os.path.splitext(f)
             if e.upper() == ".FCMAT":
                 self.cards[b] = p + os.sep + f
     if self.cards:
         self.ComboMaterial.clear()
         self.ComboMaterial.addItem("") # add a blank item first
         for k,i in self.cards.iteritems():
             self.ComboMaterial.addItem(k)
示例#30
0
def makePanelView(panel,page=None,name="PanelView"):
    """makePanelView(panel,[page]) : Creates a Drawing view of the given panel
    in the given or active Page object (a new page will be created if none exists)."""
    if not page:
        for o in FreeCAD.ActiveDocument.Objects:
            if o.isDerivedFrom("Drawing::FeaturePage"):
                page = o
                break
        if not page:
            page = FreeCAD.ActiveDocument.addObject("Drawing::FeaturePage",translate("Arch","Page"))
            page.Template = Draft.getParam("template",FreeCAD.getResourceDir()+'Mod/Drawing/Templates/A3_Landscape.svg')
    view = FreeCAD.ActiveDocument.addObject("Drawing::FeatureViewPython",name)
    page.addObject(view)
    _PanelView(view)
    view.Source = panel
    view.Label = translate("Arch","View of")+" "+panel.Name
    return view
示例#31
0
def makeSectionView(section,name="View"):
    """makeSectionView(section) : Creates a Drawing view of the given Section Plane
    in the active Page object (a new page will be created if none exists"""
    page = None
    for o in FreeCAD.ActiveDocument.Objects:
        if o.isDerivedFrom("Drawing::FeaturePage"):
            page = o
            break
    if not page:
        page = FreeCAD.ActiveDocument.addObject("Drawing::FeaturePage",translate("Arch","Page"))
        page.Template = Draft.getParam("template",FreeCAD.getResourceDir()+'Mod/Drawing/Templates/A3_Landscape.svg')

    view = FreeCAD.ActiveDocument.addObject("Drawing::FeatureViewPython",name)
    page.addObject(view)
    _ArchDrawingView(view)
    view.Source = section
    view.Label = translate("Arch","View of")+" "+section.Name
    return view
示例#32
0
def makeSectionView(section,name="View"):
    """makeSectionView(section) : Creates a Drawing view of the given Section Plane
    in the active Page object (a new page will be created if none exists"""
    page = None
    for o in FreeCAD.ActiveDocument.Objects:
        if o.isDerivedFrom("Drawing::FeaturePage"):
            page = o
            break
    if not page:
        page = FreeCAD.ActiveDocument.addObject("Drawing::FeaturePage",translate("Arch","Page"))
        page.Template = Draft.getParam("template",FreeCAD.getResourceDir()+'Mod/Drawing/Templates/A3_Landscape.svg')
        
    view = FreeCAD.ActiveDocument.addObject("Drawing::FeatureViewPython",name)
    page.addObject(view)
    _ArchDrawingView(view)
    view.Source = section
    view.Label = translate("Arch","View of")+" "+section.Name
    return view
    def import_materials(self):
        self.materials = {}
        self.pathList = []
        self.form.cb_materials.clear()
        self.fem_preferences = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem")
        use_built_in_materials = self.fem_preferences.GetBool("UseBuiltInMaterials", True)
        if use_built_in_materials:
            system_mat_dir = FreeCAD.getResourceDir() + "/Mod/Material/StandardMaterial"
            self.add_mat_dir(system_mat_dir, ":/icons/freecad.svg")

        use_mat_from_config_dir = self.fem_preferences.GetBool("UseMaterialsFromConfigDir", True)
        if use_mat_from_config_dir:
            user_mat_dirname = FreeCAD.getUserAppDataDir() + "Materials"
            self.add_mat_dir(user_mat_dirname, ":/icons/preferences-general.svg")

        use_mat_from_custom_dir = self.fem_preferences.GetBool("UseMaterialsFromCustomDir", True)
        if use_mat_from_custom_dir:
            custom_mat_dir = self.fem_preferences.GetString("CustomMaterialsDir", "")
            self.add_mat_dir(custom_mat_dir, ":/icons/user.svg")
示例#34
0
 def getMaterialResources(self):
     self.fem_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Material/Resources")
     use_built_in_materials = self.fem_prefs.GetBool("UseBuiltInMaterials", True)
     use_mat_from_config_dir = self.fem_prefs.GetBool("UseMaterialsFromConfigDir", True)
     use_mat_from_custom_dir = self.fem_prefs.GetBool("UseMaterialsFromCustomDir", True)
     if use_mat_from_custom_dir:
         custom_mat_dir = self.fem_prefs.GetString("CustomMaterialsDir", "")
     # later found cards with same name will override cards
     # FreeCAD returns paths with / at the end, thus not os.sep is needed on first +
     self.resources = []
     if use_built_in_materials:
         self.resources.append(FreeCAD.getResourceDir() + "Mod" + os.sep + "Material" + os.sep + "StandardMaterial")
     if use_mat_from_config_dir:
         self.resources.append(FreeCAD.ConfigGet("UserAppData") + "Material")
     if use_mat_from_custom_dir:
         custom_mat_dir = self.fem_prefs.GetString("CustomMaterialsDir", "")
         if os.path.exists(custom_mat_dir):
             self.resources.append(custom_mat_dir)
     self.outputResources()
示例#35
0
 def updateCards(self):
     "updates the contents of the materials combo with existing material cards"
     # look for cards in both resources dir and a Materials sub-folder in the user folder.
     # User cards with same name will override system cards
     paths = [FreeCAD.getResourceDir() + os.sep + "Mod" + os.sep + "Material" + os.sep + "StandardMaterial"]
     ap = FreeCAD.ConfigGet("UserAppData") + os.sep + "Materials"
     if os.path.exists(ap):
         paths.append(ap)
     self.cards = {}
     for p in paths:
         for f in os.listdir(p):
             b,e = os.path.splitext(f)
             if e.upper() == ".FCMAT":
                 self.cards[b] = p + os.sep + f
     if self.cards:
         self.widget.ComboMaterial.clear()
         self.widget.ComboMaterial.addItem("") # add a blank item first
         for k,i in self.cards.items():
             self.widget.ComboMaterial.addItem(k)
示例#36
0
    def Initialize(self):
        def QT_TRANSLATE_NOOP(scope, text):
            return text

        import GDMLCommands
        commands = [
            'BoxCommand', 'ConeCommand', 'SphereCommand', 'TubeCommand'
        ]
        toolbarcommands = [
            'BoxCommand', 'ConeCommand', 'SphereCommand', 'TubeCommand'
        ]

        import PartGui
        parttoolbarcommands = ['Part_Cut','Part_Fuse','Part_Common',\
            'Part_Extrude',"Part_Revolve"]
        #import FreeCAD
        #param = FreeCAD.ParamGet(\
        #    "User parameter:BaseApp/Preferences/Mod/OpenSCAD")
        #openscadfilename = param.GetString('openscadexecutable')
        #if not openscadfilename:

        #    import OpenSCADUtils
        #    openscadfilename = OpenSCADUtils.searchforopenscadexe()
        #    if openscadfilename: #automatic search was succsessful
        #        FreeCAD.addImportType("OpenSCAD Format (*.scad)","importCSG")
        #        param.SetString('openscadexecutable',openscadfilename) #save the result
        #if openscadfilename:
        #     commands.extend(['OpenSCAD_AddOpenSCADElement',
        #         'OpenSCAD_MeshBoolean','OpenSCAD_Hull','OpenSCAD_Minkowski'])
        #     toolbarcommands.extend(['OpenSCAD_AddOpenSCADElement',
        #         'OpenSCAD_MeshBoolean','OpenSCAD_Hull','OpenSCAD_Minkowski'])
        # else:
        #     FreeCAD.Console.PrintWarning('OpenSCAD executable not found\n')

        self.appendToolbar(QT_TRANSLATE_NOOP('Workbench', 'GDMLTools'),
                           toolbarcommands)
        self.appendMenu('GDML', commands)
        self.appendToolbar(QT_TRANSLATE_NOOP('Workbech', 'GDML Part tools'),
                           parttoolbarcommands)
        #FreeCADGui.addIconPath(":/icons")
        FreeCADGui.addIconPath(FreeCAD.getResourceDir() + \
                              "Mod/GDML/Resources/icons")
        FreeCADGui.addLanguagePath(":/translations")
示例#37
0
#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2012                                                    * 
#*   Yorik van Havre <*****@*****.**>                                 * 
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   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 FreeCAD,FreeCADGui,Part
Part.open(FreeCAD.getResourceDir()+"examples/Schenkel.stp")
FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
FreeCADGui.activeDocument().sendMsgToViews("ViewAxo")
示例#38
0
import FreeCAD,FreeCADGui
FreeCAD.open(FreeCAD.getResourceDir()+"examples/ArchDetail.FCStd")
FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
示例#39
0
文件: simrobot.py 项目: nortd/gx
    def dynamic_def_files(self, robot_name):
        dh_params = None
        vrml_file = None
        if robot_name == 'kr16':
            # The Denavit-Hartenberg parameters and model for a Kuka KR16.
            dh_params = {
                'axis1':{'a':260.0, 'alpha':-90.0, 'd':675.0, 'theta':0.0, 'rotDir':-1, 'maxAngle':185.0, 'minAngle':-185.0, 'axisVel':156.0},
                'axis2':{'a':680.0, 'alpha':0.0, 'd':0.0, 'theta':0.0, 'rotDir':1, 'maxAngle':35.0, 'minAngle':-155.0, 'axisVel':156.0},
                'axis3':{'a':-35.0, 'alpha':90.0, 'd':0.0, 'theta':-90.0, 'rotDir':1, 'maxAngle':154.0, 'minAngle':-130.0, 'axisVel':156.0},
                'axis4':{'a':0.0, 'alpha':-90.0, 'd':-675.0, 'theta':0.0, 'rotDir':1, 'maxAngle':350.0, 'minAngle':-350.0, 'axisVel':330.0},
                'axis5':{'a':0.0, 'alpha':90.0, 'd':0.0, 'theta':0.0, 'rotDir':1, 'maxAngle':130.0, 'minAngle':-130.0, 'axisVel':330.0},
                'axis6':{'a':0.0, 'alpha':180.0, 'd':-158.0, 'theta':180.0, 'rotDir':1, 'maxAngle':350.0, 'minAngle':-350.0, 'axisVel':615.0},
            }
            vrml_file = FreeCAD.getResourceDir()+"Mod/Robot/Lib/Kuka/kr16.wrl"
        elif robot_name == 'kr500':
            # The Denavit-Hartenberg parameters and model for a Kuka KR500.
            dh_params = {
                'axis1':{'a':500.0, 'alpha':-90.0, 'd':1045.0, 'theta':0.0, 'rotDir':-1, 'maxAngle':185.0, 'minAngle':-185.0, 'axisVel':156.0},
                'axis2':{'a':1300.0, 'alpha':0.0, 'd':0.0, 'theta':0.0, 'rotDir':1, 'maxAngle':35.0, 'minAngle':-155.0, 'axisVel':156.0},
                'axis3':{'a':55.0, 'alpha':90.0, 'd':0.0, 'theta':-90.0, 'rotDir':1, 'maxAngle':154.0, 'minAngle':-130.0, 'axisVel':156.0},
                'axis4':{'a':0.0, 'alpha':-90.0, 'd':-1025.0, 'theta':0.0, 'rotDir':1, 'maxAngle':350.0, 'minAngle':-350.0, 'axisVel':330.0},
                'axis5':{'a':0.0, 'alpha':90.0, 'd':0.0, 'theta':0.0, 'rotDir':1, 'maxAngle':130.0, 'minAngle':-130.0, 'axisVel':330.0},
                'axis6':{'a':0.0, 'alpha':180.0, 'd':-300.0, 'theta':180.0, 'rotDir':1, 'maxAngle':350.0, 'minAngle':-350.0, 'axisVel':615.0},
            }
            vrml_file = FreeCAD.getResourceDir()+"Mod/Robot/Lib/Kuka/kr500_1.wrl"
        elif robot_name == 'irb2600':
            # The Denavit-Hartenberg parameters and model for an ABB IRB2600-20-1.65.
            # it appears to be ok to invert a and alpha simultaneously
            # min/maxAngle is min/max theta
            dh_params = {
                'axis1':{'a':150.0, 'alpha':-90.0, 'd':445.0, 'theta':0.0, 'rotDir':1, 'maxAngle':180.0, 'minAngle':-180.0, 'axisVel':175.0},
                'axis2':{'a':700.0, 'alpha':0.0, 'd':0.0, 'theta':-90.0, 'rotDir':1, 'maxAngle':155.0, 'minAngle':-95.0, 'axisVel':175.0},
                'axis3':{'a':115.0, 'alpha':90.0, 'd':0.0, 'theta':0.0, 'rotDir':1, 'maxAngle':75.0, 'minAngle':-180.0, 'axisVel':175.0},
                'axis4':{'a':0.0, 'alpha':-90.0, 'd':-795.0, 'theta':0.0, 'rotDir':-1, 'maxAngle':400.0, 'minAngle':-400.0, 'axisVel':360.0},
                'axis5':{'a':0.0, 'alpha':90.0, 'd':0.0, 'theta':0.0, 'rotDir':1, 'maxAngle':120.0, 'minAngle':-120.0, 'axisVel':360.0},
                'axis6':{'a':0.0, 'alpha':180.0, 'd':-85.0, 'theta':180.0, 'rotDir':-1, 'maxAngle':400.0, 'minAngle':-400.0, 'axisVel':500.0},
            }
            thislocation = os.path.dirname(os.path.realpath(__file__))
            vrml_file = os.path.join(thislocation, 'irb2600.wrl')
        else:
            print "ERROR: no dh data for robot name"
            return

        axes = ('axis1', 'axis2', 'axis3', 'axis4', 'axis5', 'axis6')
        params = ('a', 'alpha', 'd', 'theta', 'rotDir', 'maxAngle', 'minAngle', 'axisVel')
        csv_string = []
        first = True
        for param in params:
            if first:
                first = False
            else:
                csv_string.append(',   ') 
            csv_string.append(param)
        csv_string.append('\n')
        for axis in axes:
            first = True
            for param in params:
                if first:
                    first = False
                else:
                    csv_string.append(',   ')    
                csv_string.append(str(dh_params[axis][param]))
            csv_string.append('\n')
        csv_string = ''.join(csv_string)
        thislocation = os.path.dirname(os.path.realpath(__file__))
        filename = os.path.join(thislocation, '..', '..', 'temp', 'dh_file.csv')
        with open(filename, 'w') as f:
            f.write(csv_string)
            print("INFO: DH file witten to: %s" % (filename))
        return { 'csv': filename, 'wrl':vrml_file }
示例#40
0
def Plot(scale, sections, shape):
    """ Creates the outline draw.
    @param scale Plane scale (format 1:scale)
    @param sections Computed sections.
    @param shape Ship surfaces
    @return plotted object (DocumentObject)
    """
    msg = QtGui.QApplication.translate(
        "ship_console",
        "Performing plot",
        None,
        QtGui.QApplication.UnicodeUTF8)
    FreeCAD.Console.PrintMessage(msg + ' (1:{0})...\n'.format(scale))
    scale = 1.0 / scale
    # Take positions
    bounds = [0.0, 0.0, 0.0]
    bbox = shape.BoundBox
    bounds[0] = bbox.XLength
    bounds[1] = bbox.YLength
    bounds[2] = bbox.ZLength
    xTot = scale * bounds[1] + 32.0 + scale * bounds[0]
    yTot = scale * bounds[2] + 32.0 + scale * bounds[1]
    xMid = 210.0
    yMid = 185.0
    x0 = xMid - 0.5 * xTot
    y0 = 297.0 - yMid - 0.5 * yTot  # 297 = A3_width
    # Get border
    edges = getEdges([shape])
    border = edges[0]
    for i in range(0, len(edges)):
        border = border.oldFuse(edges[i])
        border = border.oldFuse(edges[i].mirror(Vector(0.0, 0.0, 0.0),
                                                Vector(0.0, 1.0, 0.0)))
    # Fuse sections & borders
    obj = border.oldFuse(sections)
    # Send to 3D view
    Part.show(obj)
    objs = FreeCAD.ActiveDocument.Objects
    obj = objs[len(objs) - 1]
    # Create a new plane
    FreeCAD.ActiveDocument.addObject('Drawing::FeaturePage',
                                     'OutlineDrawPlot')
    FreeCAD.ActiveDocument.OutlineDrawPlot.Template = (
        FreeCAD.getResourceDir() + 'Mod/Drawing/Templates/A3_Landscape.svg')
    # Side view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart',
                                     'OutlineDrawSideView')
    FreeCAD.ActiveDocument.OutlineDrawSideView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawSideView.Direction = (1.0, 0.0, 0.0)
    FreeCAD.ActiveDocument.OutlineDrawSideView.Rotation = -90.0
    FreeCAD.ActiveDocument.OutlineDrawSideView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawSideView.X = (
        420.0 - x0 - 0.5 * scale * bounds[1])  # 420 = A3_height
    FreeCAD.ActiveDocument.OutlineDrawSideView.Y = (
        y0 + 0.5 * scale * bounds[2])
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(
        FreeCAD.ActiveDocument.OutlineDrawSideView)
    # Front view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart',
                                     'OutlineDrawFrontView')
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Direction = (0.0, 1.0, 0.0)
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Rotation = -90.0
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawFrontView.X = (
        420.0 - x0 - scale * bounds[1] - 32 - 0.5 * scale * bounds[0])
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Y = (
        y0 + 0.5 * scale * bounds[2])
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(
        FreeCAD.ActiveDocument.OutlineDrawFrontView)
    # Up view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart',
                                     'OutlineDrawUpView')
    FreeCAD.ActiveDocument.OutlineDrawUpView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawUpView.Direction = (0.0, 0.0, 1.0)
    FreeCAD.ActiveDocument.OutlineDrawUpView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawUpView.X = (
        420.0 - x0 - scale * bounds[1] - 32 - 0.5 * scale * bounds[0])
    FreeCAD.ActiveDocument.OutlineDrawUpView.Y = (
        y0 + scale * bounds[2] + 32)
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(
        FreeCAD.ActiveDocument.OutlineDrawUpView)
    FreeCAD.ActiveDocument.recompute()
    return obj
示例#41
0
 def testHtmlCase(self):
     bytestr=b'<b>Fran\xc3\xa7ais</b>'
     browser=WebGui.openBrowserWindow('Browser')
     browser.setHtml(bytestr.decode("utf8"), FreeCAD.getResourceDir())
示例#42
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:
            with open(qssfile, 'r') as f:
                ALTCSS = encode(f.read())
            HTML = HTML.replace("<!--QSS-->","<style type=\"text/css\">"+ALTCSS+"</style>")

    # 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>"
    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'))
    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
示例#43
0
#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2016                                                    * 
#*   Bernd Hahnebach <*****@*****.**>                                 * 
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   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 FreeCAD,FreeCADGui,os
# filename will be given before this script is run
FreeCAD.loadFile(os.path.join(FreeCAD.getResourceDir()+"examples",filename))
FreeCADGui.activeDocument().sendMsgToViews("ViewFit")

from StartPage import StartPage
StartPage.postStart()
示例#44
0
import FreeCAD,FreeCADGui
FreeCAD.open(FreeCAD.getResourceDir()+"examples/PartDesignExample.FCStd")
FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
FreeCADGui.activeDocument().sendMsgToViews("ViewAxo")
示例#45
0
文件: Plot.py 项目: orlik80/free-cad
def Plot(scale, sections, shape):
    """ Creates the outline draw.
    @param scale Plane scale (format 1:scale)
    @param sections Sections computed.
    @param shape Ship surfaces shell
    @return plotted object (DocumentObject)
    """
    msg = Translator.translate('Performing plot (Scale 1:%d)...\n' % (scale))
    FreeCAD.Console.PrintMessage(msg)
    scale = 1000.0 / scale
    # Take positions
    bounds = [0.0, 0.0, 0.0]
    bbox = shape.BoundBox
    bounds[0] = bbox.XLength
    bounds[1] = bbox.YLength
    bounds[2] = bbox.ZLength
    xTot = scale * bounds[1] + 32.0 + scale * bounds[0]
    yTot = scale * bounds[2] + 32.0 + scale * bounds[1]
    xMid = 210.0
    yMid = 185.0
    x0 = xMid - 0.5 * xTot
    y0 = 297.0 - yMid - 0.5 * yTot  # 297 = A3_width
    # Get border
    edges = Geometry.getEdges([shape])
    border = edges[0]
    for i in range(0, len(edges)):
        border = border.oldFuse(
            edges[i]
        )  # Only group objects, don't try to build more complex entities
        border = border.oldFuse(edges[i].mirror(Vector(0.0, 0.0, 0.0),
                                                Vector(0.0, 1.0, 0.0)))
    # Fuse sections & borders
    # obj = sections.oldFuse(border)
    obj = border.oldFuse(sections)
    # Send to 3D view
    Part.show(obj)
    objs = FreeCAD.ActiveDocument.Objects
    obj = objs[len(objs) - 1]
    # Create a new plane
    FreeCAD.ActiveDocument.addObject('Drawing::FeaturePage', 'OutlineDrawPlot')
    FreeCAD.ActiveDocument.OutlineDrawPlot.Template = FreeCAD.getResourceDir(
    ) + 'Mod/Drawing/Templates/A3_Landscape.svg'
    # Side view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart',
                                     'OutlineDrawSideView')
    FreeCAD.ActiveDocument.OutlineDrawSideView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawSideView.Direction = (1.0, 0.0, 0.0)
    FreeCAD.ActiveDocument.OutlineDrawSideView.Rotation = -90.0
    FreeCAD.ActiveDocument.OutlineDrawSideView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawSideView.X = 420.0 - x0 - 0.5 * scale * bounds[
        1]  # 420 = A3_height
    FreeCAD.ActiveDocument.OutlineDrawSideView.Y = y0 + 0.5 * scale * bounds[2]
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(
        FreeCAD.ActiveDocument.OutlineDrawSideView)
    # Front view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart',
                                     'OutlineDrawFrontView')
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Direction = (0.0, 1.0, 0.0)
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Rotation = -90.0
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawFrontView.X = 420.0 - x0 - scale * bounds[
        1] - 32 - 0.5 * scale * bounds[0]
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Y = y0 + 0.5 * scale * bounds[2]
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(
        FreeCAD.ActiveDocument.OutlineDrawFrontView)
    # Up view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart',
                                     'OutlineDrawUpView')
    FreeCAD.ActiveDocument.OutlineDrawUpView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawUpView.Direction = (0.0, 0.0, 1.0)
    FreeCAD.ActiveDocument.OutlineDrawUpView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawUpView.X = 420.0 - x0 - scale * bounds[
        1] - 32 - 0.5 * scale * bounds[0]
    FreeCAD.ActiveDocument.OutlineDrawUpView.Y = y0 + scale * bounds[2] + 32
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(
        FreeCAD.ActiveDocument.OutlineDrawUpView)
    FreeCAD.ActiveDocument.recompute()
    return obj
示例#46
0
 def __init__(self):
     self.__class__.Icon = FreeCAD.getResourceDir(
     ) + "Mod/Fem/Resources/icons/FemWorkbench.svg"
     self.__class__.MenuText = "FEM"
     self.__class__.ToolTip = "FEM workbench"
示例#47
0
def Plot(scale, sections, shape):
    """ Creates the outline draw.
    @param scale Plane scale (format 1:scale)
    @param sections Sections computed.
    @param shape Ship surfaces shell
    @return plotted object (DocumentObject)
    """
    msg = Translator.translate('Performing plot (Scale 1:%d)...\n' % (scale))
    FreeCAD.Console.PrintMessage(msg)
    scale = 1000.0 / scale
    # Take positions
    bounds = [0.0, 0.0, 0.0]
    bbox = shape.BoundBox
    bounds[0] = bbox.XLength
    bounds[1] = bbox.YLength
    bounds[2] = bbox.ZLength
    xTot = scale*bounds[1] + 32.0 + scale*bounds[0]
    yTot = scale*bounds[2] + 32.0 + scale*bounds[1]
    xMid = 210.0
    yMid = 185.0
    x0 = xMid - 0.5*xTot
    y0 = 297.0 - yMid - 0.5*yTot # 297 = A3_width
    # Get border
    edges = Geometry.getEdges([shape])
    border = edges[0]
    for i in range(0,len(edges)):
        border = border.oldFuse(edges[i])   # Only group objects, don't try to build more complex entities
        border = border.oldFuse(edges[i].mirror(Vector(0.0, 0.0, 0.0),Vector(0.0, 1.0, 0.0)))
    # Fuse sections & borders
    # obj = sections.oldFuse(border)
    obj = border.oldFuse(sections)
    # Send to 3D view
    Part.show(obj)
    objs = FreeCAD.ActiveDocument.Objects
    obj = objs[len(objs)-1]
    # Create a new plane
    FreeCAD.ActiveDocument.addObject('Drawing::FeaturePage','OutlineDrawPlot')
    FreeCAD.ActiveDocument.OutlineDrawPlot.Template = FreeCAD.getResourceDir()+'Mod/Drawing/Templates/A3_Landscape.svg'
    # Side view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart','OutlineDrawSideView')
    FreeCAD.ActiveDocument.OutlineDrawSideView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawSideView.Direction = (1.0,0.0,0.0)
    FreeCAD.ActiveDocument.OutlineDrawSideView.Rotation = -90.0
    FreeCAD.ActiveDocument.OutlineDrawSideView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawSideView.X = 420.0 - x0 - 0.5*scale*bounds[1] # 420 = A3_height
    FreeCAD.ActiveDocument.OutlineDrawSideView.Y = y0 + 0.5*scale*bounds[2]
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(FreeCAD.ActiveDocument.OutlineDrawSideView)
    # Front view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart','OutlineDrawFrontView')
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Direction = (0.0,1.0,0.0)
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Rotation = -90.0
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawFrontView.X = 420.0 - x0 - scale*bounds[1] - 32 - 0.5*scale*bounds[0]
    FreeCAD.ActiveDocument.OutlineDrawFrontView.Y = y0 + 0.5*scale*bounds[2]
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(FreeCAD.ActiveDocument.OutlineDrawFrontView)
    # Up view
    FreeCAD.ActiveDocument.addObject('Drawing::FeatureViewPart','OutlineDrawUpView')
    FreeCAD.ActiveDocument.OutlineDrawUpView.Source = obj
    FreeCAD.ActiveDocument.OutlineDrawUpView.Direction = (0.0,0.0,1.0)
    FreeCAD.ActiveDocument.OutlineDrawUpView.Scale = scale
    FreeCAD.ActiveDocument.OutlineDrawUpView.X = 420.0 - x0 - scale*bounds[1] - 32 - 0.5*scale*bounds[0]
    FreeCAD.ActiveDocument.OutlineDrawUpView.Y = y0 + scale*bounds[2] + 32
    FreeCAD.ActiveDocument.OutlineDrawPlot.addObject(FreeCAD.ActiveDocument.OutlineDrawUpView)
    FreeCAD.ActiveDocument.recompute()
    return obj
示例#48
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:
            with open(qssfile, 'r') as f:
                ALTCSS = encode(f.read())
            HTML = HTML.replace("<!--QSS-->","<style type=\"text/css\">"+ALTCSS+"</style>")

    # 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>"
    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'))
    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
示例#49
0
    def __init__(self, obj=None, prop=None, material=None):

        """Initializes, optionally with an object name and a material property
        name to edit, or directly with a material dictionary."""

        self.obj = obj
        self.prop = prop
        self.material = material
        self.customprops = []
        self.internalprops = []
        self.groups = []
        self.directory = FreeCAD.getResourceDir() + "Mod/Material"

        # load the UI file from the same directory as this script
        self.widget = FreeCADGui.PySideUic.loadUi(
            os.path.dirname(__file__) + os.sep + "materials-editor.ui"
        )

        # additional UI fixes and tweaks
        widget = self.widget
        buttonURL = widget.ButtonURL
        buttonDeleteProperty = widget.ButtonDeleteProperty
        buttonAddProperty = widget.ButtonAddProperty
        standardButtons = widget.standardButtons
        buttonOpen = widget.ButtonOpen
        buttonSave = widget.ButtonSave
        comboMaterial = widget.ComboMaterial
        treeView = widget.treeView

        # temporarily hide preview fields, as they are not used yet
        # TODO : implement previews
        widget.PreviewGroup.hide()

        buttonURL.setIcon(QtGui.QIcon(":/icons/internet-web-browser.svg"))
        buttonDeleteProperty.setEnabled(False)
        standardButtons.button(QtGui.QDialogButtonBox.Ok).setAutoDefault(False)
        standardButtons.button(QtGui.QDialogButtonBox.Cancel).setAutoDefault(False)
        self.updateCards()
        # TODO allow to enter a custom property by pressing Enter in the lineedit
        # currently closes the dialog

        standardButtons.rejected.connect(self.reject)
        standardButtons.accepted.connect(self.accept)
        buttonOpen.clicked.connect(self.openfile)
        buttonSave.clicked.connect(self.savefile)
        buttonURL.clicked.connect(self.openProductURL)
        comboMaterial.currentIndexChanged[str].connect(self.updateContents)
        buttonAddProperty.clicked.connect(self.addCustomProperty)
        buttonDeleteProperty.clicked.connect(self.deleteCustomProperty)
        treeView.clicked.connect(self.checkDeletable)

        model = QtGui.QStandardItemModel()
        treeView.setModel(model)
        treeView.setUniformRowHeights(True)
        treeView.setItemDelegate(MaterialsDelegate())

        # update the editor with the contents of the property, if we have one
        d = None
        if self.prop and self.obj:
            d = FreeCAD.ActiveDocument.getObject(self.obj).getPropertyByName(self.prop)
        elif self.material:
            d = self.material

        self.implementModel()
        if d:
            self.updateContents(d)
示例#50
0
 def __init__(self):
     self.__class__.Icon = FreeCAD.getResourceDir() + "Mod/OpenSCAD/Resources/icons/OpenSCADWorkbench.svg"
     self.__class__.MenuText = "OpenSCAD"
     self.__class__.ToolTip = "OpenSCAD workbench"
示例#51
0
  t.insertWaypoints(Waypoint(Placement(Vector(0,0,i*100+500),Vector(1,0,0),0),"LIN","Pt"))

# see a list of all waypoints:
print(t.Waypoints)

del rob,Start,t,l,w

# === working with the document ===
# 
# Working with the robot document objects:
# first create a robot in the active document
if(App.activeDocument() == None):App.newDocument()

App.activeDocument().addObject("Robot::RobotObject","Robot")
# Define the visual representation and the kinematic definition (see [[6-Axis Robot]] for details about that)
App.activeDocument().Robot.RobotVrmlFile = App.getResourceDir()+"Mod/Robot/Lib/Kuka/kr500_1.wrl"
App.activeDocument().Robot.RobotKinematicFile = App.getResourceDir()+"Mod/Robot/Lib/Kuka/kr500_1.csv"
# start position of the Axis (only that which differ from 0)
App.activeDocument().Robot.Axis2 = -90
App.activeDocument().Robot.Axis3 = 90

# retrieve the Tcp position 
pos = App.getDocument("Unnamed").getObject("Robot").Tcp
# move the robot
pos.move(App.Vector(-10,0,0))
App.getDocument("Unnamed").getObject("Robot").Tcp = pos

# create an empty Trajectory object in the active document
App.activeDocument().addObject("Robot::TrajectoryObject","Trajectory")
# get the Trajectory
t = App.activeDocument().Trajectory.Trajectory
#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2012                                                    * 
#*   Yorik van Havre <*****@*****.**>                                 * 
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   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 FreeCAD,FreeCADGui
FreeCAD.open(FreeCAD.getResourceDir()+"examples/FemCalculixCantilever3D_newSolver.FCStd")
FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
示例#53
0
#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2012                                                    * 
#*   Yorik van Havre <*****@*****.**>                                 * 
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   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 FreeCAD,FreeCADGui
FreeCADGui.activateWorkbench("DrawingWorkbench")
FreeCAD.open(FreeCAD.getResourceDir()+"examples/DrawingExample.FCStd")
FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
FreeCADGui.activeDocument().sendMsgToViews("ViewAxo")
示例#54
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)

    # 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:
            with open(qssfile, 'r') as f:
                ALTCSS = f.read()
                if sys.version_info.major < 3:
                    ALTCSS = ALTCSS.decode("utf8")
            HTML = HTML.replace("<!--QSS-->","<style type=\"text/css\">"+ALTCSS+"</style>")

    # get FreeCAD version

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

    # translate texts

    HTML = HTML.replace("T_TITLE",TranslationTexts.T_TITLE)
    HTML = HTML.replace("T_DOCUMENTS",TranslationTexts.T_DOCUMENTS)
    HTML = HTML.replace("T_HELP",TranslationTexts.T_HELP)
    HTML = HTML.replace("T_ACTIVITY",TranslationTexts.T_ACTIVITY)
    HTML = HTML.replace("T_TIP",TranslationTexts.T_TIP)
    HTML = HTML.replace("T_ADJUSTRECENT",TranslationTexts.T_ADJUSTRECENT)
    HTML = HTML.replace("T_GENERALDOCUMENTATION",TranslationTexts.T_GENERALDOCUMENTATION)
    HTML = HTML.replace("T_USERHUB",TranslationTexts.T_USERHUB)
    HTML = HTML.replace("T_DESCR_USERHUB",TranslationTexts.T_DESCR_USERHUB)
    HTML = HTML.replace("T_POWERHUB",TranslationTexts.T_POWERHUB)
    HTML = HTML.replace("T_DESCR_POWERHUB",TranslationTexts.T_DESCR_POWERHUB)
    HTML = HTML.replace("T_DEVHUB",TranslationTexts.T_DEVHUB)
    HTML = HTML.replace("T_DESCR_DEVHUB",TranslationTexts.T_DESCR_DEVHUB)
    HTML = HTML.replace("T_MANUAL",TranslationTexts.T_MANUAL)
    HTML = HTML.replace("T_DESCR_MANUAL",TranslationTexts.T_DESCR_MANUAL)
    HTML = HTML.replace("T_WBHELP",TranslationTexts.T_WBHELP)
    HTML = HTML.replace("T_DESCR_WBHELP",TranslationTexts.T_DESCR_WBHELP)
    HTML = HTML.replace("T_COMMUNITYHELP",TranslationTexts.T_COMMUNITYHELP)
    HTML = HTML.replace("T_DESCR_COMMUNITYHELP1",TranslationTexts.T_DESCR_COMMUNITYHELP1)
    HTML = HTML.replace("T_DESCR_COMMUNITYHELP2",TranslationTexts.T_DESCR_COMMUNITYHELP2)
    HTML = HTML.replace("T_DESCR_COMMUNITYHELP3",TranslationTexts.T_DESCR_COMMUNITYHELP3)
    HTML = HTML.replace("T_ADDONS",TranslationTexts.T_ADDONS)
    HTML = HTML.replace("T_DESCR_ADDONS",TranslationTexts.T_DESCR_ADDONS)
    HTML = HTML.replace("T_OFFLINEHELP",TranslationTexts.T_OFFLINEHELP)
    HTML = HTML.replace("T_OFFLINEPLACEHOLDER",TranslationTexts.T_OFFLINEPLACEHOLDER)
    HTML = HTML.replace("T_RECENTCOMMITS",TranslationTexts.T_RECENTCOMMITS)
    HTML = HTML.replace("T_DESCR_RECENTCOMMITS",TranslationTexts.T_DESCR_RECENTCOMMITS)
    HTML = HTML.replace("T_SEEONGITHUB",TranslationTexts.T_SEEONGITHUB)
    HTML = HTML.replace("T_CUSTOM",TranslationTexts.T_CUSTOM)
    HTML = HTML.replace("T_FORUM",TranslationTexts.T_FORUM)
    HTML = HTML.replace("T_DESCR_FORUM",TranslationTexts.T_DESCR_FORUM)
    HTML = HTML.replace("T_EXTERNALLINKS",TranslationTexts.T_EXTERNALLINKS)
    HTML = HTML.replace("T_NOTES",TranslationTexts.T_NOTES)

    # 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 = ""
    rf = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/RecentFiles")
    rfcount = rf.GetInt("RecentFiles",0)
    if rfcount:
        SECTION_RECENTFILES = "<h2>"+TranslationTexts.T_RECENTFILES+"</h2>"
        SECTION_RECENTFILES += "<ul>"
        for i in range(rfcount):
            filename = rf.GetString("MRU%d" % (i))
            SECTION_RECENTFILES += buildCard(filename,method="LoadMRU.py?MRU=",arg=str(i))
        SECTION_RECENTFILES += '<li class="icon">'
        SECTION_RECENTFILES += '<a href="LoadNew.py" title="'+TranslationTexts.T_CREATENEW+'">'
        SECTION_RECENTFILES += '<img src="'+iconbank["createimg"]+'">'
        SECTION_RECENTFILES += '<div class="caption">'
        SECTION_RECENTFILES += '<h4>'+TranslationTexts.T_CREATENEW+'</h4>'
        SECTION_RECENTFILES += '</div>'
        SECTION_RECENTFILES += '</li>'
        SECTION_RECENTFILES += '</a>'
        SECTION_RECENTFILES += '</ul>'
        if sys.version_info.major < 3:
            SECTION_RECENTFILES = SECTION_RECENTFILES.decode("utf8")
    HTML = HTML.replace("SECTION_RECENTFILES",SECTION_RECENTFILES)

    # build SECTION_EXAMPLES

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

    # build SECTION_CUSTOM

    SECTION_CUSTOM = ""
    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 = "<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 += buildCard(filename,method="LoadCustom.py?filename=")
        SECTION_CUSTOM += "</ul>"
    if sys.version_info.major < 3:
        SECTION_CUSTOM = SECTION_CUSTOM.decode("utf8")
    HTML = HTML.replace("SECTION_CUSTOM",SECTION_CUSTOM)

    # 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
        if wn == "flamingoTools":
            wn = "flamingo"
        if wn == "Geodat":
            wn = "geodata"
        if wn == "None":
            continue
        wblist.append(wn.lower())
        if wb in iconbank:
            img = iconbank[wb]
        else:
            img = os.path.join(FreeCAD.getResourceDir(),"data","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="images/freecad.png"
            iconbank[wb] = img
        UL_WORKBENCHES += '<li>'
        UL_WORKBENCHES += '<img src="'+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",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 = 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

    # encode if necessary

    if sys.version_info.major < 3:
        if isinstance(HTML,unicode):
            HTML = HTML.encode("utf8")

    return HTML
示例#55
0
import FreeCAD,FreeCADGui
FreeCAD.open(FreeCAD.getResourceDir()+"examples/RobotExample.FCStd")
FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
FreeCADGui.activeDocument().sendMsgToViews("ViewAxo")
 def __init__(self):
     self.__class__.Icon = FreeCAD.getResourceDir() + "Mod/Fem/Resources/icons/FemWorkbench.svg"
     self.__class__.MenuText = "FEM"
     self.__class__.ToolTip = "FEM workbench"
示例#57
0
try:
    import io as cStringIO
except:
    import cStringIO

FreeCADGui.addLanguagePath(":/translations")
FreeCADGui.updateLocale()

# get FreeCAD version
v = FreeCAD.Version()
vmajor, vminor = v[0], v[1]
vbuild = v[2].split(" ")[0]

# here is the html page skeleton
resources_dir = os.path.join(FreeCAD.getResourceDir(), "Mod", "Start", "StartPage")
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, 'rb') as f:
    startpage_html = f.read()

with open(js_filename, 'rb') as f:
    startpage_js = f.read()

with open(css_filename, 'rb') as f:
    startpage_css = f.read()

def getInfo(filename):
    "returns available file information"
示例#58
0
    # \endcond

## @package ArchProfile
#  \ingroup ARCH
#  \brief Profile tools for ArchStructure
#
#  This module provides tools to build base profiles
#  for Arch Structure elements

__title__="FreeCAD Profile"
__author__ = "Yorik van Havre"
__url__ = "http://www.freecadweb.org"

# Presets in the form: Class, Name, Profile type, [profile data]
# Search for profiles.csv in data/Mod/Arch/Presets and in the same folder as this file
profilefiles = [os.path.join(FreeCAD.getResourceDir(),"Mod","Arch","Presets","profiles.csv"),
                os.path.join(os.path.dirname(__file__),"Presets","profiles.csv")]

def readPresets():
    Presets=[]
    for profilefile in profilefiles:
        if os.path.exists(profilefile):
            try:
                with open(profilefile, "r") as csvfile:
                    beamreader = csv.reader(csvfile)
                    bid=1 #Unique index
                    for row in beamreader:
                        if row[0].startswith("#"):
                            continue
                        try:
                            r=[bid, row[0], row[1], row[2]]
示例#59
0
 def __init__(self):
     self.ui = App.getResourceDir() + "Mod/TemplatePyMod/TaskPanel.ui"