def UPLOAD_WorksetsMain(sh): ri = re #ci = ce awssDBxl = {} while(True): r = sh.Range[rg(ri, ce)] proj = r.Text if proj: ids = {int(sh.Range[rg(ri, ce + 1)].Value2): \ int(sh.Range[rg(ri, ce + 2)].Value2)} if not proj in awssDBxl: tmpbdws = {} tmpbdpj = {proj:tmpbdws} awssDBxl.update(tmpbdpj) awssDBxl[proj].update(ids) else: config.UpdateDB(awssDBxl) log = "" if sw.isEvenHandlerAdded(): log = "Attention!\n\nThe tool is or was activated, so must restart Revit to reload new data!\n\n" log += "But you can use the ActiveView button, without restarting Revit. " log += "(ActiveView button set the workset for the Active View individually.)" Alert(log, title="neoCL | Auto Workset Set", header="Update of config file done!") return ri += 1 ### END : UPLOAD TO FILE #############################################
def AlertSelection(els): if len(els) < 1: Alert( 'No elements selected!\nSelect elements before run.\nYou can select elements in Project Browser also.', title="neoCL | Edited By", header="Any elements found!") return False else: return True
def Editors(): els = ui.Selection() if AlertSelection(els): if revit.doc.IsWorkshared: ExportToExcel(els) else: Alert("Can't get information from a non Workshared document.", title="neoCL | Edited By", header="Warning")
def ExportActiveScheduleViewToExcel(): scView = uidoc.ActiveView if scView.ViewType != DB.ViewType.Schedule: Alert( "Active View is not a Schedule!\nOpen a View Schedule and activate it, before run.", title="neoCL | Open Schedule in Excel", header="Can't Export to Excel!") return False else: ExportThisScheduleViewToExcel(scView)
def SetFocus(els, cancelSelect=False): try: eids = List[ElementId](GetListOfIds(els)) if not cancelSelect: uidoc.Selection.SetElementIds(eids) uidoc.ShowElements(eids) except: Alert("Can't set focus!", title="neoCL | Selection", header="Any elements found!")
def runcmd(cmd, msg, recallCL=False): if cmd == 'p': from rpw.ui.forms import Alert Alert('Check next versions.', title="neoCL | Printer", header="Not available yet...") #from lib.printer import neo_print_main as printer #printer.Main() else: from neocl import unknowncmd unknowncmd(cmd, recallCL, getcmdlist())
def RemoveAnnotationFromSelection(): els = ui.Selection() catTypes = [x for x in GetAllCatTypes() if (x not in ['Annotation'])] els = FilterCategoryType(els, catTypes) msg = "Any elements non Annotantion in selection." if AlertSelection(els, msg): try: eids = List[ElementId](GetListOfIds(els)) uidoc.Selection.SetElementIds(eids) except: Alert("Can't create new selection!", title="neoCL | Selection", header="Error trying to select...")
def __init__(self, filePath, uidoc): self.filePath = filePath self.uidoc = uidoc try: self.filereader = StreamReader( filePath ) self.uidoc.Application.Application.OpenSharedParameterFile() except: Alert( 'Check Your Shared Parameters File Path', title="Error", header="Invalid Shared Parameters File", exit=True ) self.temp = os.environ['USERPROFILE'] + "\\AppData\\Local\\temp.txt"
def switch(): onoff = not isOn() setOnOff(onoff) script.toggle_icon(onoff) if onoff: #prevent multiple additions to eventhandler while switching on\off (remove if else (delete handler) works...) if not isEvenHandlerAdded(): __revit__.ViewActivated += EventHandler[ViewActivatedEventArgs]( awss) script.set_envvar(AUTO_WORKSET_SET_EVENTADDED, True) f.AutoSetWorkset() Alert('Auto Workset Set is activated!', title="neoCL | Auto Workset Set", header="neoCL") else: #does this line unloads eventhandler? __revit__.ViewActivated -= EventHandler[ViewActivatedEventArgs](awss) __revit__.ViewActivated -= awss
def runcmd(cmd, msg, recallCL=False): import imp ipath = GetMainDir() ipath += r"\neoCL.tab\pyRevit Scripts (non-neoCL).panel" if cmd == '_pysv': from rpw.ui.forms import Alert mg = "Can't call it from neoCL, you need to call this script from ribbon." Alert(mg, "non-neoCL Scripts", "pyRevit Sync Views") elif cmd == '_pyst': ipath += r"\SyncViewSum.stack\Sum.pushbutton\script.py" imp.load_source("py", ipath) elif cmd == '_pydh': ipath += r"\smartalign.stack\Distribute.pulldown\Horizontal.pushbutton\script.py" imp.load_source("py", ipath) elif cmd == '_pydv': ipath += r"\smartalign.stack\Distribute.pulldown\Vertical.pushbutton\script.py" imp.load_source("py", ipath) elif cmd == '_pyahc': ipath += r"\smartalign.stack\Horizontal.pulldown\Align Center.pushbutton\script.py" imp.load_source("py", ipath) elif cmd == '_pyahl': ipath += r"\smartalign.stack\Horizontal.pulldown\Align Left.pushbutton\script.py" imp.load_source("py", ipath) elif cmd == '_pyahr': ipath += r"\smartalign.stack\Horizontal.pulldown\Align Right.pushbutton\script.py" imp.load_source("py", ipath) elif cmd == '_pyavc': ipath += r"\smartalign.stack\Vertical.pulldown\Align Center.pushbutton\script.py" imp.load_source("py", ipath) elif cmd == '_pyavb': ipath += r"\smartalign.stack\Vertical.pulldown\Align Bottom.pushbutton\script.py" imp.load_source("py", ipath) elif cmd == '_pyavt': ipath += r"\smartalign.stack\Vertical.pulldown\Align Top.pushbutton\script.py" imp.load_source("py", ipath) else: from neocl import unknowncmd unknowncmd(cmd, recallCL, getcmdlist())
def ExportThisScheduleViewToExcel(scView): tb = scView.GetTableData() data = tb.GetSectionData(DB.SectionType.Body) fRow = data.FirstRowNumber lRow = data.LastRowNumber fCol = data.FirstColumnNumber lCol = data.LastColumnNumber XL, wb = ap.getApp(True) sh = wb.Activesheet sh.Cells(1, 1).Value = "Exporting... please wait..." sh.Columns(1).AutoFit() try: sh.Name = "neoCL | " + scView.Name except: pass XL.Caption = "neoCL.Revit" xlRestore = xlFrezzer(XL) isError = False for rn in range(fRow, lRow + 1): for cn in range(fCol, lCol + 1): try: sh.Cells(rn + 1, cn + 1).Value = \ "'" + str(scView.GetCellText(DB.SectionType.Body, rn, cn)) except: isError = True FormatsExcel(sh, fRow, lRow, fCol, lCol) xlFrezzer(XL, True, xlRestore) if isError: Alert("Something went wrong!\nCheck the exported data!", title="neoCL | Open Schedule in Excel", header="Error(s) during process!")
#with revit.Transaction('Created Print Set'): # ...Transaction(doc, ' SomeText ') throws error FECviewsets = FilteredElementCollector(doc).OfClass(ViewSheetSet).ToElements() #Dictionary from FECviewsets, key=viewsheetset.Name : value=vss element allviewsets = {vss.Name: vss for vss in FECviewsets} # is a set, a dictionary is created t = Transaction(doc,"Create Viewset") t.Start() try: if textin.values["textbox1"] in allviewsets.keys(): if textin.values["checkbox1"]: # if override = True viewshsetting.CurrentViewSheetSet = allviewsets[textin.values["textbox1"]] viewshsetting.Delete() else: mess = 'SheetSet exists, \nset override to True' Alert('',title="Create ViewSheetSet - ERROR", header = mess, exit=True) t.RollBack() sys.exit() viewshsetting.CurrentViewSheetSet.Views = new_viewset viewshsetting.SaveAs(textin.values["textbox1"]) # throws ERROR if name exist mess1 = '"' + textin.values["textbox1"] + '" - ViewSheetSet \nwith %s views created.' \ %(new_viewset.Size) Alert('',title="Success", header = mess1) t.Commit() except: t.RollBack() #print("Error")
def convertStr(s): try: ret = int(s) except ValueError: ret = None return ret # Get the Excel file # t = Transaction(doc, 'Read Excel spreadsheet.') # t.Start() with db.Transaction('read xl sheet'): #Accessing the Excel applications. try: xlApp = System.Runtime.InteropServices.Marshal.GetActiveObject('Excel.Application') except: Alert('The Excel sheet must be open (the program failed because of a problem with Excel)', title = "Failed", exit = True) dicWs = {} count = 1 for i in xlApp.Worksheets: dicWs[i.Name] = i count += 1 components = [Label('Select the name of Excel sheet to import :'), ComboBox('combobox', dicWs), Label('Choose the units you used in your Excel sheet :'), ComboBox('combobox2', {'Meters': 3.048, 'Decimeters': 30.48, 'Centimeters': 304.8, 'Millimeters': 3048}), Label('Enter the number of points:'), TextBox('textbox', Text="11"), Separator(), Button('OK')]
doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument # 参数输入 components = [ Label('曲面偏移距离'), TextBox('OffsetDistance', Text="500"), Label('构件名称'), TextBox('FamilyName', Text="HB200*100"), Button('确定') ] form = FlexForm('根据曲面与垂直线创建结构', components) form.show() Value=form.values OffsetDistance=Value["OffsetDistance"] FamilyName=Value['FamilyName'] Alert('请选择基础面', title=__doc__) #pick Surface Picked= uidoc.Selection.PickObject(UI.Selection.ObjectType.Face,"选择面") PickedElementId=Picked.ElementId Picked_Selection=doc.GetElement(PickedElementId) PickedFaces=Picked_Selection.GetGeometryObjectFromReference(Picked) # CovertTo Dynamo type print(PickedFaces) DS_Face=PickedFaces.ToProtoType() print(DS_Face) #Offset Surface DS_Face_Offset=DS_Face[0].Offset(float(OffsetDistance))
"""Credits to non-neoCL scripts.""" __title__ = 'Credits' __author__ = '' from rpw.ui.forms import Alert mg = \ """This panel has scripts from other coders. Check all the useful scripts in their respective pyRevit extensions. [Autor\Package] Tool name [pyRevit] Sync Views [pyRevit] Sum Total [pyRevitPlus] Smart Align (Distribute\Horizontal\Vertical)""" Alert(mg, "neoCL", "Credits to non-neoCL Scripts")
def propGenerator(): flag = True while (flag): flag = False #height takes a int value in mm height = TextInput("Prop Generator", description="Please enter a integer value in mm:", default="0") #Input validation - accepthing only integers if height.isdigit(): #Max prop height according to RMD literature is 18m if int(height) > 18000: Alert("Prop height greater than 18m is not allowed", title="Prop Generator", header="User Input Error!", exit=False) flag = True member_list = [5400, 2700, 1800, 900, 450, 270, 90] prop = [["5400"], ["2700"], ["1800"], ["900"], ["450"], ["270"], ["90"], ["jacks", 0]] no_of_jacks = TextInput( "Prop Generator", description="Megashor Jack on one(1) end or both(2) ends: ", default="1") if no_of_jacks.isdigit(): if no_of_jacks == '1': lower_limit = 410 upper_limit = 620 prop[7][1] = 1 else: lower_limit = 820 upper_limit = 1240 prop[7][1] = 2 else: Alert("Please only enter a integer value for the prop height", title="Prop Generator", header="User Input Error!", exit=False) height = int(height) j = 0 for i in member_list: res = height % i count = 0 while ((height / i) > 1): if ((height - i > lower_limit) or (res > lower_limit)): count += 1 height -= i else: break prop[j].append(count) j += 1 else: Alert("Please only enter a integer value for the prop height", title="Prop Generator", header="User Input Error!", exit=False) flag = True print(prop) return prop
def neoAlert(content, title='Alert', header='', exit=False): # replace rpw alert for custom form in the future Alert(content, title, header, exit)
tile_length = sheet_length / row_qty first_tile_loc = DB.XYZ(0.825 / 12, 9.5 / 12, 0) first_tile_pt = first_tile_loc.Add( DB.XYZ(tile_width / 2, -(tile_length / 2), 0)) total_views = column_qty * row_qty total_sheets = math.ceil(len(views) / float(total_views)) Alert( 'Max tile is {}" wide by {}" tall\nIt can be placed {} times in {} columns and {} rows\n{} sheets will be needed to fit {} views' .format( tile_width * 12, tile_length * 12, total_views, column_qty, row_qty, int(total_sheets), len(source_elements), ), title="Legend PDF", header="Legend Tiling", ) view_groups = [ views[i:i + int(total_views)] for i in range(0, len(views), int(total_views)) ] order_groups = [ order[i:i + int(total_views)] for i in range(0, len(order), int(total_views)) ]
sys.exit() familyTypes = [] for elementId in duplicates: familyTypes.append(_(elementId).get('Family and Type')) dialog = SelectType(list(set(familyTypes)), 'Select family types to be purged') selectedTypeIds = dialog.show(True) typeIdsInteger = [] if not selectedTypeIds: sys.exit() for typeId in selectedTypeIds: typeIdsInteger.append(typeId.IntegerValue) transaction = revitron.Transaction() # Purge twice to also get the nested family instances.. # The first pass will remove always the younger element, the second pass will get # a new warning list with all the duplicates that couldn't be remove in the first pass # (which must be shared families inside another family). # The second run will then remove always the older instances (getDuplicateInstances(True)). deletedCount = purge(duplicates, typeIdsInteger) deletedCount = deletedCount + purge( revitron.Document().getDuplicateInstances(True), typeIdsInteger, 'Purging duplicate instances - 2nd pass') transaction.commit() Alert('', header='Purged {} duplicate instances!'.format(deletedCount))
row_qty = int(sheet_length / max_length) tile_width = sheet_width / column_qty tile_length = sheet_length / row_qty first_tile_loc = DB.XYZ(0.825 / 12, 9.5 / 12, 0) first_tile_pt = first_tile_loc.Add( DB.XYZ(tile_width / 2, -(tile_length / 2), 0)) total_views = column_qty * row_qty total_sheets = math.ceil(len(views) / float(total_views)) Alert( 'Max tile is {}" wide by {}" tall\nIt can be placed {} times in {} columns and {} rows' .format(tile_width * 12, tile_length * 12, total_views, column_qty, row_qty), title="Finish Options PDF", header="Swatch Tiling", ) col = 1 row = 1 sheet_count = 1 view_count = total_views sheet = DB.ViewSheet.Create(revit.doc, pdf_tb.Id) sheet.SheetNumber = str(max_num + sheet_count) sheet.Name = "Finish Options" p1 = sheet.LookupParameter("SSG_Spec Short Description_1") p2 = sheet.LookupParameter("Sheet Issue Date") p1.Set(short_descript) p2.Set(today)
i.GetExternalFileReference().GetAbsolutePath()) # Update Central Dictionary Containing Links if os.path.exists(file_path): links.update( {os.path.basename(file_path): os.path.dirname(file_path)}) else: # Indicate Broken CAD Links links.update({ '(FILE NOT FOUND) {}'.format(os.path.basename(file_path)): os.path.dirname(file_path) }) # If there are no Linked Documents if not links.keys(): Alert('There are no links loaded into the project', title="No Links Available", exit=True) # Create Form selection = forms.SelectFromList.show(sorted( links.keys(), key=lambda x: (os.path.splitext(x)[1], os.path.splitext(x)[0])), button_name='Select Links to Open', multiselect=True) # If User Cancels Script if selection is None: sys.exit(1) # Open the Directory in Windows Explorer for each Linked Document Selected selectedPaths = list(set([links[key] for key in selection]))
def AlertSelection(els, msg): if len(els) < 1: Alert(msg, title="neoCL | Selection", header="Any elements found!") return False else: return True
from rpw.ui.forms import Alert Alert( 'Base CAD is linked from BIM 360 \n Base CAD is gray \n Base building is filled in gray \n All spaces have rooms in them \n All furniture GRP has a SeatingCapcity \n Support & Amenity spaces are labeled \n Graphic scale is correct & matches view template \n North arrow is adjusted \n Drawing title bar is shown \n Project name is correct \n Sheet views are labeled', title="Pipeline Checklist", header="Have you completed:")
def typeduplicating_handler(sender, args): Alert("Duplicating Types is not a good practice")
def inplace_handler(sender, args): Alert("You Serious??! Make some legit families instead")
array.append(data) t.Commit() #Check if parameters from Excel are in the model missing_param = [] for param in param_names_excel: if (param not in params_element_name) and param not in (missing_param): missing_param.append(param) #Ask to continue if some parameters are missing nbr_missing_param = len(missing_param) if nbr_missing_param != 0: miss_button = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No miss = TaskDialog.Show( "Parameters missing", "Some parameters in Excel document are missing in Revit : " + ", ".join(missing_param) + ".\nThe plugin cannot write in this parameters.\nDo you want to continue?", miss_button) if miss == TaskDialogResult.Yes: feeding_parameter(array, param_names_excel, params_element_name, unfoundelements, missing_param) else: Alert('Come back when your changes are done', title="End of the program", exit=True) else: feeding_parameter(array, param_names_excel, params_element_name, unfoundelements, missing_param) else: Alert('A plus tard!', title="End of the program", exit=True)
familyManager.RemoveParameter( p ) except Exception as e: pass # Open Temporary Shared Parameters File with SharedParametersFileClass( pathOriginal, uidoc ) as spFile: for key in sharedParameters: # Create New Shared Parameter as a Duplicate guid = sharedParameters.get( key )['guid'] definition = sharedParameters.get( key )['definition'] isInstance = sharedParameters.get( key )['isInstance'] externalDefnition = spFile.copyExternalDefinition( guid, definition ) try: # Fails if Parameter Already Exists familyManager.AddParameter( externalDefnition, BuiltInParameterGroup.PG_DATA, isInstance ) except Exception as e: pass t.Commit() # Load Families and Overwrite familyDoc.LoadFamily( doc, FamilyLoadOptions() ) familyDoc.Close() else: Alert( 'Selected Families: {}\nAvailable Schedules: {}'.format( len(family_dict), len(schedule_dict) ), title="Error", header="There was a Problem", exit=True )