forked from architecture-building-systems/revitpythonshell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.cs
614 lines (541 loc) · 25.8 KB
/
App.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Xml.Linq;
using Autodesk.Revit;
using Autodesk.Revit.UI;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using RevitPythonShell.RevitCommands;
using RpsRuntime;
namespace RevitPythonShell
{
[Regeneration(RegenerationOption.Manual)]
[Transaction(TransactionMode.Manual)]
class App : IExternalApplication
{
private const string APP_NAME = "RevitPythonShell";
private static string versionNumber;
private static string dllfolder;
/// <summary>
/// Hook into Revit to allow starting a command.
/// </summary>
Result IExternalApplication.OnStartup(UIControlledApplication application)
{
try
{
versionNumber = application.ControlledApplication.VersionNumber;
if (application.ControlledApplication.VersionName.ToLower().Contains("vasari"))
{
versionNumber = "_Vasari";
}
dllfolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// dllfolder = Path.Combine(
// Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
// $"{APP_NAME}/{versionNumber}");
var assemblyName = "CommandLoaderAssembly";
var dllfullpath = Path.Combine(dllfolder, assemblyName + ".dll");
var settings = GetSettings();
CreateCommandLoaderAssembly(settings, dllfolder, assemblyName);
BuildRibbonPanel(application, dllfullpath);
ExecuteStartupScript(application);
return Result.Succeeded;
}
catch (Exception ex)
{
var td = new TaskDialog("Error setting up RevitPythonShell");
td.MainInstruction = ex.Message;
td.ExpandedContent = ex.ToString();
td.Show();
return Result.Failed;
}
}
private static void ExecuteStartupScript(UIControlledApplication uiControlledApplication)
{
// we need a UIApplication object to assign as `__revit__` in python...
var versionNumber = uiControlledApplication.ControlledApplication.VersionNumber;
var fieldName = int.Parse(versionNumber) >= 2017 ? "m_uiapplication": "m_application";
var fi = uiControlledApplication.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
var uiApplication = (UIApplication)fi.GetValue(uiControlledApplication);
// execute StartupScript
var startupScript = GetStartupScript();
if (startupScript != null)
{
var executor = new ScriptExecutor(GetConfig(), uiApplication, uiControlledApplication);
var result = executor.ExecuteScript(startupScript, GetStartupScriptPath());
if (result == (int)Result.Failed)
{
TaskDialog.Show("RevitPythonShell - StartupScript", executor.Message);
}
}
}
private static void BuildRibbonPanel(UIControlledApplication application, string dllfullpath)
{
var assembly = typeof(App).Assembly;
var smallImage = GetEmbeddedPng(assembly, "RevitPythonShell.Resources.Python-16.png");
var largeImage = GetEmbeddedPng(assembly, "RevitPythonShell.Resources.Python-32.png");
RibbonPanel ribbonPanel = application.CreateRibbonPanel(APP_NAME);
var splitButton = ribbonPanel.AddItem(new SplitButtonData("splitButtonRevitPythonShell", APP_NAME)) as SplitButton;
PushButtonData pbdOpenPythonShell = new PushButtonData(
APP_NAME,
"Interactive\nPython Shell",
assembly.Location,
typeof(IronPythonConsoleCommand).FullName);
pbdOpenPythonShell.Image = smallImage;
pbdOpenPythonShell.LargeImage = largeImage;
pbdOpenPythonShell.AvailabilityClassName = typeof(IronPythonConsoleCommandAvail).FullName;
splitButton.AddPushButton(pbdOpenPythonShell);
PushButtonData pbdOpenNonModalShell = new PushButtonData(
"NonModalRevitPythonShell",
"Non-modal\nShell",
assembly.Location,
typeof(NonModalConsoleCommand).FullName);
pbdOpenNonModalShell.Image = smallImage;
pbdOpenNonModalShell.LargeImage = largeImage;
pbdOpenNonModalShell.AvailabilityClassName = typeof(IronPythonConsoleCommandAvail).FullName;
splitButton.AddPushButton(pbdOpenNonModalShell);
PushButtonData pbdConfigure = new PushButtonData(
"Configure",
"Configure...",
assembly.Location,
typeof(ConfigureCommand).FullName);
pbdConfigure.Image = GetEmbeddedPng(assembly, "RevitPythonShell.Resources.Settings-16.png");
pbdConfigure.LargeImage = GetEmbeddedPng(assembly, "RevitPythonShell.Resources.Settings-32.png");
pbdConfigure.AvailabilityClassName = typeof(IronPythonConsoleCommandAvail).FullName;
splitButton.AddPushButton(pbdConfigure);
PushButtonData pbdDeployRpsAddin = new PushButtonData(
"DeployRpsAddin",
"Deploy RpsAddin",
assembly.Location,
typeof(DeployRpsAddinCommand).FullName);
pbdDeployRpsAddin.Image = GetEmbeddedPng(assembly, "RevitPythonShell.Resources.Deployment-16.png");
pbdDeployRpsAddin.LargeImage = GetEmbeddedPng(assembly, "RevitPythonShell.Resources.Deployment-32.png");
pbdDeployRpsAddin.AvailabilityClassName = typeof(IronPythonConsoleCommandAvail).FullName;
splitButton.AddPushButton(pbdDeployRpsAddin);
var commands = GetCommands(GetSettings()).ToList();
AddGroupedCommands(dllfullpath, ribbonPanel, commands.Where(c => !string.IsNullOrEmpty(c.Group)).GroupBy(c => c.Group));
AddUngroupedCommands(dllfullpath, ribbonPanel, commands.Where(c => string.IsNullOrEmpty(c.Group)).ToList());
}
private static ImageSource GetEmbeddedBmp(System.Reflection.Assembly app, string imageName)
{
var file = app.GetManifestResourceStream(imageName);
var source = BmpBitmapDecoder.Create(file, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
return source.Frames[0];
}
private static ImageSource GetEmbeddedPng(System.Reflection.Assembly app, string imageName)
{
var file = app.GetManifestResourceStream(imageName);
var source = PngBitmapDecoder.Create(file, BitmapCreateOptions.None, BitmapCacheOption.None);
return source.Frames[0];
}
private static void AddGroupedCommands(string dllfullpath, RibbonPanel ribbonPanel, IEnumerable<IGrouping<string, Command>> groupedCommands)
{
foreach (var group in groupedCommands)
{
SplitButtonData splitButtonData = new SplitButtonData(group.Key, group.Key);
var splitButton = ribbonPanel.AddItem(splitButtonData) as SplitButton;
foreach (var command in group)
{
var pbd = new PushButtonData(command.Name, command.Name, dllfullpath, "Command" + command.Index);
pbd.Image = command.SmallImage;
pbd.LargeImage = command.LargeImage;
splitButton.AddPushButton(pbd);
}
}
}
private static void AddUngroupedCommands(string dllfullpath, RibbonPanel ribbonPanel, List<Command> commands)
{
// add canned commands as stacked pushbuttons (try to pack 3 commands per pushbutton, then 2)
while (commands.Count > 4 || commands.Count == 3)
{
// remove first three commands from the list
var command0 = commands[0];
var command1 = commands[1];
var command2 = commands[2];
commands.RemoveAt(0);
commands.RemoveAt(0);
commands.RemoveAt(0);
PushButtonData pbdA = new PushButtonData(command0.Name, command0.Name, dllfullpath, "Command" + command0.Index);
pbdA.Image = command0.SmallImage;
pbdA.LargeImage = command0.LargeImage;
PushButtonData pbdB = new PushButtonData(command1.Name, command1.Name, dllfullpath, "Command" + command1.Index);
pbdB.Image = command1.SmallImage;
pbdB.LargeImage = command1.LargeImage;
PushButtonData pbdC = new PushButtonData(command2.Name, command2.Name, dllfullpath, "Command" + command2.Index);
pbdC.Image = command2.SmallImage;
pbdC.LargeImage = command2.LargeImage;
ribbonPanel.AddStackedItems(pbdA, pbdB, pbdC);
}
if (commands.Count == 4)
{
// remove first two commands from the list
var command0 = commands[0];
var command1 = commands[1];
commands.RemoveAt(0);
commands.RemoveAt(0);
PushButtonData pbdA = new PushButtonData(command0.Name, command0.Name, dllfullpath, "Command" + command0.Index);
pbdA.Image = command0.SmallImage;
pbdA.LargeImage = command0.LargeImage;
PushButtonData pbdB = new PushButtonData(command1.Name, command1.Name, dllfullpath, "Command" + command1.Index);
pbdB.Image = command0.SmallImage;
pbdB.LargeImage = command0.LargeImage;
ribbonPanel.AddStackedItems(pbdA, pbdB);
}
if (commands.Count == 2)
{
// remove first two commands from the list
var command0 = commands[0];
var command1 = commands[1];
commands.RemoveAt(0);
commands.RemoveAt(0);
PushButtonData pbdA = new PushButtonData(command0.Name, command0.Name, dllfullpath, "Command" + command0.Index);
pbdA.Image = command0.SmallImage;
pbdA.LargeImage = command0.LargeImage;
PushButtonData pbdB = new PushButtonData(command1.Name, command1.Name, dllfullpath, "Command" + command1.Index);
pbdB.Image = command1.SmallImage;
pbdB.LargeImage = command1.LargeImage;
ribbonPanel.AddStackedItems(pbdA, pbdB);
}
if (commands.Count == 1)
{
// only one command defined, show as a big button...
var command = commands[0];
PushButtonData pbd = new PushButtonData(command.Name, command.Name, dllfullpath, "Command" + command.Index);
pbd.Image = command.SmallImage;
pbd.LargeImage = command.LargeImage;
ribbonPanel.AddItem(pbd);
}
}
/// <summary>
/// Creates a dynamic assembly that contains types for starting the canned commands.
/// </summary>
private static void CreateCommandLoaderAssembly(XDocument repository, string dllfolder, string dllname)
{
var assemblyName = new AssemblyName { Name = dllname + ".dll", Version = new Version(1, 0, 0, 0) };
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, dllfolder);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("CommandLoaderModule", dllname + ".dll");
foreach (var command in GetCommands(repository))
{
var typebuilder = moduleBuilder.DefineType("Command" + command.Index,
TypeAttributes.Class | TypeAttributes.Public,
typeof(CommandLoaderBase));
// add RegenerationAttribute to type
var regenerationConstrutorInfo = typeof(RegenerationAttribute).GetConstructor(new Type[] { typeof(RegenerationOption) });
var regenerationAttributeBuilder = new CustomAttributeBuilder(regenerationConstrutorInfo, new object[] {RegenerationOption.Manual});
typebuilder.SetCustomAttribute(regenerationAttributeBuilder);
// add TransactionAttribute to type
var transactionConstructorInfo = typeof(TransactionAttribute).GetConstructor(new Type[] { typeof(TransactionMode) });
var transactionAttributeBuilder = new CustomAttributeBuilder(transactionConstructorInfo, new object[] { TransactionMode.Manual });
typebuilder.SetCustomAttribute(transactionAttributeBuilder);
// call base constructor with script path
var ci = typeof(CommandLoaderBase).GetConstructor(new[] { typeof(string) });
var constructorBuilder = typebuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]);
var gen = constructorBuilder.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0); // Load "this" onto eval stack
gen.Emit(OpCodes.Ldstr, command.Source); // Load the path to the command as a string onto stack
gen.Emit(OpCodes.Call, ci); // call base constructor (consumes "this" and the string)
gen.Emit(OpCodes.Nop); // Fill some space - this is how it is generated for equivalent C# code
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ret); // return from constructor
typebuilder.CreateType();
}
assemblyBuilder.Save(dllname + ".dll");
}
Result IExternalApplication.OnShutdown(UIControlledApplication application)
{
// FIXME: deallocate the python shell...
return Result.Succeeded;
}
public static IRpsConfig GetConfig()
{
return new RpsConfig(GetSettingsFile());
}
/// <summary>
/// Returns a handle to the settings file.
/// </summary>
/// <returns></returns>
public static XDocument GetSettings()
{
string settingsFile = GetSettingsFile();
return XDocument.Load(settingsFile);
}
private static string GetSettingsFile()
{
string folder = GetSettingsFolder();
return Path.Combine(folder, "RevitPythonShell.xml");
}
/// <summary>
/// Returns the name of the folder with the settings file. This folder
/// is also the default folder for relative paths in StartupScript and InitScript tags.
/// </summary>
private static string GetSettingsFolder()
{
return dllfolder;
}
/// <summary>
/// Returns a list of commands as defined in the repository file.
/// </summary>
/// <returns></returns>
public static IEnumerable<Command> GetCommands(XDocument repository)
{
int i = 0;
foreach (var commandNode in repository.Root.Descendants("Command") ?? new List<XElement>())
{
var addinAssembly = typeof(RpsExternalApplicationBase).Assembly;
var commandName = commandNode.Attribute("name").Value;
var commandSrc = commandNode.Attribute("src").Value;
var group = commandNode.Attribute("group") == null ? "" : commandNode.Attribute("group").Value;
ImageSource largeImage = null;
if (IsValidPath(commandNode.Attribute("largeImage")))
{
var largeImagePath = GetAbsolutePath(commandNode.Attribute("largeImage").Value);
largeImage = BitmapDecoder.Create(File.OpenRead(largeImagePath), BitmapCreateOptions.None, BitmapCacheOption.None).Frames[0];
}
else
{
largeImage = GetEmbeddedPng(addinAssembly, "RpsRuntime.Resources.PythonScript32x32.png");
}
ImageSource smallImage = null;
if (IsValidPath(commandNode.Attribute("smallImage")))
{
var smallImagePath = GetAbsolutePath(commandNode.Attribute("smallImage").Value);
smallImage = BitmapDecoder.Create(File.OpenRead(smallImagePath), BitmapCreateOptions.None, BitmapCacheOption.None).Frames[0];
}
else
{
smallImage = GetEmbeddedPng(addinAssembly, "RpsRuntime.Resources.PythonScript16x16.png");
}
yield return new Command {
Name = commandName,
Source = commandSrc,
Group = group,
LargeImage = largeImage,
SmallImage = smallImage,
Index = i++
};
}
}
/// <summary>
/// True, if the contents of the attribute is a valid absolute path (or relative path to the assembly) is
/// an existing path.
/// </summary>
private static bool IsValidPath(XAttribute pathAttribute)
{
if (pathAttribute != null && !string.IsNullOrEmpty(pathAttribute.Value))
{
return File.Exists(GetAbsolutePath(pathAttribute.Value));
}
return false;
}
/// <summary>
/// Return an absolute path for input path, with relative paths seen as
/// relative to the assembly location. No guarantees are made as to
/// wether the path exists or not.
/// </summary>
private static string GetAbsolutePath(string path)
{
if (Path.IsPathRooted(path))
{
return path;
}
else
{
var assembly = typeof(App).Assembly;
return Path.Combine(Path.GetDirectoryName(assembly.Location), path);
}
}
/// <summary>
/// Returns a string to be executed, whenever the interactive shell is started.
/// If this is not specified in the XML file (under /RevitPythonShell/InitScript),
/// then null is returned.
/// </summary>
public static string GetInitScript()
{
var path = GetInitScriptPath();
if (File.Exists(path))
{
using (var reader = File.OpenText(path))
{
var source = reader.ReadToEnd();
return source;
}
}
// backwards compatibility: InitScript used to have a CDATA section directly
// embedded in the settings xml file
var initScriptTags = GetSettings().Root.Descendants("InitScript") ?? new List<XElement>();
if (initScriptTags.Count() == 0)
{
return null;
}
var firstScript = initScriptTags.First();
// backwards compatibility: InitScript used to be included as CDATA in the config file
return firstScript.Value.Trim();
}
/// <summary>
/// Returns the path to the InitScript as configured in the settings file or "" if not
/// configured. This is used in the ConfigureCommandsForm.
/// </summary>
public static string GetInitScriptPath()
{
return GetScriptPath("InitScript");
}
/// <summary>
/// Returns the path to the StartupScript as configured in the settings file or "" if not
/// configured. This is used in the ConfigureCommandsForm.
/// </summary>
public static string GetStartupScriptPath()
{
return GetScriptPath("StartupScript");
}
/// <summary>
/// Returns the value of the "src" attribute for the tag "tagName" in the settings file
/// or "" if not configured.
/// </summary>
private static string GetScriptPath(string tagName)
{
var tags = GetSettings().Root.Descendants(tagName) ?? new List<XElement>();
if (tags.Count() == 0)
{
return "";
}
var firstScript = tags.First();
if (firstScript.Attribute("src") != null)
{
var path = firstScript.Attribute("src").Value;
if (Path.IsPathRooted(path))
{
return path;
}
else
{
return Path.Combine(GetSettingsFolder(), path);
}
}
else
{
return "";
}
}
/// <summary>
/// Returns a string to be executed, whenever the revit is started.
/// If this is not specified as a path to an existing file in the XML file (under /RevitPythonShell/StartupScript/@src),
/// then null is returned.
/// </summary>
public static string GetStartupScript()
{
var path = GetStartupScriptPath();
if (File.Exists(path))
{
using (var reader = File.OpenText(path))
{
var source = reader.ReadToEnd();
return source;
}
}
// no startup script found
return null;
}
/// <summary>
/// Writes settings to the settings file, replacing the old commands.
/// </summary>
public static void WriteSettings(
IEnumerable<Command> commands,
IEnumerable<string> searchPaths,
IEnumerable<KeyValuePair<string, string>> variables,
string initScript,
string startupScript)
{
var doc = GetSettings();
var settingsFolder = GetSettingsFolder();
// clean out current stuff
foreach (var xmlExistingCommands in (doc.Root.Descendants("Commands") ?? new List<XElement>()).ToList())
{
xmlExistingCommands.Remove();
}
foreach (var xmlExistingSearchPaths in doc.Root.Descendants("SearchPaths").ToList())
{
xmlExistingSearchPaths.Remove();
}
foreach (var xmlExistingVariables in doc.Root.Descendants("Variables").ToList())
{
xmlExistingVariables.Remove();
}
foreach (var xmlExistingInitScript in doc.Root.Descendants("InitScript").ToList())
{
xmlExistingInitScript.Remove();
}
foreach (var xmlExistingStartupScript in doc.Root.Descendants("StartupScript").ToList())
{
xmlExistingStartupScript.Remove();
}
// add commnads
var xmlCommands = new XElement("Commands");
foreach (var command in commands)
{
xmlCommands.Add(new XElement(
"Command",
new XAttribute("name", command.Name),
new XAttribute("src", command.Source),
new XAttribute("group", command.Group)));
}
doc.Root.Add(xmlCommands);
// add search paths
var xmlSearchPaths = new XElement("SearchPaths");
foreach (var path in searchPaths)
{
xmlSearchPaths.Add(new XElement(
"SearchPath",
new XAttribute("name", path)));
}
// ensure settings directory is added to the search paths
if (!searchPaths.Contains(settingsFolder)) {
xmlSearchPaths.Add(new XElement(
"SearchPath",
new XAttribute("name", settingsFolder)));
}
doc.Root.Add(xmlSearchPaths);
// add variables
var xmlVariables = new XElement("Variables");
foreach (var variable in variables)
{
xmlVariables.Add(new XElement(
"StringVariable",
new XAttribute("name", variable.Key),
new XAttribute("value", variable.Value)));
}
doc.Root.Add(xmlVariables);
// add init script
var xmlInitScript = new XElement("InitScript");
xmlInitScript.Add(new XAttribute("src", initScript));
doc.Root.Add(xmlInitScript);
// add startup script
var xmlStartupScript = new XElement("StartupScript");
xmlStartupScript.Add(new XAttribute("src", startupScript));
doc.Root.Add(xmlStartupScript);
doc.Save(GetSettingsFile());
}
}
/// <summary>
/// A simple structure to hold information about canned commands.
/// </summary>
internal class Command
{
public string Name;
public string Group;
public string Source;
public int Index;
public ImageSource LargeImage;
public ImageSource SmallImage;
public override string ToString()
{
return Name;
}
}
}