Beispiel #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
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
Beispiel #3
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
def GetCentralModelFilePath(doc):
  modelPath = GetWorksharingCentralModelPath(doc)
  filePath = (
      ModelPathUtils.ConvertModelPathToUserVisiblePath(modelPath)
      if modelPath is not None else
      str.Empty
    )
  return filePath
Beispiel #5
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)
Beispiel #6
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)
Beispiel #7
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))
Beispiel #8
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)
Beispiel #9
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.***")
Beispiel #10
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.')
Beispiel #11
0
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:
	print('Model is not saved yet. Can not aquire location.')
Beispiel #12
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.')
Beispiel #13
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.")
Beispiel #14
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)
Beispiel #15
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))
Beispiel #16
0
              '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':
    cl = FilteredElementCollector(doc)
    revs = cl.OfCategory(BuiltInCategory.OST_Revisions)\
             .WhereElementIsNotElementType()

    for rev in revs:
        print('{0}\t'