Пример #1
0
def dialogManager():
    '''dialogbox to manage updater state from a ribbon button'''
    #scope when dialogManager is called
    doc = __revit__.ActiveUIDocument.Document
    
    # registering state
    app_dmu = UpdaterRegistry.IsUpdaterRegistered(myroomupdater.GetUpdaterId())
    doc_dmu = UpdaterRegistry.IsUpdaterRegistered(myroomupdater.GetUpdaterId(), doc)

    # note : the global will be unregistered when the last document is unregistered
    # note2 : look at IsUpdaterEnabled and EnableUpdater/DisableUpdater too 
    # note3 : enabled or not, an updater may be suspended by Revit for misbehaving
    
    # build the dialog box
    box = TaskDialog('Dynamic Model Updaters')
    box.MainInstruction  = 'DoubleHeight Updater Manager'

    box.MainContent = '- Document Updater is :{0} Registered'.format(' NOT' * (not doc_dmu))
    box.MainContent += '\n- Global Updater is :{0} Registered'.format(' NOT' * (not app_dmu))
    
    # add command options
    if doc_dmu:
        box.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, 'Disable document Updater')
        
    else :
        box.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, 'Enable document Updater')
        
    if app_dmu:
        box.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, 'Disable all documents Updater ')

    # box.FooterText = 'Add comments in the footer'

    # close button to abort 
    box.CommonButtons = TaskDialogCommonButtons.Close

    # show the dialogbox and capture the answer
    answer = box.Show()

    # 1st option : disable updater for current document
    if answer == TaskDialogResult.CommandLink1:
        
        doc_unregister(doc)
        
    # 2nd option : register the current doc
    elif answer == TaskDialogResult.CommandLink2:
        
        doc_register(doc)
        
    # 3rd option : disable updater for all opened documents
    elif answer == TaskDialogResult.CommandLink3:
        
        global_unregister()
Пример #2
0
def selectRoomByNameHeight(text, height,bool1,int1, date1):
    '''Select all Rooms in this view containing 'Name' and the given limited height \
(only the two first parameters matter in this example) :'''
    uidoc = __revit__.ActiveUIDocument
    doc = uidoc.Document
    view = uidoc.ActiveGraphicalView
    roomfilter = RoomFilter()
    rooms = FilteredElementCollector(doc, view.Id).WherePasses(roomfilter).ToElements()
    select = [room.Id for room in rooms if room.UnboundedHeight <= height and \
         text.lower() in Element.Name.GetValue(room).lower()]
         
    uidoc.Selection.SetElementIds(List[ElementId](select))
    
    #feedback test
    TaskDialog.Show('Test feedback', 
        '{0} Rooms named "{1}" UnboundedHeight < "{2}":\
            \nbool: {3}\n number{4}\n date :{5}'.format(
                len(select), text, height, bool1, int1, date1))
Пример #3
0
def get_views():
    selection = uidoc.Selection.GetElementIds()
    views_selected = filter(
        lambda e: doc.GetElement(e).GetType().IsSubclassOf(View), selection)

    if len(views_selected) == 0:
        error_text = "No views selected.\nTextnotes from all project views will be exported."

        q = TaskDialog.Show(
            __title__, error_text,
            TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel)

        if str(q) == "Cancel":
            return
        else:
            return None

    else:
        return views_selected
Пример #4
0
def level_dependent():
    """By level"""
    levels_all = all_levels()
    if len(levels_all) < 2:
        print(
            "At least 2 levels should be created in a project to check dependent. Create one more level and run again"
        )
        return

    selected_levels = select_levels_dialog(levels_all)
    if not selected_levels:
        print("Nothing selected")
        return

    results = {}
    for e in selected_levels:
        views_to_close = check_dependent_views(e)
        if len(views_to_close) > 0:

            q = TaskDialog.Show(
                __title__, "These views will be closed:\n%s" % ", ".join(
                    map(lambda x: doc.GetElement(x.ViewId).Name,
                        views_to_close)),
                TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel)

            if str(q) == "Cancel":
                break

            if len(uidoc.GetOpenUIViews()) == len(views_to_close):
                uidoc.ActiveView = starting_view()

            for v in views_to_close:
                v.Close()

        t = Transaction(doc, "Check level " + e.Name)
        t.Start()
        elements = doc.Delete(e.Id)
        t.RollBack()

        results[e.Name] = group_by_type(elements)

    return results
