Пример #1
0
def relink_for_ref_type(external_ref_id, ref_types, relink_map):
    global relink_counter
    ext_ref_last_saved = tm_data.GetLastSavedReferenceData(external_ref_id)
    if not ref_types.get(ext_ref_last_saved.ExternalFileReferenceType):
        return
    ref_type_name = ref_types[ext_ref_last_saved.ExternalFileReferenceType]
    ref_link_path = ext_ref_last_saved.GetPath()
    loaded_status = ext_ref_last_saved.GetLinkedFileStatus()
    user_path = ModelPathUtils.ConvertModelPathToUserVisiblePath(ref_link_path)
    ref_name = os.path.basename(user_path)
    print(" {}: {}  - {}".format(ref_type_name, loaded_status, user_path))

    for search_key in relink_map[ref_type_name]:
        if search_key in ref_name:
            target_user_path = os.path.join(
                relink_map[ref_type_name][search_key], ref_name)
            target_ref_path = ModelPathUtils.ConvertUserVisiblePathToModelPath(
                target_user_path)
            # print(" desired TO>: {}".format(target_user_path))
            tm_data.SetDesiredReferenceData(
                external_ref_id,
                target_ref_path,
                PathType.Relative,
                load_status_map[loaded_status],
            )
            ext_ref_desired = tm_data.GetDesiredReferenceData(ext_ref_id)
            desired_ref_path = ext_ref_desired.GetPath()
            desired_user_path = ModelPathUtils.ConvertModelPathToUserVisiblePath(
                desired_ref_path)
            print(" now TO>: {}".format(desired_user_path))
            print(" found current: {}; target: {}".format(
                os.path.exists(user_path), os.path.exists(desired_user_path)))
            relink_counter["{}_relink_counter".format(ref_type_name)] += 1
            return
Пример #2
0
def OpenFiles(files, app, audit):
    counter = 0
    for oFile in files:
        openOpt = OpenOptions()
        if audit == True:
            openOpt.Audit = True
        else:
            openOpt.Audit = False
        openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
        wsopt = WorksetConfiguration(
            WorksetConfigurationOption.CloseAllWorksets)
        # wsopt.Open(worksetList)
        openOpt.SetOpenWorksetsConfiguration(wsopt)
        modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(oFile)
        # doc = Application.OpenDocumentFile(modelPath, openOpt)
        docs = []
        currentdoc = app.OpenDocumentFile(modelPath, openOpt)
        try:
            DialogBoxShowingEventArgs.OverrideResult(1)
        except:
            pass
        print(str(doc) + ' Opened')
        counter += 1
        docs.append(currentdoc)
    return docs
Пример #3
0
def link_method_rvt():
    files_filter = "RVT files (*.rvt)|*.rvt"
    files = pick_files(files_filter)

    for f in files:
        t = Transaction(doc)
        t.Start(__title__)

        try:
            mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(f)
            o = RevitLinkOptions(False)
            linkType = RevitLinkType.Create(doc, mp, o)
            instance = RevitLinkInstance.Create(doc, linkType.ElementId)
            status = True
        except Exception as e:
            logger.error("Unable to import RVT")
            logger.error(e)
            status = False
            instance = None

        if status:
            instance.Pinned = True
            t.Commit()
        else:
            t.RollBack()
def WithOpenedCloudDocument(uiapp, openInUI, cloudProjectId, cloudModelId,
                            worksetConfig, audit, documentAction, output):
    app = uiapp.Application
    result = None
    output()
    output("Opening cloud model.")
    closeAllWorksets = worksetConfig is None
    if openInUI:
        uidoc = revit_file_util.OpenAndActivateCloudDocument(
            uiapp, cloudProjectId, cloudModelId, closeAllWorksets,
            worksetConfig, audit)
        doc = uidoc.Document
    else:
        doc = revit_file_util.OpenCloudDocument(app, cloudProjectId,
                                                cloudModelId, closeAllWorksets,
                                                worksetConfig, audit)
    try:
        cloudModelPathText = ModelPathUtils.ConvertModelPathToUserVisiblePath(
            doc.GetCloudModelPath())
        output()
        output("Cloud model path is: " + cloudModelPathText)
        result = documentAction(doc)
    finally:
        SafeCloseWithoutSave(doc, openInUI, "Closed cloud model.", output)
    return result
