Files
SzmediTools/Szmedi.RvKits/FamilyTools/LocalFamsLibWin.xaml.cs

621 lines
22 KiB
C#
Raw Normal View History

2025-09-16 16:06:41 +08:00

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Nice3point.Revit.Toolkit.External.Handlers;
using Szmedi.RvKits.FamilyTools;
namespace Szmedi.RvKits.FamilyLibrary
{
/// <summary>
/// LocalFamily.xaml 的交互逻辑
/// </summary>
public partial class LocalFamsLibWin
{
#region
private readonly ActionEventHandler handler = new();
/// <summary>
/// 加载缩略图资源
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
private BitmapSource LoadImage(string filename)
{
var bm = WindowsThumbnailProvider.GetThumbnail(filename, 128, 128, ThumbnailOptions.None);
return Imaging.CreateBitmapSourceFromHBitmap(
bm.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions()
);
}
#endregion
#region
/// <summary>
/// 获取页面数据源
/// </summary>
/// <param name="jo"></param>
/// <returns></returns>
private List<RvComponent> GetListviewItems(JumpOperation jo)
{
List<RvComponent> familyFileList = [];
var list = pageFamilyFileList.GetPageData(jo);
foreach (var file in list)
{
familyFileList.Add(
new RvComponent
{
Title = Path.GetFileNameWithoutExtension(file.ToString()),
ImageData = LoadImage(file.ToString()),
Path = file.FullName
}
);
}
return familyFileList;
}
#endregion
//private string GetConfigPath()
//{
// //ExeConfigurationFileMap map = new ExeConfigurationFileMap();
// //map.ExeConfigFilename = "\\FamilyTools.dll.config";
// //Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
// //string path = config.AppSettings.Settings["FamilyPath"].Value;//若路径存在则自动获取该路径
// //return path;
// Assembly assembly = Assembly.GetCallingAssembly();
// Uri uri = new Uri(Path.GetDirectoryName(assembly.CodeBase));
// ExeConfigurationFileMap map = new ExeConfigurationFileMap();
// map.ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".dll.config");
// Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
// string _Loadpath = config.AppSettings.Settings["FamilyPath"].Value; //若路径存在则自动获取该路径
// return _Loadpath;
//}
#region ListView首页数据源
/// <summary>
/// 绑定ListView首页数据源
/// </summary>
private void BindListViewSource()
{
//Stopwatch stw = new Stopwatch();
//stw.Start();
//stw.Stop();
//TimeSpan ts = stw.Elapsed;
//MessageBox.Show(ts.TotalMilliseconds.ToString(), "绑定数据源");
GetPageNumber(familyFiles);
cbbPage.SelectedIndex = 0;
//fileListView.ItemsSource = familyFileList;
FileListView.ItemsSource = GetListviewItems(JumpOperation.GoHome);
}
#endregion
#region
private void BtnBrowser_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
try
{
var file = btn.DataContext as RvComponent;
//Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
PreviewFam preview = new(uiapp.Application, uiapp.ActiveUIDocument, file.Path, handler) { Owner = this };
preview.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
LogAssists.WriteLog(ex.StackTrace);
}
}
#endregion
#region
/// <summary>
/// 将族加载到当前文件中。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnLoadFamily_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
var file = btn.DataContext as RvComponent;
//((ListViewItem)video_name.ContainerFromElement((Button)sender)).Content
//var file = btn.Parent;
FamilyLoadOption familyLoadOption = new();
Family family = null;
FamilySymbol fs = null;
//FamilySymbol symbol = null;
var view = doc.ActiveView;
List<SymbolModel> sms = [];
handler.Raise(
uiapp =>
{
using (Transaction trans = new(doc))
{
trans.Start("加载族" + "-" + Path.GetFileNameWithoutExtension(file.Title));
doc.LoadFamily(file.Path, familyLoadOption, out family);
var fsids = family.GetFamilySymbolIds();
if (fsids.Count > 1) //两种族类型以上时提供选择
{
foreach (var id in fsids)
{
var name = doc.GetElement(id).Name;
SymbolModel sm = new(name);
sms.Add(sm);
}
trans.RollBack();
SelectFamilySymbol select = new(uiapp, file.Path, sms) { Owner = this };
select.ShowDialog();
}
else
{
foreach (var id in fsids)
{
fs = doc.GetElement(id) as FamilySymbol;
if (!fs.IsActive)
{
fs.Activate();
}
break;
}
trans.Commit();
}
}
if (fs != null)
{
uiapp.ActiveUIDocument.PromptForFamilyInstancePlacement(fs);
}
});
}
#endregion
#region
/// <summary>
/// 路径选择
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnPathChoose_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog dialog = new();
if (dialog.ShowDialog())
{
try
{
//SetConfig(dialog.SelectedPath);
Properties.Settings.Default.FamilyPath2020 = dialog.SelectedPath;
FileListView.ItemsSource = null;
PopulateTreeView(dialog.SelectedPath);
//BtnPathChoose.Content = dialog.SelectedPath;
BtnPathChoose.ToolTip = dialog.SelectedPath;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
LogAssists.WriteLog(ex.StackTrace);
}
}
}
#endregion
#region TextBox内容ListViewItem
/// <summary>
/// 根据TextBox内容搜索所有ListViewItem。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnSearch_Click(object sender, RoutedEventArgs e)
{
List<FileInfo> results = [];
foreach (var item in familyFiles)
{
var fileName = item.Name;
if (fileName.Contains(TbFamilyName.Text.Trim()))
{
results.Add(item);
}
}
GetPageNumber(results);
tbPage.Text = pageFamilyFileList.Pagecount.ToString();
tbPageAll.Text = $"共计{results.Count}个";
FileListView.ItemsSource = GetListviewItems(JumpOperation.GoHome);
}
#endregion
#region ListView中
/// <summary>
/// 获取选中的树状节点时将该节点目录及子目录下的文件显示到ListView中。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DirTreeItem_Selected(object sender, RoutedEventArgs e)
{
//e.OriginalSource 就是TreeViewItem对象你可以将其保存到窗体类的某个私有字段中或者直接使用它如下所示
var selectedItem = e.OriginalSource as TreeViewItem;
//MessageBox.Show(selectedItem.Header.ToString());
familyFiles.Clear();
var currentFullPath = selectedItem.Tag.ToString();
GetFamilyFile(currentFullPath);
BindListViewSource();
}
#endregion
#region
/// <summary>
/// 获取选择路径下的所有族文件
/// </summary>
/// <param name="fullPath"></param>
private void GetFamilyFile(string fullPath)
{
DirectoryInfo dir = new(fullPath);
try
{
//判断所指的文件夹/文件是否存在
if (!dir.Exists)
{
return;
}
var dirD = dir;
//获取文件夹下所有文件和文件夹
var files = dirD.GetFileSystemInfos();
//对单个FileSystemInfo进行判断如果是文件夹则进行递归操作
foreach (var FSys in files)
{
if (FSys is FileInfo fileInfo)
{
//如果是文件,进行文件操作
//获取文件所在原始路径
if (fileInfo.Extension == ".rfa")
{
FileInfo SFInfo = new($"{fileInfo.DirectoryName}\\{fileInfo.Name}");
familyFiles.Add(SFInfo);
//SetListViewItem(SFInfo);
}
}
else
{
//如果是文件夹,则进行递归调用
//string pp = FSys.Name;
GetFamilyFile($"{fullPath}\\{FSys}");
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
LogAssists.WriteLog(e.StackTrace);
}
}
#endregion
#region
/// <summary>
/// 获取、显示页码
/// </summary>
/// <param name="list"></param>
private void GetPageNumber(List<FileInfo> list)
{
pageFamilyFileList = new PageInfo<FileInfo>(list, 24);
List<int> currentPageNum = [];
for (var i = 0; i < pageFamilyFileList.Pagecount; i++)
{
currentPageNum.Add(i + 1);
}
tbPage.Text = pageFamilyFileList.Pagecount.ToString();
tbPageAll.Text = $"共计{familyFiles.Count}个";
cbbPage.ItemsSource = currentPageNum;
}
#endregion
#region ListView右键加载族文件
/// <summary>
/// ListView选中的所有族加载到项目中
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadFamily_Click(object sender, RoutedEventArgs e)
{
handler.Raise(
_ =>
{
foreach (RvComponent item in FileListView.SelectedItems)
{
FamilyLoadOption familyLoadOption = new();
using Transaction trans = new(doc);
trans.Start("加载族" + "-" + Path.GetFileNameWithoutExtension(item.Title));
try
{
doc.LoadFamily(item.Path, familyLoadOption, out var family);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
LogAssists.WriteLog(ex.StackTrace);
}
trans.Commit();
}
});
}
#endregion
#region TreeView数据源
/// <summary>
/// 绑定TreeView数据源
/// </summary>
private void PopulateTreeView(string Path)
{
dirTree.Items.Clear();
TreeViewItem rootNode;
DirectoryInfo info = new(Path);
if (info.Exists)
{
rootNode = new TreeViewItem { Header = info.Name, Tag = info.FullName };
SubDirectories(info.GetDirectories(), rootNode);
dirTree.Items.Add(rootNode);
rootNode.IsExpanded = true;
}
}
#endregion
#region TreeView树状结构
/// <summary>
/// 添加目录结构到TreeView树状结构
/// </summary>
/// <param name="subDirs"></param>
/// <param name="nodeToAddTo"></param>
private void SubDirectories(DirectoryInfo[] subDirs, TreeViewItem nodeToAddTo)
{
TreeViewItem aNode;
DirectoryInfo[] subSubDirs;
foreach (var subDir in subDirs)
{
aNode = new TreeViewItem { Header = subDir.Name, Tag = subDir.FullName };
subSubDirs = subDir.GetDirectories();
if (subSubDirs.Length != 0)
{
SubDirectories(subSubDirs, aNode);
}
nodeToAddTo.Items.Add(aNode);
}
}
#endregion
#region TextBox内容清空后
/// <summary>
/// TextBox内容清空后恢复搜索前的页面内容。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TbFamilyName_TextChanged(object sender, TextChangedEventArgs e)
{
if (TbFamilyName.Text == string.Empty)
{
BtnSearch.IsDefault = true;
if (FileListView.ItemsSource != null)
{
GetPageNumber(familyFiles);
pageFamilyFileList.CurrentIndex = cbbPage.SelectedIndex + 1;
FileListView.ItemsSource = GetListviewItems(JumpOperation.GoAny);
}
}
}
#endregion
#region
private readonly UIApplication uiapp;
//Autodesk.Revit.ApplicationServices.Application app;
private readonly Document doc;
private PageInfo<FileInfo> pageFamilyFileList; //分页族文件列表,可作为搜索的分页族文件列表
private readonly List<FileInfo> familyFiles = []; //所有族文件列表
#endregion
#region
public LocalFamsLibWin(UIApplication uiapp)
{
//Resources.MergedDictionaries.Add(new ResourceDictionary
//{
// Source = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml")
//});
//Resources.MergedDictionaries.Add(new ResourceDictionary
//{
// Source = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml")
//});
//Resources.MergedDictionaries.Add(new ResourceDictionary
//{
// Source = new Uri("pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Blue.xaml")
//});
//Resources.MergedDictionaries.Add(new ResourceDictionary
//{
// Source = new Uri("pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml")
//});
//Assembly.LoadFile(@"F:\OneDrive\Revit二次开发\Revit Dev\FamilyTools\bin\Debug\MahApps.Metro.IconPacks.dll");
InitializeComponent();
doc = uiapp.ActiveUIDocument.Document;
//this.app = uiapp.Application;
this.uiapp = uiapp;
#if REVIT2018
var familyPath = Properties.Settings.Default.FamilyPath2018;
#elif REVIT2019
var familyPath = Properties.Settings.Default.FamilyPath2019;
#elif REVIT2020
var familyPath = Properties.Settings.Default.FamilyPath2020;
#endif
PopulateTreeView(familyPath);
//BtnPathChoose.Content = familyPath;
BtnPathChoose.ToolTip = familyPath;
}
#endregion
#region ListViewItem包装起来
//private void GetListViewSource(FileInfo SFInfo)
//{
//ListViewItem listViewItem = new ListViewItem();
//Thickness thickness = new Thickness();
//thickness.Top = 5;
//thickness.Bottom = 5;
//thickness.Left = 5;
//thickness.Right = 5;
//System.Windows.Media.Color color = (System.Windows.Media.Color)System.Windows.Media.ColorToBrushConverter.ConvertFromString("#FFF0F0F0");
//StackPanel sp = new StackPanel
//{
// //Background = new System.Windows.Media.SolidColorBrush(color),
// HorizontalAlignment = HorizontalAlignment.Center,
// VerticalAlignment = VerticalAlignment.Center,
// Margin = thickness,
//};
//TextBlock tb = new TextBlock
//{
// Text = Path.GetFileNameWithoutExtension(SFInfo.ToString()),
// Width = 64,
// Height = 15,
// TextAlignment = TextAlignment.Center,
// TextWrapping = TextWrapping.WrapWithOverflow
//};
//System.Drawing.Bitmap bmp = WindowsThumbnailProvider.GetThumbnail(SFInfo.ToString(), 64, 64, ThumbnailOptions.None);
//System.Windows.Media.Imaging.BitmapSource bm = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
//Image image = new Image
//{
// Source = bm,
// Stretch = System.Windows.Media.Stretch.Uniform,
// Height = 64,
// Width = 64
//};
//sp.Children.Add(image);
//sp.Children.Add(tb);
//listViewItem.Content = sp;
////listViewItem.ToolTip = SFInfo.ToString();
//listViewItem.ToolTip = Path.GetFileNameWithoutExtension(SFInfo.ToString());
//listViewItem.Tag = SFInfo;
//familyFileList.Add(listViewItem);
//}
#endregion
#region
private void BtnHome_Click(object sender, RoutedEventArgs e)
{
if (FileListView.ItemsSource != null)
{
FileListView.ItemsSource = GetListviewItems(JumpOperation.GoHome);
cbbPage.SelectedIndex = pageFamilyFileList.CurrentIndex - 1;
}
}
private void BtnPrevious_Click(object sender, RoutedEventArgs e)
{
if (FileListView.ItemsSource != null)
{
FileListView.ItemsSource = GetListviewItems(JumpOperation.GoPrePrevious);
cbbPage.SelectedIndex = pageFamilyFileList.CurrentIndex - 1;
}
}
private void BtnNext_Click(object sender, RoutedEventArgs e)
{
if (FileListView.ItemsSource != null)
{
FileListView.ItemsSource = GetListviewItems(JumpOperation.GoNext);
cbbPage.SelectedIndex = pageFamilyFileList.CurrentIndex - 1;
}
}
private void BtnEnd_Click(object sender, RoutedEventArgs e)
{
if (FileListView.ItemsSource != null)
{
FileListView.ItemsSource = GetListviewItems(JumpOperation.GoEnd);
cbbPage.SelectedIndex = pageFamilyFileList.CurrentIndex - 1;
}
}
private void CbbPage_DropDownClosed(object sender, EventArgs e)
{
if (FileListView.ItemsSource != null)
{
pageFamilyFileList.CurrentIndex = cbbPage.SelectedIndex + 1;
FileListView.ItemsSource = GetListviewItems(JumpOperation.GoAny);
}
}
#endregion
#region
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
foreach (RvComponent item in FileListView.SelectedItems)
{
var filePath = item.Path;
WinDialogAssists.OpenFolderAndSelectFile(filePath);
}
}
#endregion
}
}