Пример #5
0
def AppDialogShowing(sender, args):
    dialogId = args.DialogId
    promptInfo = "A Revit dialog will be opened.\n"
    promptInfo += "The DialogId of this dialog is " + dialogId + "\n"
    promptInfo += "If you don't want the dialog to open, please press cancel button"

    taskDialog = TaskDialog("Revit")
    taskDialog.Id = "Customer DialogId"
    taskDialog.MainContent = promptInfo
    buttons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel
    taskDialog.CommonButtons = buttons
    result = taskDialog.Show()
    if TaskDialogResult.Cancel == result:
        args.OverrideResult(1)
    else:
        args.OverrideResult(0)
Пример #6
0
def pick_chain(doc):
    selection = revit.selection.get_selection()
    # last_selection = selection.element_ids
    selected_curve = revit.pick_element("Select curves to sort by")

    if not selected_curve:
        forms.alert("Nothing selected")
        return None, None

    logger.debug("selected_curve: %s" % str(selected_curve.Id))

    try:
        selected_curve.GeometryCurve
    except:
        forms.alert(
            "Error! Selected element is not a Curve.\nOr it have no GeometryCurve parameter"
        )
        return None, None

    if not selected_curve.GeometryCurve.IsBound:
        forms.alert("Error! Curve cannot be bounded")

    # chain
    selection_list_sorted, selection_list_sorted_isreversed = _find_curve_chain(
        selected_curve, doc)
    logger.debug("selection_list_sorted: %s" % selection_list_sorted)
    if len(selection_list_sorted) > 1:
        # TODO undo
        selection.set_to(selection_list_sorted)
        form_result = TaskDialog.Show(
            "Select curve chain?",
            "Curve chain found. Use it?\nIf not, only one selected curve will be used",
            TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No)

        # selection.set_to(last_selection)
        if str(form_result) == "Yes":
            return selection_list_sorted, selection_list_sorted_isreversed
    logger.debug("Selected_curve: %s" % [selected_curve.Id])
    return [selected_curve.Id], None
Пример #7
0
def unjoin(pairs):
    # print(pairs)

    # rng = range(len(selection))
    # checked_pairs = []
    # joined_pairs = []
    c = 0

    # for x in rng:
    #     for y in rng:
    #         if x == y:
    #             continue
    #         _p = sorted([x,y])
    #         _t = (_p[0],_p[1])
    #         if _t in checked_pairs:
    #             continue

    #         checked_pairs.append(_t)
    #         eid1 = selection[_p[0]]
    #         eid2 = selection[_p[1]]
    #         e1,e2 = doc.GetElement(eid1),doc.GetElement(eid2)
    #         joined = JoinGeometryUtils.AreElementsJoined(doc,e1,e2)
    #         if joined:
    #             joined_pairs.append((e1,e2))

    if len(pairs) > 0:
        t = Transaction(doc)
        t.Start("UnjoinSelected")
        for p in pairs:
            e1 = doc.GetElement(ElementId(p[0]))
            e2 = doc.GetElement(ElementId(p[1]))
            joined = JoinGeometryUtils.AreElementsJoined(doc, e1, e2)
            if joined:

                JoinGeometryUtils.UnjoinGeometry(doc, e1, e2)
                c += 1
        t.Commit()
    TaskDialog.Show("R", "%d пар элементов разъединены" % c)
Пример #8
0
    def _create_pattern(self, domain):
        pat_lines = []
        for det_line in self.selected_lines:
            geom_curve = det_line.GeometryCurve
            if type(geom_curve) in accpeted_curves:
                tes_points = [tp for tp in geom_curve.Tessellate()]
                for xyz1, xyz2 in pairwise(tes_points):
                    pat_lines.append(self._make_pattern_line(xyz1, xyz2))

            elif isinstance(geom_curve, Line):
                pat_lines.append(
                    self._make_pattern_line(geom_curve.GetEndPoint(0),
                                            geom_curve.GetEndPoint(1)))

        call_params = 'Name:{} Model:{} FilledRegion:{} Domain:{} Lines:{}'.format(
            self.pat_name, self.is_model_pat, self.create_filledregion, domain,
            pat_lines)
        logger.debug(call_params)
        patmaker.make_pattern(self.pat_name,
                              pat_lines,
                              domain,
                              model_pattern=self.is_model_pat,
                              create_filledregion=self.create_filledregion)
        TaskDialog.Show('pyRevit', 'Pattern {} created.'.format(self.pat_name))
