Esempio n. 1
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)
Esempio n. 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
Esempio n. 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()
Esempio n. 4
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))
Esempio n. 5
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
Esempio n. 6
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
Esempio n. 7
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
Esempio n. 8
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:
    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:
Esempio n. 10
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()