Ejemplo n.º 1
0
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
"""

__doc__ = 'Adds "CLR." to the suffix of selected dimensions.'

__window__.Close()
from Autodesk.Revit.DB import Transaction, Dimension

uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document

t = Transaction(doc, 'Dimension CLR suffix')
t.Start()

for elId in uidoc.Selection.GetElementIds():
    el = doc.GetElement(elId)
    if isinstance(el, Dimension):
        if len(list(el.Segments)) > 0:
            for seg in el.Segments:
                if not seg.Suffix is None:
                    seg.Suffix += 'CLR.'
                else:
                    seg.Suffix = 'CLR.'
        else:
            seg = el
            if not seg.Suffix is None:
                seg.Suffix += 'CLR.'
Ejemplo n.º 2
0
# target = XYZ(0, 0, 3)
abs = origin.Z + max.Z
delta = target.Z - abs

box.Max = XYZ(max.X, max.Y, max.Z + delta)

# print(face.Origin)
# print(face.GetBoundingBox())
# print(dir(face))


# box.Max -= XYZ(0, 0, 1)


t = Transaction(doc, 'Обрезка 3D вида')
t.Start()

# Point.Create(XYZ(0, 0, 10))

# doc.ActiveView.SetSectionBox(box)

t.Commit()

# Document doc = uidoc.Document;

# Reference r = uidoc.Selection.PickObject(
#   ObjectType.Face,
#   "Please select a planar face to define work plane" );

# Element e = doc.get_Element( r.ElementId );
# -*- coding: utf-8 -*-
import clr

clr.AddReference("RevitAPI")
clr.AddReference("System")
from Autodesk.Revit.DB import FilteredElementCollector as Fec
from Autodesk.Revit.DB import BuiltInCategory as Bic
from Autodesk.Revit.DB import BuiltInParameter as Bip
from Autodesk.Revit.DB import Transaction

tx = Transaction(doc, "check structural level offsets")
tx.Start()

rooms = Fec(doc).OfCategory(
    Bic.OST_Rooms).WhereElementIsNotElementType().ToElements()
areas = Fec(doc).OfCategory(
    Bic.OST_Areas).WhereElementIsNotElementType().ToElements()

for room in rooms:
    try:
        print(room.get_Parameter(Bip.ROOM_NAME).AsString())
        value0 = room.LookupParameter("Geschoss").AsString()
        room.LookupParameter("temp").Set(value0)
    except:
        print(room.Id)

for area in areas:
    id = area.get_Parameter(Bip.AREA_SCHEME_ID).AsElementId()
    if str(id) == "522977":
        try:
            print(area.get_Parameter(Bip.ROOM_NAME).AsString())
Ejemplo n.º 4
0
pyRevit is a free set of scripts for Autodesk Revit: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3, as published by
the Free Software Foundation.

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 General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
"""

__doc__ = 'Converts the select text note element into UPPERCASE text.'

__window__.Close()
from Autodesk.Revit.DB import Transaction

doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument

t = Transaction(doc, 'convert text')
t.Start()

for elId in uidoc.Selection.GetElementIds():
    el = doc.GetElement(elId)
    el.Text = el.Text.upper()

t.Commit()
Ejemplo n.º 5
0
def transaction(doc, message):
    tr = Transaction(doc, message)
    tr.Start()
    yield
    tr.Commit()
Ejemplo n.º 6
0
doc = __revit__.ActiveUIDocument.Document

views = FilteredElementCollector(doc).OfClass(
    View).WhereElementIsNotElementType().ToElements()
filters = FilteredElementCollector(doc).OfClass(
    ParameterFilterElement).ToElements()

usedFiltersSet = set()
allFilters = set()
for flt in filters:
    allFilters.add(flt.Id.IntegerValue)

for v in views:
    try:
        filters = v.GetFilters()
        for flid in filters:
            usedFiltersSet.add(flid.IntegerValue)
    except:
        continue

unusedFilters = allFilters - usedFiltersSet

t = Transaction(doc, 'Purge Unused Filters')
t.Start()

for flid in unusedFilters:
    fl = doc.GetElement(ElementId(flid))
    print('ID: {0}\t{1}'.format(fl.Id, fl.Name))
    doc.Delete(ElementId(flid))