Пример #5
0
    def SaveLinkedDWGs(self, path):
        """Save all linked DWGs in the Project to a chosen folder.
           Function returns a dictionary of CAD filename and their new filepath.
           {Filename : Filepath} - Is will be used further for relinking DWGs."""

        CADfiles_dict = {}
        if not os.path.exists(path):
            os.makedirs(path)

        DWGs = FilteredElementCollector(doc).OfClass(
            CADLinkType).WhereElementIsElementType()
        if DWGs:
            print("----------Saved CAD files:--------")
            for cad_Link in DWGs:
                try:
                    efr = cad_Link.GetExternalFileReference()
                    dwg_path = ModelPathUtils.ConvertModelPathToUserVisiblePath(
                        efr.GetAbsolutePath())
                    dwg_name = dwg_path.split("\\")[-1]
                    dwg_new_path = os.path.join(path, dwg_name).replace(
                        '\\\\', '\\')
                    if dwg_path == dwg_new_path:
                        print('New path is the same as old one. ({})'.format(
                            str(dwg_new_path)))
                    else:
                        shutil.copyfile(dwg_path, dwg_new_path)
                        print("- CAD file saved:" + str(dwg_new_path))
                        CADfiles_dict[dwg_name] = dwg_new_path
                except:
                    print("***Exception occured while saving DWG***")
                    continue
            return CADfiles_dict
        else:
            print("- No CAD links found.")
            return
Пример #6
0
def OpenFilesandUnload(oFile, app, audit):
    openOpt = OpenOptions()
    if audit == True:
        openOpt.Audit = True
    else:
        openOpt.Audit = False
    openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
    wsopt = WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets)
    # wsopt.Open(worksetList)
    openOpt.SetOpenWorksetsConfiguration(wsopt)
    modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(oFile)
    currentdoc = app.OpenDocumentFile(modelPath, openOpt)
    try:
        DialogBoxShowingEventArgs.OverrideResult(1)
    except:
        pass
    revitLinkType = FilteredElementCollector(doc).OfClass(
        RevitLinkType).ToElements()
    for r in revitLinkType:
        try:
            r.Unload(None)
        except:
            pass
    saveOp = SaveAsOptions()
    workOp = WorksharingSaveAsOptions()
    workOp.SaveAsCentral = True
    saveOp.SetWorksharingOptions(workOp)
    title = currentdoc.Title
    currentdoc.SaveAs(destinationFolder + '\\' + title, saveOp)
    currentdoc.Close(False)
Пример #7
0
    def set_coloristic_tag(self, obj):
        """
        Устанавливает коллористические марки.

        Открывает файл с закрытыми рабочими наборами.
        Для этого создается конфиг open_opt

        Проходим по всем документам и панелям, которые переданы в obj
        Выгружаем связь.
        Открываем документ.
        Проверяем можно ли вносить изменения в документ.
        Пробуем внести изменения.
        Проходим по всем панелям и уровням.
        Получаем в документе связи панель по ID.
        Проходим по всем уровням. 
        Для каждой колористик Tag устанавливаем марку по уровню.
        Если файл общий. Синхронизироваться.
        Если файл не общий - просто сохранить.
        В противном случае закрыть документ
        """
        workset_config_option = WorksetConfigurationOption.CloseAllWorksets
        workset_config = WorksetConfiguration(workset_config_option)
        open_opt = OpenOptions()
        open_opt.SetOpenWorksetsConfiguration(workset_config)
        app = self.doc.Application
        for doc, panels in obj.items():
            title = doc.Title
            m_p = ModelPathUtils.ConvertUserVisiblePathToModelPath(
                doc.PathName)
            rvt_type = self.rvt_docs[doc]
            rvt_type.Unload(None)
            cur_doc = app.OpenDocumentFile(m_p, open_opt)
            if not cur_doc.IsReadOnly:
                try:
                    with Transaction(cur_doc, "Вносим изменения") as t:
                        t.Start()
                        for panel, levels in panels.items():
                            panel = cur_doc.GetElement(ElementId(panel.Id))
                            for level, mark in levels.items():
                                level = level if len(
                                    level) > 1 else "0" + level
                                panel.LookupParameter(
                                    "BDS_ColoristicsTag_Floor" +
                                    level).Set(mark)
                        t.Commit()
                    if cur_doc.IsWorkshared:
                        twc_opts = TransactWithCentralOptions()
                        swc_opts = SynchronizeWithCentralOptions()
                        swc_opts.SetRelinquishOptions(RelinquishOptions(True))
                        swc_opts.Comment = "Атоматическая синхронизация КЖС"
                        cur_doc.SynchronizeWithCentral(twc_opts, swc_opts)
                    cur_doc.Close(True)
                except:
                    echo(sys.exc_info()[1])
                    cur_doc.Close(False)
            else:
                echo("Файл {} доступен только для чтения".format(title))
                cur_doc.Close(False)
            rvt_type.Load()
            echo("Обработали связь {}".format(title))
