forked from baldurk/renderdoc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonShell.cs
More file actions
565 lines (450 loc) · 18.3 KB
/
Copy pathPythonShell.cs
File metadata and controls
565 lines (450 loc) · 18.3 KB
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using renderdocui.Code;
using renderdoc;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using IronPython.Runtime.Exceptions;
using System.Threading;
namespace renderdocui.Windows.Dialogs
{
public partial class PythonShell : DockContent
{
Core m_Core = null;
private ScriptEngine pythonengine = null;
private ScriptScope shellscope = null;
ScintillaNET.Scintilla scriptEditor = null;
private bool m_LibsLoaded = false;
public PythonShell(Core core)
{
InitializeComponent();
if (SystemInformation.HighContrast)
{
toolStrip1.Renderer = new ToolStripSystemRenderer();
toolStrip2.Renderer = new ToolStripSystemRenderer();
}
shellTable.Dock = DockStyle.Fill;
scriptTable.Dock = DockStyle.Fill;
scriptEditor = new ScintillaNET.Scintilla();
((System.ComponentModel.ISupportInitialize)(scriptEditor)).BeginInit();
scriptEditor.Dock = System.Windows.Forms.DockStyle.Fill;
scriptEditor.Location = new System.Drawing.Point(3, 3);
scriptEditor.Name = "scripteditor";
scriptEditor.Font = new Font("Consolas", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
scriptEditor.Margins.Left = 4;
scriptEditor.Margins.Margin0.Width = 30;
scriptEditor.Margins.Margin1.Width = 0;
scriptEditor.Margins.Margin2.Width = 16;
scriptEditor.Markers[0].BackColor = System.Drawing.Color.LightCoral;
scriptEditor.ConfigurationManager.Language = "python";
((System.ComponentModel.ISupportInitialize)(scriptEditor)).EndInit();
scriptEditor.KeyDown += new KeyEventHandler(scriptEditor_KeyDown);
scriptEditor.TextChanged += new EventHandler(scriptEditor_TextChanged);
scriptEditor.Scrolling.HorizontalWidth = 1;
const uint SCI_SETSCROLLWIDTHTRACKING = 2516;
scriptEditor.NativeInterface.SendMessageDirect(SCI_SETSCROLLWIDTHTRACKING, true);
scriptSplit.Panel1.Controls.Add(scriptEditor);
m_Core = core;
pythonengine = NewEngine();
mode_Changed(shellMode, null);
newScript.PerformClick();
clearCmd_Click(null, null);
EnableButtons(true);
}
void scriptEditor_TextChanged(object sender, EventArgs e)
{
SetLineNumber(-1);
}
void scriptEditor_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control)
{
if (e.KeyCode == Keys.O)
{
openButton.PerformClick();
e.Handled = true;
e.SuppressKeyPress = true;
}
if (e.KeyCode == Keys.S)
{
saveAs.PerformClick();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
}
private ScriptEngine NewEngine()
{
var engine = Python.CreateEngine();
List<string> searches = new List<string>(engine.GetSearchPaths());
searches.Add(Directory.GetCurrentDirectory());
string libspath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "pythonlibs.zip");
if (File.Exists(libspath))
{
m_LibsLoaded = true;
searches.Add(libspath);
}
engine.SetSearchPaths(searches);
return engine;
}
private ScriptScope NewScope(ScriptEngine engine)
{
engine.Runtime.LoadAssembly(typeof(PythonShell).Assembly);
var scope = engine.CreateScope();
scope.SetVariable("pyrenderdoc", m_Core);
// try to import the RenderDoc namespace.
// This isn't equivalent to scope.ImportModule
try
{
engine.CreateScriptSourceFromString("import renderdoc").Execute(scope);
}
catch (Exception)
{
}
return scope;
}
private Thread pythonThread = null;
private MemoryStream stdout = null;
private StreamWriter stdoutwriter = null;
private StreamReader stdoutreader = null;
private int linenum = -1;
private string Execute(ScriptEngine engine, ScriptScope scope, string script)
{
stdout = new MemoryStream();
stdoutwriter = new StreamWriter(stdout);
stdoutreader = new StreamReader(stdout);
engine.Runtime.IO.SetOutput(stdout, stdoutwriter);
try
{
m_Core.Renderer.SetExceptionCatching(true);
dynamic ret = engine.CreateScriptSourceFromString(script).Execute(scope);
m_Core.Renderer.SetExceptionCatching(false);
if (ret != null)
{
stdoutwriter.Write(ret.ToString() + Environment.NewLine);
stdoutwriter.Flush();
}
}
catch (Exception ex)
{
m_Core.Renderer.SetExceptionCatching(false);
// IronPython throws so many exceptions, we don't want to kill the application
// so we just swallow Exception to cover all the bases
string exstr = engine.GetService<ExceptionOperations>().FormatException(ex);
stdoutwriter.Write(exstr);
stdoutwriter.Write(Environment.NewLine);
stdoutwriter.Flush();
}
stdout.Seek(0, SeekOrigin.Begin);
string output = stdoutreader.ReadToEnd();
stdoutreader.Dispose();
stdout = null;
stdoutreader = null;
stdoutwriter = null;
return output;
}
private void mode_Changed(object sender, EventArgs e)
{
if (sender == shellMode)
{
shellMode.Checked = true;
scriptMode.Checked = false;
scriptTable.Visible = false;
shellTable.Visible = true;
Text = "Interactive Python Shell";
interactiveInput_TextChanged(null, null);
}
else if (sender == scriptMode)
{
scriptMode.Checked = true;
shellMode.Checked = false;
shellTable.Visible = false;
scriptTable.Visible = true;
scriptOutput.Text = "";
Text = "Python Script Execute";
}
}
private List<string> history = new List<string>();
int historyidx = -1;
string workingtext = "";
private void interactiveInput_KeyDown(object sender, KeyEventArgs e)
{
if (!e.Shift && e.KeyCode == Keys.Return)
{
executeCmd_Click(null, null);
e.Handled = true;
e.SuppressKeyPress = true;
}
bool moved = false;
if (e.KeyCode == Keys.Down && historyidx > -1)
{
historyidx--;
moved = true;
}
if (e.KeyCode == Keys.Up && historyidx + 1 < history.Count)
{
if (historyidx == -1)
workingtext = interactiveInput.Text;
historyidx++;
moved = true;
}
if (moved)
{
if (historyidx == -1)
interactiveInput.Text = workingtext;
else
interactiveInput.Text = history[historyidx];
interactiveInput.Select(interactiveInput.Text.Length, 0);
}
}
private void interactiveInput_TextChanged(object sender, EventArgs e)
{
using (var g = interactiveInput.CreateGraphics())
{
SizeF MessageSize = g.MeasureString(interactiveInput.Text + "a", interactiveInput.Font,
interactiveInput.Width, new StringFormat(0));
const int maxHeight = 100;
if (MessageSize.Height <= maxHeight)
{
interactiveInput.Height = 20 + (int)MessageSize.Height;
interactiveInput.ScrollBars = ScrollBars.None;
}
else
{
interactiveInput.Height = 20 + maxHeight;
interactiveInput.ScrollBars = ScrollBars.Vertical;
}
}
}
private void interactiveInput_Layout(object sender, LayoutEventArgs e)
{
interactiveInput_TextChanged(null, null);
}
private void executeCmd_Click(object sender, EventArgs e)
{
var nl = Environment.NewLine;
interactiveOutput.AppendText(">> " + interactiveInput.Text.Trim().Replace(nl, nl + ">> ") + nl);
interactiveOutput.AppendText(Execute(pythonengine, shellscope, interactiveInput.Text));
history.Insert(0, interactiveInput.Text);
historyidx = -1;
workingtext = "";
interactiveInput.Text = "";
}
private void clearCmd_Click(object sender, EventArgs e)
{
interactiveOutput.Text = String.Format("RenderDoc Python console, powered by IronPython {0}{1}" +
"The 'pyrenderdoc' object is the Core class instance.{1}" +
"The 'renderdoc' module is available, as the matching namespace in C#.{1}",
IronPython.CurrentVersion.AssemblyFileVersion, Environment.NewLine);
if (!m_LibsLoaded)
{
interactiveOutput.Text = String.Format("!!! pythonlibs.zip not found! Check installation !!!{0}" +
"!!! If building locally, ensure you have compiled python libraries: !!!{0}" +
"!!! Download IronPython-2.7.4 package, run this command and rebuild renderdocui !!!{0}" +
"cd renderdocui/3rdparty/ironpython/ && ./compilelibs.sh /path/to/IronPython-2.7.4{0}{0}{1}",
Environment.NewLine, interactiveOutput.Text);
}
shellscope = NewScope(pythonengine);
}
private static PythonShell me = null;
private static TracebackDelegate PythonTrace(TraceBackFrame frame, string result, object payload)
{
if(me != null)
me.TraceCallback(frame, result, payload);
return PythonTrace;
}
private void TraceCallback(TraceBackFrame frame, string result, object payload)
{
if (result == "exception")
{
System.Diagnostics.Trace.WriteLine("On line " + frame.f_lineno.ToString());
}
linenum = (int)frame.f_lineno - 1;
stdoutwriter.Flush();
stdout.Seek(0, SeekOrigin.Begin);
string output = stdoutreader.ReadToEnd();
stdout.Seek(0, SeekOrigin.Begin);
stdout.SetLength(0);
if (output.Length > 0)
{
this.BeginInvoke(new Action(() =>
{
scriptOutput.Text += output;
scriptOutput.SelectionStart = scriptOutput.TextLength;
scriptOutput.ScrollToCaret();
}));
}
}
bool recurse = false;
private void SetLineNumber(int lineNum)
{
if (recurse || me == null || me.scriptEditor == null)
return;
recurse = true;
for (int i = 0; i < me.scriptEditor.Lines.Count; i++)
{
me.scriptEditor.Lines[i].DeleteMarker(0);
}
if (lineNum >= 0 && lineNum < me.scriptEditor.Lines.Count)
{
me.scriptEditor.Lines[lineNum].AddMarker(0);
}
recurse = false;
}
private void EnableButtons(bool enable)
{
shellMode.Enabled = scriptMode.Enabled =
newScript.Enabled = openButton.Enabled = saveAs.Enabled =
runButton.Enabled = enable;
abortButton.Enabled = !enable;
}
private void abortButton_Click(object sender, EventArgs e)
{
if (pythonThread != null)
pythonThread.Abort();
}
private void runButton_Click(object sender, EventArgs e)
{
var scriptscope = NewScope(pythonengine);
me = this;
var script = scriptEditor.Text;
scriptOutput.Text = "";
linenum = -1;
EnableButtons(false);
linenumTimer.Enabled = true;
linenumTimer.Start();
pythonThread = Helpers.NewThread(new ThreadStart(() =>
{
pythonengine.SetTrace(PythonTrace);
string output = "";
// ignore output, the trace handler above will print output
try
{
output = Execute(pythonengine, scriptscope, script);
}
catch (ThreadAbortException)
{
// python was interrupted
Thread.ResetAbort();
}
linenumTimer.Stop();
pythonengine.SetTrace(null);
this.BeginInvoke(new Action(() =>
{
pythonThread = null;
scriptOutput.Text += output;
scriptOutput.SelectionStart = scriptOutput.TextLength;
scriptOutput.ScrollToCaret();
SetLineNumber(linenum);
EnableButtons(true);
}));
}));
pythonThread.Start();
}
private string ValidData(IDataObject d)
{
var fmts = new List<string>(d.GetFormats());
if (fmts.Contains("FileName"))
{
var data = d.GetData("FileName") as Array;
if (data != null && data.Length == 1 && data.GetValue(0) is string)
{
var filename = (string)data.GetValue(0);
try
{
if (File.Exists(filename) && Path.GetExtension(filename).ToUpperInvariant() == ".PY")
return Path.GetFullPath(filename);
}
catch (ArgumentException)
{
// invalid path etc
}
}
}
return "";
}
private void shell_DragEnter(object sender, DragEventArgs e)
{
if (ValidData(e.Data).Length > 0)
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void shell_DragDrop(object sender, DragEventArgs e)
{
string fn = ValidData(e.Data);
if (fn.Length > 0)
{
try
{
scriptEditor.Text = File.ReadAllText(fn);
}
catch (System.Exception ex)
{
MessageBox.Show("Couldn't open file " + saveDialog.FileName + Environment.NewLine + ex.ToString(), "Cannot open script",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
mode_Changed(scriptMode, null);
}
}
private void openButton_Click(object sender, EventArgs e)
{
DialogResult res = openDialog.ShowDialog();
if (res == DialogResult.OK)
{
try
{
scriptEditor.Text = File.ReadAllText(openDialog.FileName);
}
catch (System.Exception ex)
{
MessageBox.Show("Couldn't load from " + openDialog.FileName + Environment.NewLine + ex.ToString(), "Cannot open script",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void saveAs_Click(object sender, EventArgs e)
{
DialogResult res = saveDialog.ShowDialog();
if (res == DialogResult.OK)
{
try
{
File.WriteAllText(saveDialog.FileName, scriptEditor.Text);
}
catch (System.Exception ex)
{
MessageBox.Show("Couldn't save to " + saveDialog.FileName + Environment.NewLine + ex.ToString(), "Cannot save script",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void newScript_Click(object sender, EventArgs e)
{
scriptEditor.Text = String.Format("# RenderDoc Python scripts, powered by IronPython {0}\n" +
"# The 'pyrenderdoc' object is the Core class instance.\n" +
"# The 'renderdoc' module is available, as the matching namespace in C#\n\n",
IronPython.CurrentVersion.AssemblyFileVersion);
if (!m_LibsLoaded)
{
scriptEditor.Text += "# !!! pythonlibs.zip not found! Check installation !!!\n" +
"# !!! If building locally, ensure you have compiled python libraries: !!!\n" +
"# !!! Download IronPython-2.7.4 package, run this command and rebuild renderdocui !!!\n" +
"# cd renderdocui/3rdparty/ironpython/ && ./compilelibs.sh /path/to/IronPython-2.7.4\n\n";
}
scriptEditor.Text = scriptEditor.Text.Replace("\n", Environment.NewLine);
}
private void linenumTimer_Tick(object sender, EventArgs e)
{
SetLineNumber(linenum);
}
}
}