t.Commit()
Ejemplo n.º 7
0
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
'''

__doc__ = 'Sets element graphic override to halftone on the selected elements. If any of the elements is a group, the script will apply the override to all its members.'

__window__.Close()
from Autodesk.Revit.DB import Transaction, OverrideGraphicSettings, Group

doc = __revit__.ActiveUIDocument.Document
selection = [
    doc.GetElement(elId)
    for elId in __revit__.ActiveUIDocument.Selection.GetElementIds()
]

with Transaction(doc, 'Halftone Elements in View') as t:
    t.Start()
    for el in selection:
        if isinstance(el, Group):
            for mem in el.GetMemberIds():
                selection.append(doc.GetElement(mem))
        ogs = OverrideGraphicSettings()
        ogs.SetHalftone(True)
        ogs.SetProjectionFillPatternVisible(False)
        doc.ActiveView.SetElementOverrides(el.Id, ogs)
    t.Commit()
Ejemplo n.º 8
0
    toStyle = toStyleLine.LineStyle

    linelist = []

    cl = FilteredElementCollector(doc)
    cllines = cl.OfCategory(
        BuiltInCategory.OST_Lines
        or BuiltInCategory.OST_SketchLines).WhereElementIsNotElementType()
    for c in cllines:
        if c.LineStyle.Name == fromStyle.Name:
            linelist.append(c)
            # print( '{0:<10} {1:<25}{2:<8} {3:<15}'.format(c.Id, c.GetType().Name, c.LineStyle.Id, c.LineStyle.Name) )

    if len(linelist) > 100:
        verbose = False
    with Transaction(doc, 'Swap Line Styles') as t:
        t.Start()
        for line in linelist:
            if line.Category.Name != '<Sketch>' and line.GroupId < ElementId(
                    0):
                if verbose:
                    print('LINE FOUND:\t{0:<10} {1:<25}{2:<8} {3:<15}'.format(
                        line.Id,
                        line.GetType().Name, line.LineStyle.Id,
                        line.LineStyle.Name))
                line.LineStyle = toStyle
            elif line.Category.Name == '<Sketch>':
                print(
                    'SKIPPED <Sketch> Line ----:\n           \t{0:<10} {1:<25}{2:<8} {3:<15}\n'
                    .format(line.Id,
                            line.GetType().Name, line.LineStyle.Id,
Ejemplo n.º 9
0
 def __init__(self, name=None):
     self.transaction = Transaction(doc, name if name else DEFAULT_TRANSACTION_NAME)
Ejemplo n.º 10
0
from Precast.Instalation_plan import Instalation_plan
from Autodesk.Revit.DB import Transaction

doc = __revit__.ActiveUIDocument.Document
with Transaction(doc, "Сформировать монтажный план.") as t:
    t.Start()
    ip = Instalation_plan(doc)
    ip.create_instalation_plan()
    t.Commit()
Ejemplo n.º 11
0
def SetParameterFamilySymbol(FamilySymbol, ParameterName, ParameterValue):
    Parameter = FamilySymbol.LookupParameter(ParameterName)
    t = Transaction(doc, "Set parameter")
    t.Start()
    Parameter.Set(ParameterValue)
    t.Commit()
Ejemplo n.º 12
0
for linkdoc in linkdocs:
    try:
        linkrooms.append(
            FilteredElementCollector(linkdoc).OfCategory(
                BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().
            ToElements())
    except:
        pass
levels = FilteredElementCollector(doc).OfCategory(
    BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements()
'''
linkrooms = []
linkrooms.append(FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToElements())
levels = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements()
'''
t = Transaction(doc, 'Create Spaces')
t.Start()
for g_rooms in linkrooms:
    for room in g_rooms:
        if room.Area > 0:
            list = []
            message = []
            cArray = CurveArray()
            pt = room.Location.Point
            uv = UV(pt.X, pt.Y)
            elev = round(room.Level.Elevation)
            level2 = None
            for level in levels:
                elev2 = round(level.Elevation)
                if elev == elev2:
                    level2 = level
Ejemplo n.º 13
0
            t = int(TuboSecionado3[i].Location.Curve.Length / L)
        d = L * TuboSecionado3[i].Location.Curve.Direction
        for n in range(0, t):
            if (n == 0):
                continue
            else:
                pointsAUX.append(
                    TuboSecionado3[i].Location.Curve.GetEndPoint(0) + n * d)
        points.append(pointsAUX)
        pointsAUX = []

    pipes = TuboSecionado3

    # Typical Transaction in Revit Python Shell / pyRevit
    doc = __revit__.ActiveUIDocument.Document
    transaction = Transaction(doc, 'Delete Object')
    transaction.Start()
    try:
        for t in range(0, len(pipes), 1):
            for i in range(0, len(points[t]), 1):
                dbPoint = points[t][i]
                pipe = pipes[t]
                newPipeId = BreakCurve(doc, pipe.Id, dbPoint)
                newPipe = doc.GetElement(newPipeId)

                if (P[0] != ''):
                    for z in range(0, len(P)):
                        newPipe.LookupParameter(P[z]).Set(
                            str(pipe.LookupParameter(P[z]).AsString()))

                newPipeConnectors = newPipe.ConnectorManager.Connectors
Ejemplo n.º 14
0
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
"""

__doc__ = 'Clears all text overrides from selected dimensions.'

__window__.Close()
from Autodesk.Revit.DB import Transaction, Dimension

uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document

t = Transaction(doc, 'Reset dimension text')
t.Start()

for elId in uidoc.Selection.GetElementIds():
    el = doc.GetElement(elId)
    if isinstance(el, Dimension):
        if len(list(el.Segments)) > 0:
            for seg in el.Segments:
                seg.Below = ''
                seg.Above = ''
                seg.Prefix = ''
                seg.Suffix = ''
                seg.ValueOverride = ''
        else:
            seg = el
            seg.Below = ''
# prepare lists
elem_info = []
element_ids = []

# process elements
GetElemProps(walls)
GetElemProps(floors)
ElemCnvrt(columns)
ElemCnvrt(framing)

# create a collection from all element ids
col1 = List[ElementId](element_ids)

# entering a transaction to modify the revit model database
# start transaction
tx = Transaction(doc, "check structural elements")
tx.Start()

# isolate all elements of category
doc.ActiveView.IsolateElementsTemporary(col1)

# set graphical overrides
for elem in elem_info:
    if elem.structural == 1:
        doc.ActiveView.SetElementOverrides((elem.id), ogs_true)
    if elem.structural == 0:
        doc.ActiveView.SetElementOverrides((elem.id), ogs_false)

# commit the changes to the revit model database
# end transaction
tx.Commit()
Ejemplo n.º 16
0
ids = [
    47945, 47987, 373122, 375375, 377461, 378800, 381142, 382522, 383894,
    385122, 386324, 387562, 388767, 389970, 391929, 393079, 394229, 395434,
    396765, 398040, 400988, 403286, 408378, 409619, 411852, 414828, 417170,
    418519, 419856, 426477, 562883, 564375, 566480, 568623, 569964
]

materials = FilteredElementCollector(doc)\
 .OfCategory(BuiltInCategory.OST_Materials)\
 .WhereElementIsNotElementType().ToElements()

# for mat in materials:
# 	if mat.Name == "My Material":
# 		orig = mat

t = Transaction(doc, 'Материалы')
t.Start()

# types = [doc.GetElement(doc.GetElement(id).GetTypeId()) for id in uidoc.Selection.GetElementIds()]

# params = []
# for type in types:
# 	for param in type.GetOrderedParameters():
# 		if param.Definition.ParameterType == ParameterType.Material:
# 			if param.Name in names.keys():
# 				for mat in materials:
# 					if mat.Name == names[param.Definition.Name]:
# 						break
# 				param.Set(mat.Id)

for id in ids:
doc = __revit__.ActiveUIDocument.Document

if doc.IsFamilyDocument:
	params = doc.FamilyManager.GetParameters()
	dims = FilteredElementCollector( doc ).OfClass( Dimension ).WhereElementIsNotElementType()

	labelParams = set()
	for d in dims:
		try:
			if isinstance( d.FamilyLabel, FamilyParameter ):
				labelParams.add( d.FamilyLabel.Id.IntegerValue )
		except:
			continue

	print('STARTING CLEANUP...')
	t = Transaction(doc, 'Remove all family parameters') 
	t.Start()

	for param in params:
		try:
			print( '\nREMOVING FAMILY PARAMETER:\nID: {0}\tNAME: {1}'.format( param.Id, param.Definition.Name ))
			doc.FamilyManager.RemoveParameter( param )
			print( 'REMOVED.' )
		except:
			print( '-- CAN NOT DELETE --')
			if param.Id.IntegerValue not in labelParams:
				try:
					if param.CanAssignFormula:
						doc.FamilyManager.SetFormula( param , None )
					if param.StorageType == StorageType.Integer or param.StorageType == StorageType.Double:
						doc.FamilyManager.Set( param, 0 )
Ejemplo n.º 18
0
it under the terms of the GNU General Public License version 3, as published by
the Free Software Foundation.

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 General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
'''