def GetCentralModelFilePath(doc):
  modelPath = GetWorksharingCentralModelPath(doc)
  filePath = (
      ModelPathUtils.ConvertModelPathToUserVisiblePath(modelPath)
      if modelPath is not None else
      str.Empty
    )
  return filePath
Пример #9
0
 def open_coloristic_file(self):
     dialog = FileOpenDialog("Файл колористики json|*.json")
     dialog.Show()
     mpath = dialog.GetSelectedModelPath()
     path = ModelPathUtils.ConvertModelPathToUserVisiblePath(mpath)
     with io.open(path, "r", encoding='utf8') as f:
         text = f.read()
         text = text.replace('"rotate"', '"rotation"')
         return json.loads(text)
Пример #10
0
def count_non_project_dwg_links(filter_paths):
    counter = 0
    collector = Fec(doc).OfClass(Autodesk.Revit.DB.ImportInstance).ToElements()
    for inst in collector:
        if inst.IsLinked:
            inst_path = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetElement(inst.GetTypeId()).GetExternalFileReference().GetAbsolutePath())
            for img_path in filter_paths:
                if img_path in inst_path:
                    counter += 1
    return str(counter)
Пример #11
0
def event_handler_function(sender, args):
    print(15*"-" + "event_handler file opened" + 15*"-")
    doc = __revit__.ActiveUIDocument.Document
    now_utc = str(datetime.datetime.utcnow())
    log_path = "d:/delme/model_open_log.txt"

    if doc.IsWorkshared:
        doc_central_path = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath())
        doc_local_path = doc.PathName
        doc_path = doc_central_path
        in_central = doc_central_path == doc_local_path
        if in_central:
            task_dialog = TaskDialog("rvt_fixme_central_model_warning")
            task_dialog.Id = "rvt_fixme_central_model_warning"
            task_dialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning
            task_dialog.Title = "Attention - you are in central model!!!"
            task_dialog.MainContent = task_dialog.Title
            task_dialog.TitleAutoPrefix = True
            task_dialog.AllowCancellation = True
            task_dialog.Show()
        model_name = op.basename(doc_path)
        model_path = op.dirname(doc_path)
        # model_central_name = model_name.split("_" + rvt_user)[0]
        model_central_name = model_name.split(".rvt")[0]
        assume_fix_tasks_dir = op.join(model_path, "RVT_fixme")
        ini = op.join(assume_fix_tasks_dir, "fixme_{}.ini".format(model_central_name))
        jsn = op.join(assume_fix_tasks_dir, "fixme_{}_ids.json".format(model_central_name))

        # print("searching for fixme: {}".format(ini))
        if op.exists(ini):
            print("- found corresponding RVT_fixme ini to this model.")
            # print(doc_path)
            # print("file was opened at {0}".format(now_utc))
            # print("ini found at: {0}".format(ini))
            if doc.IsWorkshared:
                import on_ws_model_opened
                print("- workshared model found at:\n- {0}".format(doc_path))
                # print("attempt reload")
                # reload(on_ws_model_opened)
                # print("after_reload")
                on_ws_model_opened.connect_to_rvt(ini)

        # print("searching for fixme: {}".format(jsn))
        if op.exists(jsn):
            print("- found corresponding RVT_fixme json to this model.")
            if doc.IsWorkshared:
                import on_ws_model_opened
                print("- workshared model found at:\n- {0}".format(doc_path))
                on_ws_model_opened.connect_to_rvt(jsn)

        with open(log_path, "a") as model_log:
            model_log.write("ws file was opened at \n- {0}\n-".format(now_utc))