Пример #9
0
__window__.Visible = False
from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, Transaction
from Autodesk.Revit.UI import TaskDialog
from Autodesk.Revit.UI import UIApplication
doc = __revit__.ActiveUIDocument.Document
collector = FilteredElementCollector(doc).OfCategory(
    BuiltInCategory.OST_RasterImages).ToElements()
coll = FilteredElementCollector(doc).OfCategory(
    BuiltInCategory.OST_RasterImages).ToElementIds()
try:
    catId = collector[0].Category.Id
    if collector[0].IsHidden(doc.ActiveView) == True:
        t = Transaction(doc, 'Unhide Raster Image files')
        t.Start()
        doc.ActiveView.UnhideElements(coll)
        t.Commit()
    else:
        t = Transaction(doc, 'Hide Raster Image files')
        t.Start()
        doc.ActiveView.HideElements(coll)
        t.Commit()
except Exception:
    TaskDialog.Show("Missing Raster Image", "No Raster Image files loaded")
Пример #10
0
from pyrevit import forms

__doc__ = 'Print all the  pipe slopes and element id in selection, please make a selection to run'


def isclose(a, b, rel_tol=1e-08, abs_tol=1e-03):
    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)


def isnotclose(a, b, rel_tol=1e-08, abs_tol=1e-03):
    return abs(a - b) >= max(rel_tol * max(abs(a), abs(b)), abs_tol)


sel_element = Selection.get_selected_elements(doc)
if len(sel_element) == 0:
    TaskDialog.Show('Warning', 'Please make selection first')
else:
    outprint = script.get_output()
    pipes = []
    for i in sel_element:
        if i.Category.Name == 'Pipes':
            pipes.append(i)
    print('Found ' + str(len(pipes)) + ' pipes')
    # pipes = FilteredElementCollector(doc).OfClass(Pipe).ToElements()
    for p in pipes:
        slope = p.LookupParameter('Slope').AsDouble()
        print(
            format(outprint.linkify(p.Id)) + '     SLOPE: ' + str(slope * 12) +
            '/foot')
    print('End')
Пример #11
0
def error(msg):
    TaskDialog.Show('pyrevit', msg)
    sys.exit(0)
doc = __revit__.ActiveUIDocument.Document

# create an instance
my_updater = MyRoomUpdater(app.ActiveAddInId)

# registering state
app_dmu = UpdaterRegistry.IsUpdaterRegistered(my_updater.GetUpdaterId())
doc_dmu = UpdaterRegistry.IsUpdaterRegistered(my_updater.GetUpdaterId(), doc)

# note : the global will be unregistered when the last document is unregistered
# note2 : look at IsUpdaterEnabled and EnableUpdater/DisableUpdater too 
# note3 : enabled or not, an updater may be suspended by Revit for misbehaving


# build the dialog box
box = TaskDialog('Dynamic Model Updaters')
box.MainInstruction  = 'DoubleHeight Updater Manager'

box.MainContent = '- Document Updater is :{0} Registered'.format(' NOT' * (not doc_dmu))
box.MainContent += '\n- Global Updater is :{0} Registered'.format(' NOT' * (not app_dmu))


# add command options
if doc_dmu:
    box.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, 'Disable document Updater')
    
else :
    box.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, 'Enable document Updater')
    
if app_dmu:
    box.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, 'Disable all documents Updater ')
Пример #13
0
if isinstance(curview, View3D) and curview.IsSectionBoxActive:
    try:
        ref = uidoc.Selection.PickObject(ObjectType.Face)
        el = doc.GetElement(ref.ElementId)
        face = el.GetGeometryObjectFromReference(ref)
        box = curview.GetSectionBox()
        norm = face.ComputeNormal(UV(0, 0)).Normalize()
        boxNormal = box.Transform.Basis[0].Normalize()
        angle = norm.AngleTo(boxNormal)
        axis = XYZ(0, 0, 1.0)
        origin = XYZ(box.Min.X + (box.Max.X - box.Min.X) / 2,
                     box.Min.Y + (box.Max.Y - box.Min.Y) / 2, 0.0)
        if norm.Y * boxNormal.X < 0:
            rotate = Transform.CreateRotationAtPoint(axis, Math.PI / 2 - angle,
                                                     origin)
        else:
            rotate = Transform.CreateRotationAtPoint(axis, angle, origin)
        box.Transform = box.Transform.Multiply(rotate)
        t = Transaction(doc, 'Orient Section Box to Face')
        t.Start()
        curview.SetSectionBox(box)
        uidoc.RefreshActiveView()
        t.Commit()
    except:
        pass