__doc__ = 'Flips hand on the selected doors.'

__window__.Close()
from Autodesk.Revit.DB import Transaction

doc = __revit__.ActiveUIDocument.Document
selection = [
    doc.GetElement(elId)
    for elId in __revit__.ActiveUIDocument.Selection.GetElementIds()
]

t = Transaction(doc, 'Flip Hand Selected Doors')
t.Start()

for el in selection:
    if el.Category.Name == 'Doors':
        el.flipHand()

t.Commit()
"""
Copyright (c) 2018 Daniel J. Swearson

"""

# Run this script in RevitPythonShell; user must create a project parameter in Revit titled "CUSTOM_PARAM".
# CUSTOM_PARAM should be created as instance parameter, category set to sheet and type set to text.

__author__ = 'Daniel J. Swearson'
__doc__ = 'Updates custom_param project parameter for all sheets in model.'

from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, Transaction

doc = __revit__.ActiveUIDocument.Document

sheets_collector = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets) \
            .WhereElementIsNotElementType().ToElements()

t = Transaction(doc, "Update Sheet Parameters")
t.Start()

for sheet in sheets_collector:
    custom_param = sheet.LookupParameter("CUSTOM_PARAM")
    if custom_param:
        custom_param.Set("Example Value")

t.Commit()
__window__.Close()
Ejemplo n.º 20
0
from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, Transaction, TransactionGroup