Пример #12
0
 def get_import_instance_path(self):
     # type:(ImportInstance) -> str
     """Function to get a path of the selected ImportInstance if it is linked."""
     import_instance = self.selected_dwg_ImportInstance
     if import_instance.IsLinked:
         cad_linktype_id = import_instance.get_Parameter(
             BuiltInParameter.ELEM_FAMILY_PARAM).AsElementId()
         cad_linktype = doc.GetElement(cad_linktype_id)
         efr = cad_linktype.GetExternalFileReference()
         dwg_path = ModelPathUtils.ConvertModelPathToUserVisiblePath(
             efr.GetAbsolutePath())
         return dwg_path
     else:
         alert("Selected DWG instance is not linked.",
               __title__,
               exitscript=True)
Пример #13
0
def OpenFileCloseWorksets(oFile, app, audit):
    openOpt = OpenOptions()
    if audit == True:
        openOpt.Audit = True
    else:
        openOpt.Audit = False
    openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
    wsopt = WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets)
    openOpt.SetOpenWorksetsConfiguration(wsopt)
    modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(oFile)
    currentdoc = app.OpenDocumentFile(modelPath, openOpt)
    try:
        DialogBoxShowingEventArgs.OverrideResult(1)
    except:
        pass
    return currentdoc
Пример #14
0
def OpenCloudFiles(modelGUID, projectGUID, app, audit):
    openOpt = OpenOptions()
    if audit == True:
        openOpt.Audit = True
    else:
        openOpt.Audit = False
    # openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
    wsopt = WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets)
    # wsopt.Open(worksetList)
    openOpt.SetOpenWorksetsConfiguration(wsopt)
    modelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath(
        projectGUID, modelGUID)
    currentdoc = app.OpenDocumentFile(modelPath, openOpt)
    try:
        DialogBoxShowingEventArgs.OverrideResult(1)
    except:
        pass
    return currentdoc
Пример #15
0
def OpenFiles(oFile, app, audit):
    openOpt = OpenOptions()
    if audit == True:
        openOpt.Audit = True
    else:
        openOpt.Audit = False
    openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets

    # Needed for specific view to work:
    # wsopt = WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets)

    # Better for all elements as faster and unload all links cause worksets closed:
    wsopt = WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets)

    # wsopt.Open(worksetList)
    openOpt.SetOpenWorksetsConfiguration(wsopt)
    modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(oFile)
    currentdoc = app.OpenDocumentFile(modelPath, openOpt)
    try:
        DialogBoxShowingEventArgs.OverrideResult(1)
    except:
        pass
    return currentdoc
Пример #16
0
    def RelinkCAD(self, dict_dwg):
        """Relink all CAD files with newly exported ones.
           arg: dictionary of CAD files produced by SaveLinkedDWGs function.
           {filename : new_filepath}"""
        dialogResult = MessageBox.Show(
            "Would you like to Relink saved CAD files in the currently open model?",
            "Relink CAD files?", MessageBoxButtons.YesNo)

        if (dialogResult == DialogResult.Yes):
            DWGs = FilteredElementCollector(doc).OfClass(
                CADLinkType).WhereElementIsElementType()
            if not DWGs:
                print("***No linked CAD files were found***")
                return

            print("---------------------------------------")
            print("----------Relinked CAD files:----------")
            for cad_Link in DWGs:
                try:
                    efr = cad_Link.GetExternalFileReference()
                    dwg_path = ModelPathUtils.ConvertModelPathToUserVisiblePath(
                        efr.GetPath())
                    dwg_name = dwg_path.split("\\")[-1]
                    if dwg_name in dict_dwg:
                        try:
                            cad_Link.LoadFrom(dict_dwg[dwg_name])
                            print("- CAD file relinked - {}".format(dwg_name))
                        except:
                            print(
                                "*** Could not relink CAD file - {}***".format(
                                    dwg_name))
                except:
                    print("***Exception occured while Relinking DWG***")
                    continue
        else:
            print("*** CAD files were not relinked.***")