elif isinstance(curview, View3D) and not curview.IsSectionBoxActive:
    TaskDialog.Show("pyRevit", "The section box for View3D isn't active.")
else:
    TaskDialog.Show("pyRevit",
                    "You must be on a 3D view for this tool to work.")
Пример #14
0
        fRule = FilterStringRule(pvp, fnrv, values[count], True)
    elif 'Interger' in str(i.StorageType):
        fnrv = FilterNumericEquals()
        fRule = FilterIntegerRule(pvp, fnrv, int(values[count]))
    elif 'Double' in str(i.StorageType):
        fnrv = FilterNumericEquals()
        fRule = FilterDoubleRule(pvp, fnrv, float(values[count]), 0.001)
    elif 'ElementId' in str(i.StorageType):
        fnrv = FilterNumericEquals()
        fRule = FilterElementIdRule(pvp, fnrv, ElementId(int(values[count])))
    fRules.append(fRule)
    count += 1
# Filter all elements based on parameter values selected
paramFilters = ElementParameterFilter(fRules)
ele = filter.WherePasses(paramFilters).ToElements()
elements = []
for i in ele:
    elements.append(i)

# Task Dialogue Creation
dialog = TaskDialog('Warning')
dialog.CommonButtons = TaskDialogCommonButtons.Ok
dialog.DefaultButton = TaskDialogResult.Ok
dialog.Title = 'Warning'
dialog.MainInstruction = 'You are about to select ' + str(
    len(elements)) + ' elements'
bool = dialog.Show()
if str(bool) == 'Ok':
    revit.get_selection().set_to(elements)
else:
    pass
Пример #15
0
 #Call CoolProp to get fluid properties and convert it to internal units if necessary
 temperature = 273.15 + i
 viscosity = UnitUtils.ConvertToInternalUnits(
     PropsSI('V', 'T', t_init + i, 'P', pressure, fluid),
     DisplayUnitType.DUT_PASCAL_SECONDS)
 density = UnitUtils.ConvertToInternalUnits(
     PropsSI('D', 'T', t_init + i, 'P', pressure, fluid),
     DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER)
 #Catching exceptions and trying to overwrite temperature if asked by user in the TaskDialog
 try:
     fluid_type.AddTemperature(
         FluidTemperature(temperature, viscosity, density))
 except ArgumentException:
     result = TaskDialog.Show(
         "Error",
         "Temperature already exist, do you want to overwrite it ?",
         TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No
         | TaskDialogCommonButtons.Cancel, TaskDialogResult.Yes)
     if result == TaskDialogResult.Yes:
         try:
             fluid_type.RemoveTemperature(temperature)
             fluid_type.AddTemperature(
                 FluidTemperature(temperature, viscosity, density))
         except ArgumentException:
             TaskDialog.Show(
                 "Overwrite error",
                 "Temperature is currently in use and cannot be overwritten"
             )
     elif result == TaskDialogResult.No:
         pass
     else:
Пример #16
0
            # print v.ViewTemplateId.IntegerValue
            # v.ViewTemplateId = t.Id
            # print v.ViewTemplateId.IntegerValue
            ii += 1
            break
            
    else:
      # will be called if the previous loop did not end with a `break` 
      continue
if ii == 0: print "None"
if ii !=0: print "Total Details/Sections Modified: " + str(i)

if i == ii == 0:
    __window__.Close()
    trans.RollBack()
    TaskDialog.Show("You are amazing!  None of the Drafting Views or Sections on sheets were missing templates. You should celebrate.")
    sys.exit() 
# Get the application and document from external command data.
# app = commandData.Application.Application;
# activeDoc = commandData.Application.ActiveUIDocument.Document;

# Creates a Revit task dialog to communicate information to the user.
mainDialog = TaskDialog("SilmanApps")
mainDialog.MainInstruction = "I recommend reviewing the results before keeping them."
mainDialog.MainContent = "Click on the Revit icon on the taskbar and switch windows to view."

