def _check_connection(): logger.info('Checking internet connection...') successful_url = check_internet_connection() if successful_url: logger.debug('Url access successful: {}'.format(successful_url)) return True else: return False
def parse(value,even=False,odd=False,saveSelection=True): logger.info(str([even,odd,saveSelection])) if(value!=None): value = value.strip("\n").strip(" ").strip("\t").strip("\r") value_lines = value.split("\n") errors = [] ids = [] ids_all = [] ids_text = [] for v in range(len(value_lines)): line_ok = False if(odd==True): if v%2 == 0: line_ok = True elif(even==True): if v%2 != 0: line_ok = True else: line_ok = True if line_ok==True: vl = value_lines[v] vl = vl.strip(" ").strip("\n").strip("\t").strip("\r") try: _id = int(vl) ids_all.append(str(int(_id))) ids.append(doc.GetElement(ElementId(int(_id))).Id) except: m = re.search(r"(id|Код)\s+([0-9]{1,})[^0-9]*", vl) try: _id=str(m.group(2)) ids_all.append(str(int(_id))) ids.append(doc.GetElement(ElementId(int(_id))).Id) except: errors.append(vl) a='' errors.append(str(len(ids))) errors.append( str(len(set(ids_all))) ) print(",".join(set(ids_all))) addtoclipboard(",".join(set(ids_all))) selection = uidoc.Selection selection_ids = List[ElementId](ids) selection.SetElementIds(selection_ids) if saveSelection==True: selection = {elId.ToString() for elId in selection_ids} f = open(datafile, 'w') pl.dump(selection, f) f.close() if(len(errors)): print("Error lines", "\n".join(errors))
def _update_repo(repo_info): # update one by one logger.debug('Updating repo: {}'.format(repo_info.directory)) try: upped_repo_info = updater.update_pyrevit(repo_info) logger.info(':inbox_tray: Successfully updated: {} to {}' .format(upped_repo_info.name, upped_repo_info.last_commit_hash[:7])) except: logger.info('Can not update repo: {} (Run in debug to see why)' .format(repo_info.name))
def _check_for_updates(): if _check_connection(): logger.info('Checking for updates...') for repo in updater.get_all_extension_repos(): if updater.has_pending_updates(repo): return True else: logger.warning('No internet access detected. ' 'Skipping check for updates.') return False
def selectDuplicateTags(selected_switch="OST_RoomTags"): uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document av = doc.ActiveView cl_tags = FilteredElementCollector(doc) tags = cl_tags.OfCategory(switches[selected_switch] ).WhereElementIsNotElementType().ToElementIds() logger.debug(str(len(tags)) + " tags found") tags_dict = {} views_dict = [] for eId in tags: e = doc.GetElement(eId) try: e.View except: logger.debug(str(eId) + " is element type") continue try: v = e.View #пропускает, если тэг не на текущем виде - оптимизировать через фильтр! if not __shiftclick__ and v.Id != av.Id: logger.debug(str(eId) + " not on active view" + v.Name) continue text = str(e.Room.Id) + "_" + str(v.Id) views_dict.append(int(str(e.View.Id))) if text not in tags_dict: tags_dict[text] = [] tags_dict[text].append(int(eId.ToString())) except: logger.info(str(eId) + " unknown exception") ttags = [] for t in tags_dict: if len(tags_dict[t]) > 1: i = 0 tags_dict[t].sort() for tt in tags_dict[t]: if i != 0: ttags.append(tt) i += 1 ttags_text = ",".join(map(lambda x: str(x), ttags)) selection = uidoc.Selection collection = List[ElementId](map(lambda x: ElementId(int(x)), ttags)) selection.SetElementIds(collection) logger.info(str(len(ttags)) + " tags selected")
#=============================================================================== #--- SETUP Config #=============================================================================== from __future__ import print_function #=============================================================================== #--- SETUP Logging #=============================================================================== from scriptutils import logger, this_script from scriptutils.userinput import CommandSwitchWindow logger.info('Test Log Level :ok_hand_sign:') logger.warning('Test Log Level') logger.critical('Test Log Level') #=============================================================================== #--- SETUP Standard modules #=============================================================================== import sys from collections import namedtuple from customcollections import DefaultOrderedDict #=============================================================================== #--- SETUP Custom modules #=============================================================================== path_exergy_util_dir = r"C:\LOCAL_REPO\py_ExergyUtilities" sys.path.insert(0,path_exergy_util_dir)
#=============================================================================== #--- SETUP Config #=============================================================================== from __future__ import print_function #=============================================================================== #--- SETUP Logging #=============================================================================== from scriptutils import logger, this_script from scriptutils.userinput import CommandSwitchWindow logger.info('Test Log Level :ok_hand_sign:') logger.warning('Test Log Level') logger.critical('Test Log Level') #=============================================================================== #--- SETUP Standard modules #=============================================================================== import sys from collections import namedtuple from customcollections import DefaultOrderedDict #=============================================================================== #--- SETUP Custom modules #=============================================================================== path_exergy_util_dir = r"C:\LOCAL_REPO\py_ExergyUtilities" sys.path.insert(0, path_exergy_util_dir)
def change_materials(reverse=False, datafile=None, limit=None): mat_dict = {} white_material_name = config_material() materials_exceptions = config_exceptions() ignore_transparent = config_ignore_transparent() if os.path.exists(datafile): logger.debug("Datafile found %s" % datafile) if reverse == False: logger.debug("New materials will be added") f = open(datafile, 'r') mat_dict = pl.load(f) f.close() else: logger.debug("New datafile %s" % datafile) cl = FilteredElementCollector(doc) mats = list( cl.OfCategory(BuiltInCategory.OST_Materials). WhereElementIsNotElementType().ToElements()) try: white_mat = filter(lambda x: x.Name == white_material_name, mats)[0] except Exception as e: logger.error("Material '%s' not found" % white_material_name) logger.error(e) return white_mat_a = white_mat.AppearanceAssetId logger.info("White material: %s\nAssetId: %d" % (white_material_name, white_mat_a.IntegerValue)) t = Transaction(doc) t.Start(__title__ + (" reverse" if reverse else "")) if limit > 0: mats = mats[:limit] for m in mats: m_name = m.Name m_name_ignore = False for r in materials_exceptions: re_match = re.match(r, m_name, re.I) if re_match: m_name_ignore = True break if m_name_ignore: logger.info("%s - ignore name" % m_name) continue if m.Transparency != 0 and ignore_transparent: logger.info("%s - ignore transparency" % m_name) continue m_id = m.Id.IntegerValue a_id = m.AppearanceAssetId.IntegerValue if reverse == False: if a_id != white_mat_a.IntegerValue: mat_dict[m_id] = a_id m.AppearanceAssetId = white_mat_a logger.info("%s (%d, asset %d) changed to white" % (m_name, m_id, a_id)) else: logger.info("%s (%d) wasn't change" % (m_name, m_id)) else: try: _id = mat_dict[m_id] m.AppearanceAssetId = ElementId(_id) logger.info("%s (%d) changed to %d" % (m_name, m_id, _id)) except: logger.info("%s (%d) not found or wasn't change" % (m_name, m_id)) t.Commit() if reverse == False: f = open(datafile, 'w') pl.dump(mat_dict, f) f.close() else: backup_datafile(datafile) print("Completed")
"""Searches the script folders and create buttons for the new script or newly installed extensions.""" from scriptutils import logger from pyrevit.loader.sessionmgr import load_session from pyrevit.loader.sessioninfo import get_session_uuid from scriptutils import this_script # re-load pyrevit session. logger.info('Reloading....') load_session() this_script.results.newsession = get_session_uuid()
dest_vp_types = SelectFromList.show(sorted( [x for x in all_viewport_types if x not in purge_vp_types]), multiselect=False, title='Select Replacement Type') if len(dest_vp_types) >= 1: dest_vp_typeid = dest_vp_types[0].get_rvt_obj().Id else: sys.exit() # Collect all elements that are somehow linked to the viewport types to be purged -------------------------------------- # TaskDialog.Show('pyRevit', 'Starting Conversion. Hit Cancel if you get any prompts.') purge_dict = {} for purge_vp_type in purge_vp_types: logger.info('Finding all viewports of type: {}'.format(purge_vp_type.name)) logger.debug('Purging: {}'.format(repr(purge_vp_type))) linked_elements = purge_vp_type.find_linked_elements() logger.debug('{} elements are linked to this viewport type.'.format( len(linked_elements))) purge_dict[purge_vp_type.name] = linked_elements # Perform cleanup ------------------------------------------------------------------------------------------------------ with ActionGroup('Fixed Unpurgable Viewport Types'): # Correct all existing viewports that use the viewport types to be purged # Collect viewports and find the ones that use the purging viewport types all_viewports = Fec(doc).OfClass(clr.GetClrType(Viewport)).ToElements() purge_vp_ids = [x.get_rvt_obj().Id for x in purge_vp_types] with Action('Correct Viewport Types'): for vp in all_viewports: if vp.GetTypeId() in purge_vp_ids:
def main(): active_view = get_active_view() if not active_view: logger.warning('Activate a view to copy') return logger.info('Source view selected: %s id%s' % (active_view.Name, active_view.Id.ToString())) """ Filters selection """ active_template_filters_ch = get_view_filters(doc, active_view) sel_set = read_checkboxes_state() vt_list = get_view_templates(doc, sel_set=sel_set) if not vt_list: logger.warning('Project has no view templates') return if not active_template_filters_ch: logger.warning('Active view has no filter overrides') return filter_checkboxes = SelectFromList.show(active_template_filters_ch, name_attr='Name', title='Select filters to copy', button_name='Select filters', multiselect=True) filter_checkboxes_sel = [] # Select filters from active view for checkbox in filter_checkboxes: if checkbox: filter_checkboxes_sel.append(checkbox) if not filter_checkboxes_sel: return """ Target view templates selection """ view_checkboxes = SelectFromList.show(vt_list, name_attr='Name', title='Select templates to apply filters', button_name='Apply filters to templates', multiselect=True) view_checkboxes_sel = [] # Select view templates to copy for checkbox in view_checkboxes: if checkbox: view_checkboxes_sel.append(checkbox) if not view_checkboxes_sel: return save_checkboxes_state(view_checkboxes_sel) # active_template = doc.GetElement(active_view.ViewTemplateId) t = Transaction(doc) t.Start(__title__) for vt in view_checkboxes_sel: if vt.Id == active_view.ViewTemplateId: logger.debug('Current template found') continue for f in filter_checkboxes_sel: try: vt.RemoveFilter(f.Id) logger.info('filter %s deleted from template %s' % (f.Id.IntegerValue.ToString(), vt.Name)) except: pass try: fr = active_view.GetFilterOverrides(f.Id) vt.SetFilterOverrides(f.Id, fr) except Exception as e: logger.warning('filter %s was not aplied to view %s\n%s' % (f.Id.IntegerValue.ToString(), vt.Name, e)) t.Commit() print("Completed")
# define the __nonzero__ method so you can use your objects in an # if statement. e.g. if checkbox_option: def __nonzero__(self): return self.state # __bool__ is same as __nonzero__ but is for python 3 compatibility def __bool__(self): return self.state usertemp = os.getenv('Temp') prjname = op.splitext(op.basename(doc.PathName))[0] datafile = usertemp + '\\' + prjname + '_pyChecked_Templates.pym' logger.info(datafile) sel_set = [] allowed_types = [ ViewPlan, View3D, ViewSection, ViewSheet, ViewDrafting ] def read_checkboxes_state(): try: f = open(datafile, 'r')
if __name__ == '__main__': # collect a list of all repos to be updates if _check_connection(): pyrevit_repo = updater.get_pyrevit_repo() thirdparty_repos = updater.get_thirdparty_ext_repos() logger.debug('List of thirdparty repos to be updated: {}' .format(thirdparty_repos)) for thirdparty_repo_info in thirdparty_repos: _update_repo(thirdparty_repo_info) if not updater.has_core_updates(): _update_repo(pyrevit_repo) # perform upgrade tasks logger.info('Upgrading settings...') upgrade.upgrade_existing_pyrevit() # Call pyRevit reload command to reload pyRevit # The reason to call the command instead of using sessionmgr module # to realod is that the repo has been just updatedm so all # modules need to be re-imported again in a clean engine. from pyrevit.loader.sessionmgr import execute_command execute_command(PYREVIT_CORE_RELOAD_COMMAND_NAME) this_script.results.newsession = get_session_uuid() else: this_script.output.print_html(COREUPDATE_MESSAGE .format(home=HOME_DIR)) logger.debug('Core updates. Skippin update and reload.')
return if __name__ == '__main__': # collect a list of all repos to be updates if _check_connection(): repo_info_list = updater.get_all_extension_repos() logger.debug('List of repos to be updated: {}'.format(repo_info_list)) for repo_info in repo_info_list: # update one by one logger.debug('Updating repo: {}'.format(repo_info.directory)) try: upped_repo_info = updater.update_pyrevit(repo_info) logger.info( ':inbox_tray: Successfully updated: {} to {}'.format( upped_repo_info.name, upped_repo_info.last_commit_hash[:7])) except: logger.info( 'Can not update repo: {} (Run in debug to see why)'. format(repo_info.name)) # perform upgrade tasks logger.info('Upgrading settings...') upgrade.upgrade_existing_pyrevit() # now re-load pyrevit session. sleep(1) logger.info('Reloading...') load_session() else:
from Autodesk.Revit.DB import Transaction, ViewSheet shift = 1 selected_sheets = [] for sheet in selection.elements: if isinstance(sheet, ViewSheet): selected_sheets.append(sheet) sorted_sheet_list = sorted(selected_sheets, key=lambda x: x.SheetNumber) if shift >= 0: sorted_sheet_list.reverse() with Transaction(doc, 'Shift Sheets') as t: t.Start() for sheet in sorted_sheet_list: try: cur_sheet_num = sheet.SheetNumber sheet_num_param = sheet.LookupParameter('Sheet Number') sheet_num_param.Set( coreutils.increment_str(sheet.SheetNumber, shift)) new_sheet_num = sheet.SheetNumber logger.info('{} -> {}'.format(cur_sheet_num, new_sheet_num)) except Exception as shift_err: logger.error(shift_err) doc.Regenerate() t.Commit()
def main(): allowed_types = [ ViewPlan, View3D, ViewSection, ViewSheet, ViewDrafting ] selection = uidoc.Selection.GetElementIds() if type(doc.ActiveView)!=View: active_view = doc.ActiveView else: active_view = doc.GetElement(selection[0]) if type(active_view) not in allowed_types: logger.error('Selected view is not allowed. Please select or open view from which you want to copy template settings VG Overrides - Filters') return logger.info('Source view selected: %s id%s' % (active_view.Name, active_view.Id.ToString())) active_template = doc.GetElement(active_view.ViewTemplateId) logger.info('Source template: %s id%s' % (active_template.Name, active_template.Id.ToString())) active_template_filters = active_template.GetFilters() # print(active_template_filter_rules) # return selset = read_states() # print(selset) vt_dict = get_view_templates(doc,selset=selset) active_template_filters_ch = get_view_filters(doc,active_template) all_checkboxes = SelectFromCheckBoxes.show(active_template_filters_ch) sel_checkboxes_filter = [] # now you can check the state of checkboxes in your program for checkbox in all_checkboxes: if checkbox: sel_checkboxes_filter.append(checkbox) if len(sel_checkboxes_filter)==0: return all_checkboxes = SelectFromCheckBoxes.show(vt_dict) sel_checkboxes = [] # now you can check the state of checkboxes in your program for checkbox in all_checkboxes: if checkbox: sel_checkboxes.append(checkbox) if len(sel_checkboxes)==0: return write_state(sel_checkboxes) t = Transaction(doc) t.Start("Copy VG") for ch in sel_checkboxes: vt = doc.GetElement(ch.id) if vt.Id == active_template.Id: print('current template found') continue for f in sel_checkboxes_filter: fId = f.id try: vt.RemoveFilter(fId) logger.info('filter %s deleted from template %s' % (fId.ToString(), vt.Name)) except: pass try: fr = active_template.GetFilterOverrides(fId) vt.SetFilterOverrides(fId,fr) except Exception as e: logger.warning('filter not aplied to active view %s\n%s' % (fId.ToString(), e)) t.Commit() print("finished")