-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathascx_Execute_Scripts.cs
More file actions
498 lines (442 loc) · 21 KB
/
ascx_Execute_Scripts.cs
File metadata and controls
498 lines (442 loc) · 21 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
// This file is part of the OWASP O2 Platform (http://www.owasp.org/index.php/OWASP_O2_Platform) and is released under the Apache 2.0 License (http://www.apache.org/licenses/LICENSE-2.0)
using System;
using System.Drawing;
using System.Windows.Forms;
using FluentSharp.REPL;
using FluentSharp.REPL.Controls;
using FluentSharp.WinForms;
using FluentSharp.WinForms.Controls;
using FluentSharp.WinForms.Utils;
using FluentSharp.CoreLib;
using FluentSharp.CoreLib.API;
using FluentSharp.REPL.Utils;
namespace FluentSharp.O2Platform.Controls
{
public class ascx_Execute_Scripts : UserControl
{
public string welcomeMessage = "Hello! To start right-click on the logo";
public string currentScript = "";
public CSharp_FastCompiler csharpCompiler;
public Action csharpCompiler_OnAstFail;
public Action csharpCompiler_OnAstOk;
public Action csharpCompiler_OnCompileFail;
public Action csharpCompiler_OnCompileOk;
//public Label statusLabel;
public RichTextBox results_RichTextBox;
public SplitContainer mainSplitContainer;
public ToolStripStatusLabel statusLabel;
public static string NEW_GUI_SCRIPT = "Main O2 Gui.h2";
public static void startControl_No_Args()
{
startControl("");
}
public static void startControl_With_Args(string[] args)
{
startControl(args);
}
public static void startControl(string scriptToExecute)
{
var formTitle = "{0} - Launcher".format(O2_Platform_Config.Current.Version_Name);
"{0}".info(formTitle);
var executeScripts = (ascx_Execute_Scripts)typeof(ascx_Execute_Scripts).showAsForm(formTitle, 340, 300);
if (executeScripts.isNull())
{
MessageBox.Show(@"Object Creation error in startControl", @"Start_O2 (ascx_Execute_Scripts)");
return;
}
"LocalScriptsFolder: {0}".debug(PublicDI.config.LocalScriptsFolder);
executeScripts.buildGui();
executeScripts.insert_LogViewer();
// see if there there is a script to execute
//(first via normal process arguments
if (scriptToExecute.valid() && scriptToExecute.fileExists())
executeScripts.runScriptAndCloseGui(scriptToExecute);
else
{
// load new gui
var newGuiScript = NEW_GUI_SCRIPT.local();
if (newGuiScript.fileExists())
{
executeScripts.currentScript = newGuiScript;
executeScripts.welcomeMessage = "New O2 GUI detected, launching it now...";
executeScripts.status(executeScripts.welcomeMessage);
{
O2Thread.mtaThread(() =>
{
loadNewGui(executeScripts);
});
}
}
//}
}
}
public static void startControl(string[] args)
{
if (args.notNull() && args.size() > 0)
{
var fileToExecute = args[0];
if (fileToExecute.fileExists().isFalse())
fileToExecute = fileToExecute.local();
startControl(fileToExecute);
}
else
startControl("");
}
public void runScriptAndCloseGui(string scriptToExecute)
{
"Found startup script (for execution): ".info(scriptToExecute);
this.loadFile(scriptToExecute);
this.csharpCompiler_OnCompileOk = () => { this.close(); };
}
private static void loadNewGui(ascx_Execute_Scripts executeScripts)
{
try
{
/* var cached_O2Main_WPF_GUI = PublicDI.config.CurrentExecutableDirectory.pathCombine(NEW_GUI_SCRIPT + ".cached.h2");
var cached_O2Main_WPF_GUI_Dll = PublicDI.config.CurrentExecutableDirectory.pathCombine(NEW_GUI_SCRIPT + ".cached.Dll");
if (cached_O2Main_WPF_GUI.fileExists().isFalse() ||
cached_O2Main_WPF_GUI.fileContents() != NEW_GUI_SCRIPT.local().fileContents())
{
Files.deleteFile(cached_O2Main_WPF_GUI);
Files.deleteFile(cached_O2Main_WPF_GUI_Dll);
Files.Copy(NEW_GUI_SCRIPT.local(), cached_O2Main_WPF_GUI);
var assembly = cached_O2Main_WPF_GUI.compile_H2Script();
var dllLocation = assembly.Location;
Files.Copy(dllLocation, cached_O2Main_WPF_GUI_Dll);
//we need to make this or the 2nd time around the dynamic compiled references will not be found
foreach (var referencedAssembly in assembly.GetReferencedAssemblies().toList())
{
var localPath = "{0}\\{1}.dll".format("".o2Temp2Dir(), referencedAssembly.Name);
if (localPath.fileExists())
// if (referencedAssembly.E.Location.starts())
Files.Copy(localPath, PublicDI.config.CurrentExecutableDirectory);
}
}
if (cached_O2Main_WPF_GUI_Dll.fileExists())
{
"Found local copy of precompiled {0} as {1}, so executing it".info(NEW_GUI_SCRIPT, cached_O2Main_WPF_GUI_Dll);
cached_O2Main_WPF_GUI_Dll.assembly().executeFirstMethod();
}
else
{
*/
var newGui = NEW_GUI_SCRIPT.compile_H2Script();
if (newGui.notNull())
{
newGui.executeFirstMethod();
"Welcome to O2 :)".info();
}
else
{
executeScripts.status("There was an error compiling the new GUI!");
/* if ("There was an error compiling the main O2 Script, do you want to clear the Compiled Cache and try again?".askUserQuestion())
{
CompileEngine.clearCompilationCache();
NEW_GUI_SCRIPT.compile_H2Script().executeFirstMethod();
}*/
}
// }
var currentWinForms = executeScripts.applicationWinForms();
if (currentWinForms.size() == 1)
{
// if ("The new GUI could not be launched, do you want download the latest version?".askUserQuestion())
// openBrowserWithDownloadLink();
}
else
executeScripts.close();
}
catch (Exception ex)
{
ex.log("in ascx_ExecuteScripts.loadNewGui()");
}
}
/*private static void openBrowserWithDownloadLink()
{
O2Gui.open<Panel>("Download new version of O2", 700, 500)
.add_Browser()
.open(PublicDI.config.O2DownloadLocation);
} */
public ascx_Execute_Scripts()
{
handleSpecialControlKeys();
}
public bool is32Bit()
{
if (@"C:\Program Files (x86)".dirExists())
{
"This is a 64bit OS".debug();
return false;
}
return true;
}
private void handleSpecialControlKeys()
{
if (Control.ModifierKeys == Keys.Shift)
openO2LogViewer();
}
private void buildGui()
{
this.invokeOnThread(
() =>
{
"Buliding Gui for ascx_ExecuteScripts.cs.o2".info();
// add controls
statusLabel = this.parentForm().add_StatusStrip(Color.White);
BackColor = Color.White;
var topPanel = this.add_Panel();
var pictureBox = topPanel.add_PictureBox();
statusLabel.IsLink = true;
statusLabel.LinkBehavior = LinkBehavior.NeverUnderline;
statusLabel.set_Text(welcomeMessage).textColor(this, Color.Black);
results_RichTextBox = this.add_RichTextBox();
mainSplitContainer = topPanel.insert_Below(results_RichTextBox, 100)
.get<SplitContainer>();
mainSplitContainer.panel2Collapsed(true);
setupPictureBoxContextMenu(pictureBox);
pictureBox.load(FormImages.O2_Logo);
this.onDrop((file) => loadFile(file));
statusLabel.Click += (sender, e) => openSimpleScriptEditor();
//statusLabel.textColor(this, Color.Black);
// put this on menu item
//this.add_Link("reload",10,2,()=>loadH2Script());
"Buliding Gui complete".info();
});
}
public void setupPictureBoxContextMenu(PictureBox pictureBox)
{
pictureBox.onDrop((file) => loadFile(file));
pictureBox.DoubleClick += (sender, e) => showAvailableScripts();
var contextMenu = pictureBox.add_ContextMenu();
contextMenu.add_MenuItem("View available scripts", () => showAvailableScripts());
contextMenu.add_MenuItem("Open O2 Command Prompt", () => openO2CommandPromt());
contextMenu.add_MenuItem("O2 Script Development && Debug")
.add_MenuItem("Open Source Code Editor", () => openSourceCodeEditor())
.add_MenuItem("Open Simple Script Editor", () => openSimpleScriptEditor())
.add_MenuItem("Open Quick development gui", () => executeScript("Opening Quick Development GUI", "ascx_Quick_Development_GUI.cs.o2"))
.add_MenuItem("Open 'Graph' development gui", () => executeScript("Opening Graph With Inspector)", "ascx_GraphWithInspector.cs"))
//.add_MenuItem("Open XRules/Script Editor", () => open.scriptEditor())
.add_MenuItem("Show O2 Object Model", () => open.o2ObjectModel())
.add_MenuItem("Show O2 Executable Directry", () => open.directory(PublicDI.config.CurrentExecutableDirectory, true))
.add_MenuItem("Current Script", false)
.add_MenuItem("View loaded script source Code", () => showLoadedScriptSourceCode())
.add_MenuItem("Execute Again", executeCompiledCode);
contextMenu.add_MenuItem("Tools")
//.add_MenuItem("Image Screenshot tool", () => screenShotTool())
.add_MenuItem("MediaWiki Editor", () => executeScript("Opening MediaWiki Client)", "MediaWikiEditor.cs.o2"))
.add_MenuItem("Twitter Client", () => executeScript("Opening Twitter Client)", "Twitter Client.h2"))
.add_MenuItem("Simple Text Editor", () => executeScript("Opening Simple Text Editor", "Simple Text Editor.h2"))
.add_MenuItem("O2 'Secret Data' Editor", () => executeScript("Opening 'Secret Data Editor'", "SecretDataEditor.cs.o2"));
//.add_MenuItem("O2 'Secret Data' Editor", () => new SecretDataEditor().showGui());
contextMenu.add_MenuItem("Open O2 Log Viewer", openO2LogViewer);
contextMenu.add_MenuItem("Exit Application (and close all windows)", () => PublicDI.config.closeO2Process());
}
public ascx_Execute_Scripts execute(string infoMessage, MethodInvoker codeToExecute)
{
showInfo(infoMessage);
codeToExecute();
return this;
}
public ascx_Execute_Scripts executeScript(string infoMessage, string scriptToExecute)
{
showInfo(infoMessage);
scriptToExecute.executeFirstMethod();
return this;
}
public void loadH2Script()
{
loadFile(currentScript);
}
public object loadFile(string fileToLoad)
{
if (fileToLoad.isImage())
{
statusLabel.set_Text("showing image: {0}".format(fileToLoad));
return show.image(fileToLoad);
}
if (fileToLoad.isText())
{
statusLabel.set_Text("showing text file: {0}".format(fileToLoad));
return show.file(fileToLoad);
}
if (fileToLoad.isDocument())
{
statusLabel.set_Text("showing rtf document: {0}".format(fileToLoad));
return show.document(fileToLoad);
}
loadH2Script(fileToLoad);
return null;
}
public void loadH2Script(string scriptToLoad)
{
O2Thread.mtaThread(() =>
{
if (scriptToLoad.fileName().starts(this.typeName()))
{
PublicDI.log.error("We can execute the current type of we will get a recursive load :)");
return;
}
currentScript = scriptToLoad;
statusLabel.set_Text("loading script: {0}".format(scriptToLoad.fileName()));
csharpCompiler = new CSharp_FastCompiler();
csharpCompiler.set_OnAstFail(() =>
{
showError("Ast creation failed", csharpCompiler.astErrors());
csharpCompiler_OnAstFail.invoke();
});
csharpCompiler.set_OnAstOK (() =>
{
showInfo("Ast creation Ok");
csharpCompiler_OnAstOk.invoke();
});
csharpCompiler.set_OnCompileFail(() =>
{
showError("Compilation failed", csharpCompiler.compilationErrors());
csharpCompiler_OnCompileFail.invoke();
});
csharpCompiler.set_OnCompileOK(() =>
{
showInfo("Compilation Ok: Executing 1st method");
csharpCompiler_OnCompileOk.invoke();
executeCompiledCode();
});
var sourceCode = "";
PublicDI.CurrentScript = scriptToLoad;
csharpCompiler.CompilerOptions.SourceCodeFile = scriptToLoad;
if (scriptToLoad.extension(".h2"))
sourceCode = H2.load(scriptToLoad).SourceCode;
if (scriptToLoad.extension(".o2") || scriptToLoad.extension(".cs"))
sourceCode = scriptToLoad.contents();
if (sourceCode.valid())
csharpCompiler.compileSnippet(sourceCode);
else
statusLabel.set_Text("Non supported file").textColor(this, Color.Red);
});
}
/*public string currentScript()
{
if (csharpCompiler.notNull() && csharpCompiler.SourceCodeFile.fileExists())
return csharpCompiler.SourceCodeFile.fileName();
return "";
}*/
public void showLoadedScriptSourceCode()
{
if (currentScript.fileExists())
{
var sourceCodeEditor = (SourceCodeEditor)typeof(SourceCodeEditor)
.showAsForm("source code for: {0}".format(currentScript), 600, 200);
sourceCodeEditor.loadSourceCodeFile(currentScript);
}
}
public void mapFoldersAndFiles(TreeView targetTreeView, TreeNode treeNode)
{
targetTreeView.clear(treeNode);
var folder = treeNode.Tag.ToString();
foreach (var dir in folder.dirs())
if (dir.contains(".git").isFalse())
targetTreeView.add_Node(treeNode, dir.fileName(), dir, true)
.ForeColor = Color.SaddleBrown;
foreach (var file in folder.files())
targetTreeView.add_Node(treeNode, file.fileName(), file, false)
.ForeColor = Color.DarkBlue;
}
public void showAvailableScripts()
{
status("Showing available scripts");
//var path = XRules_Config.PathTo_XRulesDatabase_fromO2;
var path = PublicDI.config.LocalScriptsFolder;
//var treeView = new TreeView();
var treeView = (TreeView)WinForms_Show.showAscxInForm(typeof(TreeView), "O2 - Available scripts", 300, 300);
treeView.BeforeExpand += (sender, e) => mapFoldersAndFiles(treeView, e.Node);
treeView.NodeMouseDoubleClick += (sender, e) =>
{
var target = e.Node.Tag.ToString();
if (target.isFile())
loadFile(target);
};
// ReSharper disable ImplicitlyCapturedClosure
treeView.ItemDrag += (sender, e) =>
{
var node = (TreeNode)e.Item;
treeView.SelectedNode = node;
var target = node.Tag.ToString();
if (target.isFile())
treeView.DoDragDrop(target, DragDropEffects.Copy);
};
// ReSharper restore ImplicitlyCapturedClosure
var rootNode = treeView.add_Node("Scripts in: " + path + "", path, true);
mapFoldersAndFiles(treeView, rootNode);
treeView.expand(rootNode);
}
public void openSourceCodeEditor()
{
var sourceCodeEditor = O2Gui.open<Panel>("Source Code Editor", 600, 400).add_SourceCodeEditor();
var defaultSourceCode = CompileEngine.findScriptOnLocalScriptFolder("Hello_O2_World.cs").fileContents();
sourceCodeEditor.open(defaultSourceCode.saveWithExtension(".cs"));
}
public void openO2CommandPromt()
{
executeScript("Showing O2 CommandPromt", "ascx_O2_Command_Prompt.cs.o2");
//O2Utils.O2CommandPrompt.run();
}
public void openSimpleScriptEditor()
{
open.scriptEditor();
//executeScript("Showing Simple Script Editor", "ascx_Simple_Script_Editor.cs.o2");
//typeof(ascx_Simple_Script_Editor).showAsForm("Simple Script Editor", 600,400);
}
public void openO2LogViewer()
{
O2Gui.open<ascx_LogViewer>();
}
public void executeCompiledCode()
{
O2Thread.mtaThread(() =>
{
try
{
if (csharpCompiler != null)
//if (csharpCompiler.CompilerResults != null)
if (csharpCompiler.compiledAssembly() != null)
{
var result = csharpCompiler.executeFirstMethod();
showInfo("Execution Completed", result);
}
}
catch (Exception ex)
{
PublicDI.log.ex(ex, "in executeCompiledCode");
}
});
}
public void showError(string errorMessage, string errorDetails)
{
statusLabel.set_Text(errorMessage).textColor(this, Color.Red);
results_RichTextBox.set_Text(errorDetails).textColor(Color.Red);
mainSplitContainer.panel2Collapsed(false);
}
public void showInfo(string infoMessage)
{
showInfo(infoMessage, null);
}
public void showInfo(string infoMessage, object details)
{
infoMessage.info();
statusLabel.set_Text(infoMessage).textColor(this, Color.Green);
if (details != null)
{
var data = details.ToString();
if (data.valid())
{
results_RichTextBox.textColor(Color.Black).set_Text(data);
mainSplitContainer.panel2Collapsed(false);
return;
}
}
mainSplitContainer.panel2Collapsed(true);
}
public void status(string newStatusText)
{
statusLabel.set_Text(newStatusText).textColor(this, Color.Black);
}
}
}