Пример #17
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.')
Пример #18
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
'''

from Autodesk.Revit.DB import ModelPathUtils, TransmissionData, RevitLinkType, ElementType
import clr
uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
# selection = [ doc.GetElement( elId ) for elId in __revit__.ActiveUIDocument.Selection.GetElementIds() ]

location = doc.PathName
try:
	modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath( location )
	transData = TransmissionData.ReadTransmissionData( modelPath )
	externalReferences = transData.GetAllExternalFileReferenceIds()
	for refId in externalReferences:
		extRef = transData.GetLastSavedReferenceData( refId )
		if 'CADLink' == str( extRef.ExternalFileReferenceType ):
			link = doc.GetElement( refId )
			# link = clr.Convert( link, ElementType )
			path = ModelPathUtils.ConvertModelPathToUserVisiblePath( extRef.GetPath() )
			if '' == path:
				path = '--NOT ASSIGNED--'
			print( "Reloading...\n{0}{1}".format( str( str( extRef.ExternalFileReferenceType )+':').ljust(20), path ))
			# link.Reload()
			# print('Done\n')
			print('Revit API does not have a CADLinkType.Reload method yet')
except:
Пример #19
0
__doc__ = 'Print the full path to the central model (if model is workshared).'

from rpw import doc

# noinspection PyUnresolvedReferences
from Autodesk.Revit.DB import ModelPathUtils
# noinspection PyUnresolvedReferences
from Autodesk.Revit.UI import TaskDialog

if doc.IsWorkshared:
    model_path = doc.GetWorksharingCentralModelPath()
    print(ModelPathUtils.ConvertModelPathToUserVisiblePath(model_path))
else:
    TaskDialog.Show('pyrevit', 'Model is not workshared.')
    elif model + upgrade_suffix in dir_files:
        skip_counter[model] = "model_is_upgraded_already"
        continue
    rvt_models.add(os.path.join(upgrade_dir, model))

for model_name, reason in skip_counter.items():
    print("{}:{}".format(reason.ljust(25), model_name))

print("following {} models found for upgrade:".format(len(rvt_models)))
for model_path in sorted(rvt_models):
    print(model_path)

for model_path in sorted(rvt_models):
    new_target_path = model_path + upgrade_suffix
    rvt_path = FilePath(model_path)
    rvt_model_path = ModelPathUtils.ConvertUserVisiblePathToModelPath(
        model_path)
    print("currently processing: {}".format(model_path))

    ws_conf = WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets)
    open_opt = OpenOptions()
    open_opt.Audit = True
    open_opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
    open_opt.SetOpenWorksetsConfiguration(ws_conf)

    save_opt = SaveAsOptions()
    if os.path.exists(new_target_path):
        print("warning! overwriting: {}".format(new_target_path))
        save_opt.OverwriteExistingFile = True

    model_doc = app.OpenDocumentFile(rvt_path, open_opt)
    if model_doc.IsWorkshared:
Пример #21
0
                            echo("Добавлен параметр {}".format(b.Name))
            t.Commit()


try:
    if selection:
        message(
            "Параметризация производится для выбранного оборудования в количестве {}"
            .format(len(selection)))
    message("Выберете файл с Итогами отопительных приборов в формате csv")
    dialog = FileOpenDialog("Файл CSV (*.csv;)|*.csv")
    dialog.Show()
    mpath = dialog.GetSelectedModelPath()
    if mpath is None:
        raise SystemError("Не выборан файл с Итогами отопительных приборов")
    path = ModelPathUtils.ConvertModelPathToUserVisiblePath(mpath)

    with open(path, 'rt', encoding="maccyrillic") as file:
        data = csv.reader(file, delimiter=';')
        data = [i for i in data]
        for k in range(len(data)):
            if data[k][0].isdigit():
                break
        data = data[2:]
        file.close()

    dialog = FileOpenDialog("Файл CSV (*.csv;)|*.csv")
    dialog.Show()
    mpath = dialog.GetSelectedModelPath()
    if mpath is None:
        raise SystemError("Не выборан файл с Итогами настройки")
Пример #22
0
__doc__ = 'Opens the central log for the current workshared project.'

import os
import os.path as op

from rpw import doc

# noinspection PyUnresolvedReferences
from Autodesk.Revit.DB import ModelPathUtils


if doc.GetWorksharingCentralModelPath():
    model_path = doc.GetWorksharingCentralModelPath()
    centralPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(model_path)
    centralName = op.splitext(op.basename(centralPath))[0]
    slogFile = centralPath.replace('.rvt',
                                   '_backup\\{0}.slog'.format(centralName))
    pfFolder = os.getenv('ProgramFiles(x86)')
    nppExists = op.isfile(op.join(pfFolder, 'Notepad++\\Notepad++.EXE'))
    if nppExists:
        os.system('start notepad++ "{0}"'.format(slogFile))
    else:
        os.system('start notepad "{0}"'.format(slogFile))
else:
    print("Model is not work-shared.")
Пример #23
0
void_height_map = {}

output = script.get_output()

dprint("model check:")
prerequisite_check()

if not correct_selection(selection):
    sys.exit()

with db.Transaction("cut_nested_rvt_voids"):

    selected_link_type = selection[0]
    link_model_path = selected_link_type.GetExternalFileReference(
    ).GetAbsolutePath()
    link_user_path = ModelPathUtils.ConvertModelPathToUserVisiblePath(
        link_model_path)

    discipline_void_re_pat = ""

    for discipline in discipline_void_fam_re_pat:
        if discipline in link_user_path:
            discipline_void_re_pat = discipline_void_fam_re_pat[discipline]
            break

    print("found: {}".format(link_user_path))
    print("date modified: {}".format(
        time.ctime(os.path.getmtime(link_user_path))))

    rvt_link_type = RevitLinkType.Create(doc, link_model_path, rvt_link_opt)
    link_inst = RevitLinkInstance.Create(doc, rvt_link_type.ElementId)
Пример #24
0
    roomlist = cl.OfCategory(BuiltInCategory.OST_Rooms)\
                 .WhereElementIsNotElementType().ToElements()

    for el in roomlist:
        print('ROOM NAME: {0} '
              'ROOM NUMBER: {1} '
              'ROOM ID: {2}'.format(
                  el.LookupParameter('Name').AsString().ljust(30),
                  el.LookupParameter('Number').AsString().ljust(20), el.Id))

    print('\n\nTOTAL ROOMS FOUND: {0}'.format(len(roomlist)))

elif sel_switch == 'External References':
    location = doc.PathName
    try:
        modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(location)
        transData = TransmissionData.ReadTransmissionData(modelPath)
        externalReferences = transData.GetAllExternalFileReferenceIds()
        for refId in externalReferences:
            extRef = transData.GetLastSavedReferenceData(refId)
            refpath = extRef.GetPath()
            path = ModelPathUtils.ConvertModelPathToUserVisiblePath(refpath)
            if '' == path:
                path = '--NOT ASSIGNED--'
            reftype = str(str(extRef.ExternalFileReferenceType) +
                          ':').ljust(20)
            print("{0}{1}".format(reftype, path))
    except:
        print('Model is not saved yet. Can not aquire location.')

elif sel_switch == 'Revisions':
Пример #25
0
        files.append(str(file))
counter = 0
worksetList = []

__doc__ = 'Open projects and remove all the links.' \
          'Please do not use lightly'

# Open Files
for oFile in files:
    openOpt = OpenOptions()
    openOpt.Audit = False
    openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
    wsopt = WorksetConfiguration(WorksetConfigurationOption.OpenLastViewed)
    wsopt.Open(worksetList)
    openOpt.SetOpenWorksetsConfiguration(wsopt)
    modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(models +
                                                                 oFile)
    __revit__.OpenAndActivateDocument(modelPath, openOpt, False)
    # Define doc
    uidoc = __revit__.ActiveUIDocument
    doc = __revit__.ActiveUIDocument.Document
    placeholderfile = "C:\\Users\\loum\\Desktop\\Empty Project.rvt"

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

    t = Transaction(doc, 'Delete CAD Elements')
    # Get Fist View Position
    t.Start()
Пример #26
0
"""Opens keynote source file used in this model."""

__author__ = 'Dan Mapes'
__contact__ = 'https://github.com/DMapes'

import os

from scriptutils import logger
from revitutils import doc

from Autodesk.Revit.DB import KeynoteTable, ModelPathUtils

kt = KeynoteTable.GetKeynoteTable(doc)
kt_ref = kt.GetExternalFileReference()
path = ModelPathUtils.ConvertModelPathToUserVisiblePath(
    kt_ref.GetAbsolutePath())
if not path:
    logger.error('No keynote file is assigned...File address is empty.')
else:
    os.system('start notepad "{0}"'.format(path))