# Add commmandLink options to task dialog
mainDialog.AddCommandLink(Autodesk.Revit.UI.TaskDialogCommandLinkId.CommandLink1,"Undo changes?")
mainDialog.AddCommandLink(Autodesk.Revit.UI.TaskDialogCommandLinkId.CommandLink2,"Keep Changes")

# Set footer text. Footer text is usually used to link to the help document.
    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)
                        print('-- PARAMETER VALUE SET TO INTEGER 0')
                    elif param.StorageType == StorageType.String:
                        doc.FamilyManager.Set(param, '')
                        print('-- PARAMETER VALUE SET TO EMPTY STRING.')
                    else:
                        print('-- PARAMETER TYPE IS UNKNOWN. CAN NOT RESET VALUE.')
                except Exception as e:
                    print e
                    continue
            else:
                print('PARAMETER IS BEING USED AS A LABEL. PARAMETER VALUE WON\'T BE RESET')
            continue
    print('\n\nALL DONE.....................................')
    t.Commit()
else:
    __window__.Close()
    TaskDialog.Show('pyRevit', 'This script works only on an active family editor.')
Author: Gui Talarico | github.com/gtalarico

This file is shared on www.revitapidocs.com
For more information visit http://github.com/gtalarico/revitapidocs
License: http://github.com/gtalarico/revitapidocs/blob/master/LICENSE.md
"""

from Autodesk.Revit.DB import Transaction
from Autodesk.Revit.UI import TaskDialog

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

if not doc.IsFamilyDocument:
    TaskDialog.Show('Message', 'Must be in Family Document.')

else:
    family_types = [x for x in doc.FamilyManager.Types]
    sorted_type_names = sorted([x.Name for x in family_types])
    current_type = doc.FamilyManager.CurrentType

    # Iterate through sorted list of type names, return name of next in list
    for n, type_name in enumerate(sorted_type_names):
        if type_name == current_type.Name:
            try:
                next_family_type_name = sorted_type_names[n + 1]
            except IndexError:
                # wraps list back to 0 if current is last
                next_family_type_name = sorted_type_names[0]
Пример #19
0
This file is shared on www.revitapidocs.com
For more information visit http://github.com/gtalarico/revitapidocs
License: http://github.com/gtalarico/revitapidocs/blob/master/LICENSE.md
"""
from Autodesk.Revit.DB import Transaction, Element
from Autodesk.Revit.DB import FilteredElementCollector
from Autodesk.Revit.UI import TaskDialog
from System.Collections.Generic import List

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

# GET ALL ROOMS IN MODEL
rooms = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms)
ub_rooms = []

for r in rooms:
    if r.Area > 0:
        pass
    else:
        ub_rooms.append(r)

# SELECT UNBOUND ROOMS
collection = List[ElementId]([r.Id for r in ub_rooms])
selection = uidoc.Selection
selection.SetElementIds(collection)

TaskDialog.Show('Unbound Rooms',
                "{} unbound rooms selected".format(len(ub_rooms)))
Пример #20
0
currentChoice = []
for i in get_selected_elements(doc):
    currentChoice.append(Reference(i))
result = 'Retry'
while result == 'Retry':
    conduitFilter = ConduitSelectionFilter()
    choices = uidoc.Selection
    try:
        conduitRef = choices.PickObjects(ObjectType.Element, conduitFilter,
                                         "Pick Conduit", currentChoice)
        currentChoice = conduitRef
        length = 0
        for i in conduitRef:
            conduit = doc.GetElement(i.ElementId)
            if conduit.Category.Name == 'Conduits':
                length += conduit.LookupParameter("Length").AsDouble()
            else:
                angle = conduit.LookupParameter("Angle").AsDouble()
                radius = conduit.LookupParameter("Bend Radius").AsDouble()
                length += radius * angle
                # Backup Length Parameter for fittings, mostly not correct
                # length += conduit.LookupParameter("Conduit Length").AsDouble()
        result = str(
            TaskDialog.Show(
                "Measure", "Overall Length " +
                str(QuestionableMath.FeettoInchNotRounded(length)) + " feet",
                TaskDialogCommonButtons.Retry))
        uidoc.RefreshActiveView()
    except:
        result = "Cancel"
Пример #21
0
    if v.IsTemplate and 'master' not in v.ViewName.lower():
        vtemp.add(v.Id.IntegerValue)
    else:
        views.append(v)

for v in views:
    vtid = v.ViewTemplateId.IntegerValue
    if vtid > 0:
        usedvtemp.add(vtid)