doc = __revit__.ActiveUIDocument.Document

sheets_collector = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets) \
                                                .WhereElementIsNotElementType() \
                                                .ToElementIds()

wall_id_collector = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls) \
                                                 .WhereElementIsNotElementType() \
                                                 .ToElementIds()

tg = TransactionGroup(doc, "Update and Delete")
tg.Start()

t = Transaction(doc, "Update Sheet Parameters")
t.Start()

for sheet in sheets_collector:
    custom_param = sheet.LookupParameter('-Beispielparameter-')
    if custom_param:
        custom_param.Set("Example value")

t.Commit()

t = Transaction(doc, "Deleting All Walls")
t.Start()

for wall_id in wall_id_collector:
    doc.Delete(wall_id)
Ejemplo n.º 21
0
pyRevit is a free set of scripts for Autodesk Revit: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3, as published by
the Free Software Foundation.

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 General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
"""

__doc__ = 'Brings selected object to Front of the current view. This only works on elements that support this option.'

__window__.Close()
from Autodesk.Revit.DB import Transaction
from Autodesk.Revit.DB import DetailElementOrderUtils as eo

uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document

with Transaction(doc, 'Bring Selected To Front') as t:
    t.Start()
    for elId in uidoc.Selection.GetElementIds():
        try:
            eo.BringForward(doc, doc.ActiveView, elId)
        except:
            continue
    t.Commit()
    for cat in b.Categories:
        try:
            elements = FilteredElementCollector(doc).OfCategoryId(cat.Id).WhereElementIsNotElementType()
            if bind == 'Type' and p.Visible:
                elementTypes = FilteredElementCollector(doc).OfCategoryId(cat.Id).WhereElementIsElementType()
                print('Searching through {0} ElementTypes of Category {1}'.format(len(list(elements)), cat.Name))
                for elType in elementTypes:
                    paramidlist.add(elType.LookupParameter(p.Name).Id.IntegerValue)
            elif p.Visible:
                print('Searching through {0} Elements of Category {1}'.format(len(list(elements)), cat.Name))
                for el in elements:
                    paramidlist.add(el.LookupParameter(p.Name).Id.IntegerValue)
        except Exception as e:
            print('---ERROR---\n', p.Name, cat.Name, cat.Id, e)
            continue

t = Transaction(doc, 'Remove all project parameters')
t.Start()

for pid in paramidlist:
    try:
        doc.Delete(ElementId(pid))
    except Exception as e:
        print(pid, e)
        continue

for p in deflist:
    pm.Remove(p)

t.Commit()
Ejemplo n.º 23
0

collectorCSVFile = forms.pick_file(file_ext='csv', multi_file=False, unc_paths=False)

# Main
uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document

__doc__ = 'Extract information from csv file and batch apply parameter value changes.'\
          'Format of csv: "model name, element Id, parameter name, new parameter value".'\
            'Step 1: Select the csv File'\
            'Step 2: Select the Revit Files'\
            'Step 3: Select the directory new models to be placed.'
uiapp = UIApplication(doc.Application)
application = uiapp.Application
t = Transaction(doc, "Apply Parameters")
t.Start()
print(str(doc.Title) + ' Opened')
workshareOp = WorksharingSaveAsOptions()
rawTitle = re.split('detached', doc.Title)[0]
title = rawTitle[0:len(rawTitle) - 1]
# Define the name and location of excel file
for line in Importcsv(collectorCSVFile):
    modelName = line[0]
    id = line[1]
    parameterName = line[2]
    parameterValue = line[3]
    v1 = ()

    if modelName == title:
        element = ()

def get_rules(s):
    result = []
    for part in s.split('; '):
        param_name = part.split('"')[1]
        value = part.split('"')[3]
        evaluator = part.replace(' "' + param_name + '"',
                                 '').replace(' "' + value + '"', '').split()[1]
        param = get_param(param_name)
        rule = create_rule(param, evaluator, value)
        result.append(rule)
    return result


t = Transaction(doc, 'Виды и фильтры')
t.Start()

all_filters = FilteredElementCollector(doc).OfClass(
    ParameterFilterElement).ToElements()
all_filters = natural_sorted(all_filters, key=lambda x: x.Name)
data = []
for filt in all_filters:
    current_id = str(filt.Id)
    current_name = str(filt.Name)
    current_cats = '; '.join(
        sorted([cats[elid.IntegerValue][1] for elid in filt.GetCategories()]))
    lfilter = filt.GetElementFilter()
    current_logic = ''
    current_rules = ''
    if lfilter:
Ejemplo n.º 25
0
# get family document and verify the file exists -----------------------------------------------------------------------
fam_doc = doc.EditFamily(fam_symbol)
fam_doc_path = fam_doc.PathName
if not op.exists(fam_doc_path):
    TaskDialog.Show(
        'pyRevit',
        'Can not file original family file at\n{}'.format(fam_doc_path))
    logger.debug(
        'Can not file original family file at {}'.format(fam_doc_path))
    this_script.exit()
else:
    logger.debug('Loading family from: {}'.format(fam_doc_path))

# fake load the family so we can get the symbols -----------------------------------------------------------------------
symbol_list = set()
with Transaction(doc, 'Fake load') as t:
    t.Start()
    # remove existing family so we can load the original
    doc.Delete(fam_symbol.Id)
    # now load the original
    ret_ref = clr.Reference[Family]()
    doc.LoadFamily(fam_doc_path, ret_ref)
    loaded_fam = ret_ref.Value
    # get the symbols from the original
    for sym_id in loaded_fam.GetFamilySymbolIds():
        fam_sym = doc.GetElement(sym_id)
        fam_sym_name = Element.Name.GetValue(fam_sym)
        sortable_sym = SmartSortableFamilyType(fam_sym_name)
        logger.debug('Importable Type: {}'.format(sortable_sym))
        symbol_list.add(sortable_sym)
    # okay. we have all the symbols. now rollback all the changes
Ejemplo n.º 26
0
it under the terms of the GNU General Public License version 3, as published by
the Free Software Foundation.

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 General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
'''

__window__.Close()
from Autodesk.Revit.DB import Transaction, Dimension

uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document

t = Transaction(doc, 'VIF dimensions')
t.Start()

for elId in uidoc.Selection.GetElementIds():
    el = doc.GetElement(elId)
    if isinstance(el, Dimension):
        if len(list(el.Segments)) > 0:
            for seg in el.Segments:
                seg.Below = 'VIF'
        else:
            el.Below = 'VIF'

t.Commit()
Ejemplo n.º 27
0
class Action():
    """
    Simplifies transactions by applying ``Transaction.Start()`` and
    ``Transaction.Commit()`` before and after the context.
    Automatically rolls back if exception is raised.

    >>> with Action('Move Wall'):
    >>>     wall.DoSomething()

    >>> with Action('Move Wall') as action:
    >>>     wall.DoSomething()
    >>>     assert action.status == ActionStatus.Started  # True
    >>> assert action.status == ActionStatus.Committed    # True

    """
    def __init__(self,
                 name=None,
                 clear_after_rollback=False,
                 show_error_dialog=False):
        self._rvt_transaction = Transaction(
            self.doc, name if name else DEFAULT_TRANSACTION_NAME)
        self._fail_hndlr_ops = self._rvt_transaction.GetFailureHandlingOptions(
        )
        self._fail_hndlr_ops.SetClearAfterRollback(clear_after_rollback)
        self._fail_hndlr_ops.SetForcedModalHandling(show_error_dialog)
        self._rvt_transaction.SetFailureHandlingOptions(self._fail_hndlr_ops)

    def __enter__(self):
        self._rvt_transaction.Start()
        return self

    def __exit__(self, exception, exception_value, traceback):
        if exception:
            self._rvt_transaction.RollBack()
            logger.error(
                'Error in Action Context. Rolling back changes. | {}:{}'.
                format(exception, exception_value))
        else:
            try:
                self._rvt_transaction.Commit()
            except Exception as errmsg:
                self._rvt_transaction.RollBack()
                logger.error(
                    'Error in Action Commit. Rolling back changes. | {}'.
                    format(errmsg))

    @property
    def name(self):
        return self._rvt_transaction.GetName()

    @name.setter
    def name(self, new_name):
        return self._rvt_transaction.SetName(new_name)

    @property
    def status(self):
        return ActionStatus.from_rvt_trans_stat(
            self._rvt_transaction.GetStatus())

    @staticmethod
    def carryout(name):
        """ Action Decorator

        Decorate any function with ``@Action.carryout('Action Name')``
        and the funciton will run within an Action context.

        Args:
            name (str): Name of the Action

        >>> @Action.carryout('Do Something')
        >>> def set_some_parameter(wall, value):
        >>>     wall.parameters['Comments'].value = value
        >>>
        >>> set_some_parameter(wall, value)
        """
        from functools import wraps

        def wrap(f):
            @wraps(f)
            def wrapped_f(*args, **kwargs):
                with Action(name):
                    return_value = f(*args, **kwargs)
                return return_value

            return wrapped_f

        return wrap

    def has_started(self):
        return self._rvt_transaction.HasStarted()

    def has_ended(self):
        return self._rvt_transaction.HasEnded()
Ejemplo n.º 28
0
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
"""

