def main(): if __forceddebugmode__: limit = 10 logger.debug("limit %d" % limit) else: limit = None reverse = False x, file_name = os.path.split(doc.PathName) file_id, x = os.path.splitext(file_name) if len(file_id) == 0: file_id = doc.Title datafile = script.get_data_file(file_id, "pym") if os.path.exists(datafile): options = ["Make White", "Revert original"] if pyRevitNewer44: selected_switch = CommandSwitchWindow.show( options, message='Select direction') else: selected_switch = CommandSwitchWindow( options, message='Select direction').pick_cmd_switch() if not selected_switch: return if selected_switch == "Revert original": reverse = True change_materials(reverse, datafile=datafile, limit=limit)
def get_tags_by_type(all_views): # find available tags in project tags_by_type = {} for cat_name, cat in switches.items(): cl_tags = FilteredElementCollector(doc) tags = cl_tags.OfCategory(cat) # Find only current view tags, if not ShiftClick if not all_views: tags = tags.OwnedByView(doc.ActiveView.Id) tags = tags.WhereElementIsNotElementType().ToElements() tags = filter(lambda t: type(t) != FamilyInstance, tags) if len(tags) == 0: continue else: logger.debug("%d %s found" % (len(tags), cat_name)) tags_by_view = {} for e in tags: v = e.OwnerViewId if not v: continue if v not in tags_by_view.keys(): tags_by_view[v] = [] tags_by_view[v].append(e) tags_by_type[cat_name] = tags_by_view return tags_by_type
def iterate(mode, step_size=1): if os.path.isfile(datafile_i): f = open(datafile_i, 'r') cur_i = pl.load(f) f.close() if (mode == '-'): i = cur_i - step_size else: i = cur_i + step_size else: i = 0 try: f = open(datafile, 'r') cursel = pl.load(f) f.close() _i = i if (i < 0): i = abs(i / len(cursel)) * len(cursel) + i elif (i >= len(cursel)): i = i - abs(i / len(cursel)) * len(cursel) eId = DB.ElementId(int(list(cursel)[i])) uidoc.Selection.SetElementIds(List[DB.ElementId]([eId])) f = open(datafile_i, 'w') pl.dump(i, f) f.close() except: logger.debug('Selection file {0} does not exit'.format(datafile))
def get_modelview_type(): switch = CommandSwitchWindow(view_types_dict.keys()).pick_cmd_switch() if switch: return switch else: logger.debug('User cancelled.') sys.exit(0)
def _create_pattern(self, domain, export_only=False, export_path=None): 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) if export_only: patmaker.export_pattern(self.pat_name, pat_lines, domain, export_path, model_pattern=self.is_model_pat) TaskDialog.Show('pyRevit', 'Pattern {} exported.'.format(self.pat_name)) else: 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))
def copy_view_contents(activedoc, source_view, dest_doc, dest_view, clear_contents=False): logger.debug('Copying view contents: {}'.format(source_view.Name)) elements_ids = get_view_contents(activedoc, source_view) if clear_contents: if not clear_view_contents(dest_doc, dest_view): return False cp_options = CopyPasteOptions() cp_options.SetDuplicateTypeNamesHandler(CopyUseDestination()) if elements_ids: t = Transaction(dest_doc, 'Copy View Contents') t.Start() copiedElement = \ ElementTransformUtils.CopyElements(source_view, List[ElementId](elements_ids), dest_view, None, cp_options) t.Commit() return True
def save_options(self, sender, args): errors = [] try: my_config.exceptions = pau.str2list( self.exceptions.Text.encode('utf-8')) except: errors.append("Exceptions value is invalid") try: v = self.material.Text assert len(v) >= 0 my_config.material = v.encode('utf-8') except Exception as exc: errors.append("Material name is invalid") logger.debug(exc) try: my_config.ignore_transparent = bool( self.ignore_transparent.IsChecked) except: errors.append("Ignore transparent value is invalid") if errors: alert("Can't save config.\n" + "\n".join(errors)) return else: script.save_config() self.Close()
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 backup_datafile(f): try: _new_path, ext = os.path.splitext(f) new_path = _new_path + datetime.now().strftime( "_%y%m%d_%H-%M-%S") + ext os.rename(f, new_path) logger.debug("Datafile backed up to %s" % new_path) except Exception as e: logger.error("Error renaming datafile\n" + str(e))
def get_copyable_elements(src_view): # get drafting view elements and exclude non-copyable elements view_elements = FilteredElementCollector(doc, src_view.Id).ToElements() elements_to_copy = [] for el in view_elements: if isinstance(el, Element) and el.Category: elements_to_copy.append(el.Id) else: logger.debug('Skipping Element with id: {0}'.format(el.Id)) return elements_to_copy
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 create_dest_view(view_type, view_name, view_scale): with Transaction(doc, 'Create model view') as t: t.Start() try: dest_view = None if view_type == 'Floor Plan': level = get_view_level() view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeFloorPlan) dest_view = ViewPlan.Create(doc, view_fam_typeid, level.Id) elif view_type == 'Reflected Ceiling Plan': level = get_view_level() view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeCeilingPlan) dest_view = ViewPlan.Create(doc, view_fam_typeid, level.Id) elif view_type == 'Section': view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeSection) view_direction = BoundingBoxXYZ() trans_identity = Transform.Identity trans_identity.BasisX = -XYZ.BasisX # x direction trans_identity.BasisY = XYZ.BasisZ # up direction trans_identity.BasisZ = XYZ.BasisY # view direction view_direction.Transform = trans_identity dest_view = ViewSection.CreateSection(doc, view_fam_typeid, view_direction) scale_param = dest_view.LookupParameter( 'Hide at scales coarser than') scale_param.Set(1) elif view_type == 'Elevation': view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeElevation) elev_marker = ElevationMarker.CreateElevationMarker( doc, view_fam_typeid, XYZ(0, 0, 0), 1) default_floor_plan = find_first_floorplan() dest_view = elev_marker.CreateElevation( doc, default_floor_plan.Id, 0) scale_param = dest_view.LookupParameter( 'Hide at scales coarser than') scale_param.Set(1) dest_view.ViewName = view_name dest_view.Scale = view_scale model_visib_param = dest_view.LookupParameter('Display Model') model_visib_param.Set(2) dest_view.CropBoxActive = False dest_view.CropBoxVisible = False t.Commit() return dest_view except Exception as create_err: t.RollBack() logger.debug('Can not create model view: {} | {}'.format( view_name, create_err)) raise create_err
def set_filename_prompt_state(dkeys, state): if dkeys: try: for dkey in dkeys: wr.SetValueEx(dkey, r'PromptForFileName', 0, wr.REG_SZ, '1' if state else '0') return state except Exception as key_read_err: logger.error('Error accessing registry key value. | {}'.format( key_read_err)) else: logger.debug('No registry keys are available for revu printer driver.')
def set_param_values(element, value_dict): for param in element.Parameters: param_name = param.Definition.Name if not param.IsReadOnly and param_name not in exclude_params: if param_name in value_dict.keys(): param_value = value_dict[param_name] try: logger.debug('Setting param: {} to value: {}'.format( param_name, param_value)) param.Set(param_value) except: logger.debug('Param: {} Value is not settable: {}'.format( param_name, param_value))
def clear_view_contents(dest_doc, dest_view): logger.debug('Removing view contents: {}'.format(dest_view.Name)) elements_ids = get_view_contents(dest_doc, dest_view) t = Transaction(dest_doc, 'Delete View Contents') t.Start() for el_id in elements_ids: try: dest_doc.Delete(el_id) except Exception as err: continue t.Commit() return True
def toggle_state(): dkeys = get_driver_keys() if dkeys: curval = query_filename_prompt_state(dkeys) if curval: logger.debug('Prompt For FileName is Enabled. Disabling...') set_filename_prompt_state(dkeys, False) else: logger.debug('Prompt For FileName is Disabled. Enabling...') set_filename_prompt_state(dkeys, True) this_script.toggle_icon(not curval) close_keys(dkeys)
def query_filename_prompt_state(dkeys): state = False if dkeys: try: for dkey in dkeys: key_state = wr.QueryValueEx(dkey, r'PromptForFileName')[0] logger.debug('Checking reg key state: {}'.format(key_state)) state |= int(key_state) > 0 return state except Exception as key_read_err: logger.error('Error accessing registry key value. | {}'.format( key_read_err)) else: logger.debug('No registry keys are available for revu printer driver.')
def toggle_state(): on_icon = this_script.get_bundle_file('on.png') off_icon = this_script.get_bundle_file('off.png') dkeys = get_driver_keys() if dkeys: curval = query_filename_prompt_state(dkeys) if curval: logger.debug('Prompt For FileName is Enabled. Disabling...') set_filename_prompt_state(dkeys, False) this_script.ui_button.set_icon(off_icon, icon_size=ICON_MEDIUM) else: logger.debug('Prompt For FileName is Disabled. Enabling...') set_filename_prompt_state(dkeys, True) this_script.ui_button.set_icon(on_icon, icon_size=ICON_MEDIUM) close_keys(dkeys)
def __selfinit__(script_cmp, ui_button_cmp, __rvt__): on_icon = script_cmp.get_bundle_file('on.png') off_icon = script_cmp.get_bundle_file('off.png') dkeys = get_driver_keys() if dkeys: curval = query_filename_prompt_state(dkeys) close_keys(dkeys) if curval: logger.debug('Prompt For FileName is Enabled...') ui_button_cmp.set_icon(on_icon, icon_size=ICON_MEDIUM) else: logger.debug('Prompt For FileName is Disabled...') ui_button_cmp.set_icon(off_icon, icon_size=ICON_MEDIUM) return True else: return False
def _read_log_file(self, file_path): entry_list = [] log_file_line = 1 prev_entry = None try: with open(file_path, 'r') as log_file: for log_entry in log_file.readlines(): try: new_entry = LogMessageListItem(log_entry) entry_list.append(new_entry) log_file_line += 1 prev_entry = new_entry except Exception as err: logger.debug('Error processing entry at {}:{}'.format( op.basename(file_path), log_file_line)) prev_entry.message += log_entry log_file_line += 1 except Exception as read_err: logger.error('Error reading log file: {} | {}'.format( file_path, read_err)) return entry_list
def create_sheets(self, sender, args): self.Close() if self._process_sheet_code(): if self.sheet_cb.IsChecked: create_func = self._create_sheet transaction_msg = 'Batch Create Sheets' if not self._ask_for_titleblock(): this_script.exit() else: create_func = self._create_placeholder transaction_msg = 'Batch Create Placeholders' with TransactionGroup(doc, transaction_msg) as tg: tg.Start() for sheet_num, sheet_name in self._sheet_dict.items(): logger.debug('Creating Sheet: {}:{}'.format( sheet_num, sheet_name)) create_func(sheet_num, sheet_name) tg.Assimilate()
def find_driver_key(driver_keys, parent_string, key): subkey_count, value_count, last_changed = wr.QueryInfoKey(key) logger.debug('{} reg key has {} subkeys and {} values.'.format( parent_string, subkey_count, value_count)) for idx in range(0, subkey_count): subkey_name = wr.EnumKey(key, idx) key_path = op.join(parent_string, subkey_name) logger.debug('Checking subkey: {}'.format(key_path)) dkey = get_reg_key(key, subkey_name) if dkey: if key_finder.match(key_path): logger.debug('Driver key found: {}'.format(key_path)) driver_keys.append(dkey) logger.debug('Looking into subkey for key: {}'.format(key_path)) find_driver_key(driver_keys, key_path, dkey)
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")
def get_driver_keys(): global driver_keys if not driver_keys: logger.debug('Opening master bluebeam registry key: %s' % BBS_KEY_PATH) bbs_key = get_reg_key(wr.HKEY_CURRENT_USER, BBS_KEY_PATH) if bbs_key: logger.debug('Master key acquired.') logger.debug('Finding list of printer driver keys.') find_driver_key(driver_keys, '', bbs_key) return driver_keys else: return None else: return driver_keys
def copy_sheet(activedoc, source_sheet, dest_doc): logger.debug('Copying sheet {} to document {}'.format( source_sheet.Name, dest_doc.Title)) print('\tCopying/updating Sheet: {}'.format(source_sheet.Name)) tg = TransactionGroup(dest_doc, 'Import Sheet') tg.Start() logger.debug('Creating destination sheet...') new_sheet = copy_sheet_view(activedoc, source_sheet, dest_doc) if new_sheet: if OPTION_SET.op_copy_vports: logger.debug('Copying sheet viewports...') copy_sheet_viewports(activedoc, source_sheet, dest_doc, new_sheet) else: print('Skipping viewports...') else: logger.error('Failed copying sheet: {}'.format(source_sheet.Name)) tg.Assimilate()
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")
def OnDuplicateTypeNamesFound(self, args): logger.debug('Duplicate types found. Using destination types.') return DuplicateTypeAction.UseDestinationTypes
def create_dest_view(view_type, view_name, view_scale): with Transaction(doc, 'Create model view') as t: t.Start() try: dest_view = None if view_type == 'Floor Plan': level = get_view_level() view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeFloorPlan) dest_view = ViewPlan.Create(doc, view_fam_typeid, level.Id) elif view_type == 'Reflected Ceiling Plan': level = get_view_level() view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeCeilingPlan) dest_view = ViewPlan.Create(doc, view_fam_typeid, level.Id) elif view_type == 'Section': view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeSection) view_direction = BoundingBoxXYZ() trans_identity = Transform.Identity trans_identity.BasisX = -XYZ.BasisX # x direction trans_identity.BasisY = XYZ.BasisZ # up direction trans_identity.BasisZ = XYZ.BasisY # view direction view_direction.Transform = trans_identity dest_view = ViewSection.CreateSection(doc, view_fam_typeid, view_direction) scale_param = dest_view.Parameter[ DB.BuiltInParameter. SECTION_COARSER_SCALE_PULLDOWN_IMPERIAL] scale_param.Set(1) elif view_type == 'Elevation': view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeElevation) elev_marker = ElevationMarker.CreateElevationMarker( doc, view_fam_typeid, XYZ(0, 0, 0), 1) default_floor_plan = find_first_floorplan() dest_view = elev_marker.CreateElevation( doc, default_floor_plan.Id, 0) scale_param = dest_view.Parameter[ DB.BuiltInParameter. SECTION_COARSER_SCALE_PULLDOWN_IMPERIAL] scale_param.Set(1) elif view_type == 'Drafting': view_fam_typeid = doc.GetDefaultElementTypeId( ElementTypeGroup.ViewTypeDrafting) dest_view = ViewDrafting.Create(doc, view_fam_typeid) dest_view.ViewName = view_name dest_view.Scale = view_scale model_visib_param = dest_view.Parameter[ DB.BuiltInParameter.VIEW_MODEL_DISPLAY_MODE] if model_visib_param: model_visib_param.Set(2) dest_view.CropBoxActive = False dest_view.CropBoxVisible = False t.Commit() return dest_view except Exception as create_err: t.RollBack() logger.debug('Can not create model view: {} | {}'.format( view_name, create_err)) raise create_err
import os.path as op import _winreg as wr from scriptutils import this_script, logger from pyrevit.coreutils.ribbon import ICON_MEDIUM __doc__ = 'Enables and disables the Revu PDF Printer prompt for filename option. ' \ 'The Icon shows the current state of this setting.' # op.sep = '\\' driver_keys = [] BBS_KEY_PATH = r'Software\Bluebeam Software' BBS_PRINT_DRIVER_MATCH_STR = r'\d{4}\\Brewery\\V\d{2}\\Printer Driver\Z' logger.debug('Match string is: {}'.format(BBS_PRINT_DRIVER_MATCH_STR)) key_finder = re.compile(BBS_PRINT_DRIVER_MATCH_STR) def get_reg_key(key, subkey): try: return wr.OpenKey(key, subkey, 0, wr.KEY_WRITE) except Exception as key_error: logger.debug('Can not open key: {}'.format(subkey)) return None def find_driver_key(driver_keys, parent_string, key): subkey_count, value_count, last_changed = wr.QueryInfoKey(key) logger.debug('{} reg key has {} subkeys and {} values.'.format( parent_string, subkey_count, value_count))
def get_reg_key(key, subkey): try: return wr.OpenKey(key, subkey, 0, wr.KEY_WRITE) except Exception as key_error: logger.debug('Can not open key: {}'.format(subkey)) return None