unusedvtemp = vtemp - usedvtemp

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

for vid in unusedvtemp:
    view = doc.GetElement(ElementId(vid))
    print view.ViewName

res = TaskDialog.Show(
    'pyrevit', 'Are you sure you want to remove these view templates?',
    TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.Cancel)

if res == TaskDialogResult.Yes:
    for v in unusedvtemp:
        doc.Delete(ElementId(v))
else:
    print('----------- Purge Cancelled --------------')

t.Commit()
Пример #22
0
# Import Revit DB
from Autodesk.Revit.DB import OverrideGraphicSettings, Transaction

# Store current document to variable
doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument

# Retrieve current view
activeView = doc.ActiveView

# Retrieve all categories in the document
docCat = doc.Settings.Categories

# Show task dialog to inform user
TaskDialog.Show("Select elements",
                "Select elements from categories to isolate")

# Select elements
objType = ObjectType.Element
selection = uidoc.Selection.PickObjects(
    objType, "Pick elements to isolate with transparency")

# Store categories of the selected elements
categories = []
for e in selection:
    elem = doc.GetElement(e.ElementId)
    cat = doc.GetElement(e.ElementId).Category.Name
    # Check if element is group or assembly to extract elements
    if cat == "Assemblies" or cat == "Model Groups":
        ids = elem.GetMemberIds()
        # Get elements category inside groups or assemblies
Пример #23
0
def alert(msg):
    TaskDialog.Show('RevitPythonShell', msg)
Пример #24
0
"""Just a script that
Displays Hello world."""

# tested versions: 2018

__title__ = 'Hello\nWorld'
__author__ = 'Michael Spencer Quinto'

# __context__ = 'Selection'
# Tools are active even when there are no documents available/open in Revit
# __context__ = 'zerodoc'

from Autodesk.Revit.UI import TaskDialog

TaskDialog.Show('spencerCorePyRevut', 'Hello World!')

if __name__ == '__main__':
    from sample import sample_func
    print(sample_func())
Пример #25
0
This file is part of pyRevit repository at https://github.com/eirannejad/pyRevit

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__ = 'Print the full path to the central model (if model is workshared).'

from Autodesk.Revit.DB import ModelPathUtils
from Autodesk.Revit.UI import TaskDialog

doc = __revit__.ActiveUIDocument.Document

if doc.IsWorkshared:
    print(
        ModelPathUtils.ConvertModelPathToUserVisiblePath(
            doc.GetWorksharingCentralModelPath()))
else:
    __window__.Close()
    TaskDialog.Show('pyrevit', 'Model is not workshared.')
Пример #26
0
    # if the config file exists then read values and apply
    if op.exists(configfile):
        try:
            with open(configfile, 'w') as udfile:
                cparser = settingsParser.ConfigParser()
                cparser.add_section(globalsectionname)
                cparser.set(globalsectionname, "verbose",
                            "true" if verbose else "false")
                cparser.add_section(initsectionname)
                cparser.set(initsectionname, "logScriptUsage",
                            "true" if logScriptUsage else "false")
                cparser.set(initsectionname, "archivelogfolder",
                            archivelogfolder)
                cparser.write(udfile)
        except:
            raise ErrorWritingUserSettings
    else:
        raise MasterSettingsIsOverriding


try:
    load_user_settings()
    settingsWindow().showwindow()
except ErrorReadingUserSettings:
    TaskDialog.Show('pyRevit', 'Error reading settings file.')
except ErrorWritingUserSettings:
    TaskDialog.Show('pyRevit', 'Error writing settings file.')
except MasterSettingsIsOverriding:
    TaskDialog.Show('pyRevit', 'Settings are set by the master settings file and '\
                               'can not be changed from this window.')
Пример #27
0
 def alert(msg):
     TaskDialog.Show('pyrevit', msg)
Пример #28
0
    sel = uidoc.Selection.PickObjects(ObjectType.Element)
    for el in sel:
        selViewports.append(doc.GetElement(el))

    if len(selViewports) > 0:
        with Transaction(doc, 'Move Viewports') as t:
            t.Start()
            for sht in selSheets:
                for vp in selViewports:
                    if isinstance(vp, Viewport):
                        viewId = vp.ViewId
                        vpCenter = vp.GetBoxCenter()
                        vpTypeId = vp.GetTypeId()
                        cursheet.DeleteViewport(vp)
                        nvp = Viewport.Create(doc, sht.Id, viewId, vpCenter)
                        nvp.ChangeTypeId(vpTypeId)
                    elif isinstance(vp, ScheduleSheetInstance):
                        nvp = ScheduleSheetInstance.Create(
                            doc, sht.Id, vp.ScheduleId, vp.Point)
                        doc.Delete(vp.Id)

            t.Commit()
    else:
        TaskDialog.Show('pyRevit', 'At least one viewport must be selected.')