__doc__ = 'Adds "MAX." below the line for selected dimensions.'

__window__.Close()
from Autodesk.Revit.DB import Transaction, Dimension

uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document

t = Transaction(doc, 'Dimension MAX below')
t.Start()

for elId in uidoc.Selection.GetElementIds():
    el = doc.GetElement(elId)
    if isinstance(el, Dimension):
        if len(list(el.Segments)) > 0:
            for seg in el.Segments:
                if not seg.Below is None:
                    seg.Below += 'MAX.'
                else:
                    seg.Below = 'MAX.'
        else:
            seg = el
            if not seg.Below is None:
                seg.Below += 'MAX.'
Ejemplo n.º 29
0
See this link for a copy of the GNU General Public License protecting this package.
https://github.com/eirannejad/pyRevit/blob/master/LICENSE
'''

__window__.Width = 1100
from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, View, Transaction

uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document

cl_views = FilteredElementCollector(doc)
views = cl_views.OfCategory(
    BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements()

vtbd = []

for v in views:
    if v.IsTemplate:
        print('ID: {1}		{0}'.format(
            v.ViewName,
            str(v.Id).ljust(10),
        ))
        vtbd.append(v)

t = Transaction(doc, 'Remove All View Templates')
t.Start()

for v in vtbd:
    doc.Delete(v.Id)

t.Commit()
Ejemplo n.º 30
0
def collect_views(input_doc):
    return FilteredElementCollector(input_doc) \
           .OfCategory(BuiltInCategory.OST_Views) \
           .WhereElementIsNotElementType() \
           .ToElements()


# current document views
curdoc_views = collect_views(doc)
curdoc_views_dict = {v.ViewName: v for v in curdoc_views}

for open_doc in all_docs:
    if open_doc is not doc and not open_doc.IsLinked:
        views = collect_views(open_doc)
        t = Transaction(open_doc, 'Match Title on Sheets')
        t.Start()
        for v in views:
            if v.ViewName in curdoc_views_dict:
                tos_param = v.LookupParameter('Title on Sheet')
                matching_view = curdoc_views_dict[v.ViewName]
                orig_tos_param = matching_view.LookupParameter(
                    'Title on Sheet')

                if orig_tos_param and tos_param:
                    print('Matching Views: {} / {}'.format(
                        v.ViewName, matching_view.ViewName))
                    print('{} = {}'.format(tos_param.AsString(),
                                           orig_tos_param.AsString()))
                    tos_param.Set(orig_tos_param.AsString())
        t.Commit()