elif len(selSheets) == 0:
    TaskDialog.Show(
        'pyRevit',
        'You must select at least one sheet to add the selected viewports to.')
elif len(selSheets) > 2:
    TaskDialog.Show('pyRevit', 'Maximum of two sheets can only be selected.')
Пример #29
0
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 Viewport
from Autodesk.Revit.UI import TaskDialog

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

#Opens the associated view with the selected viewport on a sheet.
if len(selection) > 0 and isinstance(selection[0], Viewport):
    vp = selection[0]
    vpid = vp.ViewId
    view = doc.GetElement(vpid)
    uidoc.ActiveView = view
else:
    TaskDialog.Show('pyRevit', 'Select a Viewport first')
    vsList = firstEl.ViewSpecific

    for r in list:
        if r.GetTypeId() == TID:
            set.append(r.Id)
            if vsList:
                ovname = doc.GetElement(r.OwnerViewId).ViewName
                if ovname in vsItems:
                    vsItems[ovname].append(r)
                else:
                    vsItems[ovname] = [r]
            else:
                modelItems.append(r)

    if vsList:
        for ovname, items in vsItems.items():
            print('OWNER VIEW: {0}'.format(ovname))
            for r in items:
                print('\tID: {0}\t{1}'.format(r.Id,
                                              r.GetType().Name.ljust(20)))
            print('\n')
    else:
        print('SELECTING MODEL ITEMS:')
        for el in modelItems:
            print('\tID: {0}\t{1}'.format(r.Id, r.GetType().Name.ljust(20)))

    uidoc.Selection.SetElementIds(List[ElementId](set))
else:
    __window__.Close()
    TaskDialog.Show('pyRevit', 'At least one object must be selected.')
elements = get_selected_elements()
floor_types = get_floor_types()

chosen_type_name = 'Floor 1'
# If can't find matchign floor type name will use the first one found.
type_id = floor_types.get(chosen_type_name, floor_types.values()[0])

#  This is not needed but helps package needed elements to make floor
NewFloor = namedtuple('NewFloor', ['type_id', 'boundary', 'level_id'])
new_floors = []
room_boundary_options = SpatialElementBoundaryOptions()

for element in elements:
    if isinstance(element, Room):
        room = element
        room_level_id = room.Level.Id
        # List of Boundary Segment comes in an array by itself.
        room_boundary = room.GetBoundarySegments(room_boundary_options)[0]
        new_floor = NewFloor(type_id=type_id, boundary=room_boundary,
                             level_id=room_level_id)
        new_floors.append(new_floor)

if not new_floors:
    TaskDialog.Show('MakeFloors', 'You need to select at least one room.')
    __window__.Close()
    sys.exit(0)

for new_floor in new_floors:
    view = make_floor(new_floor)
Пример #32
0
        vor = ViewOrientation3D(XYZ(vo.eyex, vo.eyey, vo.eyez),
                                XYZ(vo.upx, vo.upy, vo.upz),
                                XYZ(vo.forwardx, vo.forwardy, vo.forwardz))

        av = uidoc.ActiveGraphicalView
        avui = uidoc.GetOpenUIViews()[0]
        if isinstance(av, View3D):
            with Transaction(doc, 'Paste Section Box Settings') as t:
                t.Start()
                av.SetSectionBox(sb)
                av.SetOrientation(vor)
                t.Commit()
            avui.ZoomToFit()
        else:
            TaskDialog.Show(
                'pyrevit',
                'You must be on a 3D view to paste Section Box settings.')
    except:
        TaskDialog.Show(
            'pyrevit',
            'Can not find any section box settings in memory:\n{0}'.format(
                datafile))

elif selected_switch == 'Viewport Placement on Sheet':
    """
    Copyright (c) 2016 Gui Talarico

    CopyPasteViewportPlacemenet
    Copy and paste the placement of viewports across sheets
    github.com/gtalarico