BioGTK  6.7.0
A .NET library & program for annotating, editing various microscopy imaging formats using Bioformats supported images. Including whole slide, pyramidal, and series.
Loading...
Searching...
No Matches
Scripting.cs
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.ComponentModel;
5using System.Data;
6using System.Linq;
7using System.Text;
8using System.Threading.Tasks;
9using System.IO;
10using System.Threading;
11using CSScripting;
12using csscript;
13using CSScriptLib;
14using Gtk;
15using AForge;
16using BioGTK;
17using System.Reflection.Metadata;
18
19namespace BioGTK
20{
21 public class Scripting : Window
22 {
23 #region Properties
24 private Builder _builder;
25
26#pragma warning disable 649
27 [Builder.Object]
28 private TreeView scriptView;
29 [Builder.Object]
30 private TextView view;
31 [Builder.Object]
32 private TextView outputBox;
33 [Builder.Object]
34 private TextView errorBox;
35 [Builder.Object]
36 private TextView logBox;
37 [Builder.Object]
38 private Button scriptLoadBut;
39 [Builder.Object]
40 private Button saveBut;
41 [Builder.Object]
42 private Button runBut;
43 [Builder.Object]
44 private Button stopBut;
45 [Builder.Object]
46 private Label scriptLabel;
47 [Builder.Object]
48 private CheckButton headlessBox;
49 [Builder.Object]
50 private Notebook tabsView;
51#pragma warning restore 649
52
53 #endregion
54
55 #region Constructors / Destructors
60 public static Scripting Create()
61 {
62 Builder builder = new Builder(new FileStream(System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "/" + "Glade/Scripting.glade", FileMode.Open));
63 return new Scripting(builder, builder.GetObject("scripting").Handle);
64 }
65
66 /* Creating a new instance of the Scripting class. */
67 protected Scripting(Builder builder, IntPtr handle) : base(handle)
68 {
69 _builder = builder;
70 builder.Autoconnect(this);
71 scriptView.RowActivated += ScriptView_RowActivated;
72 scriptView.ButtonPressEvent += ScriptView_ButtonPressEvent;
73 this.KeyPressEvent += Scripting_KeyPressEvent;
74 saveBut.ButtonPressEvent += SaveBut_ButtonPressEvent;
75 runBut.ButtonPressEvent += runButton_Click;
76 scriptLoadBut.ButtonPressEvent += scriptLoadBut_Click;
77 outputBox.ButtonPressEvent += OutputBox_ButtonPressEvent;
78 errorBox.ButtonPressEvent += OutputBox_ButtonPressEvent;
79 logBox.ButtonPressEvent += OutputBox_ButtonPressEvent;
80 stopBut.ButtonPressEvent += stopBut_Click;
81 tabsView.SwitchPage += TabsView_SwitchPage;
82 window = this;
83 if (!Directory.Exists(System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "//" + "Scripts"))
84 Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "//" + "Scripts");
85 if (!Directory.Exists(System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "//" + "Tools"))
86 Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "//" + "Tools");
87 InitItems();
88 scriptLabel.Text = "NewScript.cs";
89 App.ApplyStyles(this);
90 }
91
98 private void TabsView_SwitchPage(object o, SwitchPageArgs args)
99 {
100 logBox.Buffer.Text = log;
101 errorBox.Buffer.Text = error;
102 outputBox.Buffer.Text = output;
103 }
104
110 private void OutputBox_ButtonPressEvent(object o, ButtonPressEventArgs args)
111 {
112 logBox.Buffer.Text = log;
113 errorBox.Buffer.Text = error;
114 outputBox.Buffer.Text = output;
115 }
116
122 private void ScriptView_ButtonPressEvent(object o, ButtonPressEventArgs args)
123 {
124 RefreshItems();
125 }
126
131 private void SaveBut_ButtonPressEvent(object o, ButtonPressEventArgs args)
132 {
133 Save();
134 }
135
141 private void Scripting_KeyPressEvent(object o, KeyPressEventArgs args)
142 {
143 if (args.Event.Key == Gdk.Key.s && args.Event.State == Gdk.ModifierType.ControlMask)
144 {
145 Save();
146 }
147 }
148
155 private void ScriptView_RowActivated(object o, RowActivatedArgs args)
156 {
157 TreeView treeView = (TreeView)o;
158 TreePath path = args.Path;
159 TreeIter iter;
160
161 // Get the TreeIter for the selected row
162 if (treeView.Model.GetIter(out iter, path))
163 {
164 // Get the value of the "Text" column for the selected row
165 string text = (string)treeView.Model.GetValue(iter, 0);
166 if (scripts.ContainsKey(text))
167 {
168 selectedItem = scripts[text];
169 view.Buffer.Text = selectedItem.scriptString;
170 scriptLabel.Text = selectedItem.name;
171 }
172 }
173 }
174 #endregion
175
176 /* Creating a static class called Window, and a static string called log. */
177 public static Window window;
178 /* Declaring a static variable called log. */
179 public static string log;
180 public static string output;
181 public static string error;
182 public static string ImageJPath = Fiji.ImageJPath;
183 public static Dictionary<string,Script> scripts = new Dictionary<string,Script>();
184 public static void LogLine(string s)
185 {
186 log += s + Environment.NewLine;
187 }
188 /* It takes a string, adds using statements, wraps it in a class, and then runs it */
189 public class Script
190 {
191 public string name;
192 public string file;
193 public string scriptString;
194 public bool exit = false;
195 public dynamic script;
196 public object obj;
197 public string output = "";
198 public bool done = false;
199 public static List<string> usings = new List<string>();
200 public Exception ex = null;
201 public Thread thread;
202 public ScriptType type = ScriptType.script;
203 /* Creating a new script object. */
204 public Script(string file, string scriptStr)
205 {
206 name = System.IO.Path.GetFileName(file);
207 scriptString = scriptStr;
208 if (file.EndsWith(".txt") || file.EndsWith(".ijm"))
209 type = ScriptType.imagej;
210 }
211 /* Reading the file and storing the file name, file path, and file contents in the
212 variables name, file, and scriptString. */
213 public Script(string file)
214 {
215 name = System.IO.Path.GetFileName(file);
216 scriptString = File.ReadAllText(file);
217 this.file = file;
218 if (file.EndsWith(".txt") || file.EndsWith(".ijm"))
219 type = ScriptType.imagej;
220 }
225 public static void Run(Script rn)
226 {
227 scriptName = rn.name;
228 Thread t = new Thread(new ThreadStart(RunScript));
229 t.Start();
230 }
231 private static string scriptName = "";
232 private static string str = "";
234 private static async void RunScript()
235 {
236 Script rn = scripts[scriptName];
237 rn.ex = null;
238 if (rn.type == ScriptType.imagej)
239 {
240 try
241 {
242 rn.done = false;
243 if (App.UseFiji)
244 await Fiji.RunStringFiji(ImageView.SelectedImage,rn.scriptString, "", false);
245 else
246 ImageJ.RunString(ImageView.SelectedImage, rn.scriptString, "", false);
247 rn.done = true;
248 }
249 catch (Exception e)
250 {
251 rn.ex = e;
252 }
253 }
254 else
255 {
256 try
257 {
258 rn.done = false;
259 rn.script = CSScript.Evaluator.LoadCode(rn.scriptString);
260 rn.obj = rn.script.Load();
261 rn.output = rn.obj.ToString();
262 rn.done = true;
263
264 }
265 catch (Exception e)
266 {
267 rn.ex = e;
268 error = e.Message + Environment.NewLine + e.StackTrace;
269 }
270 }
271 }
278 public static object RunString(string st)
279 {
280 try
281 {
282 string loader =
283 @"//css_reference " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + @".dll
284 using System;
285 using Gtk;
286 using System.Threading;
287 using BioGTK;
288 using AForge;";
289 foreach (string s in usings)
290 {
291 loader += usings + Environment.NewLine;
292 }
293 loader += @"
294 public class Loader
295 {
296 public object Load()
297 {" +
298 st + @";
299 return true;
300 }
301 }";
302 dynamic script = CSScript.Evaluator.LoadCode(loader);
303 return script.Load();
304 }
305 catch (Exception e)
306 {
307 MessageDialog md = new MessageDialog(window,
308 DialogFlags.DestroyWithParent, MessageType.Info,
309 ButtonsType.Close, e.Message + ", " + e.Source);
310 return e;
311 }
312 }
314 public void Run()
315 {
316 if (!scripts.ContainsKey(name))
317 scripts.Add(name, this);
318 scriptName = this.name;
319 thread = new Thread(new ThreadStart(RunScript));
320 thread.Start();
321 }
323 public void Stop()
324 {
325 exit = true;
326 }
331 public override string ToString()
332 {
333 if (thread != null)
334 {
335 return name.ToString() + ", " + thread.ThreadState.ToString();
336 }
337 else
338 return name.ToString();
339 }
340 }
341 /* It's a class that represents a mouse event */
342 /* It's a class that holds the state of the mouse */
343 public class State
344 {
345 public Event type;
353 public static State GetUp(PointD pf,uint mb)
354 {
355
356 State st = new State();
357 st.type = Event.Up;
358 st.p = pf;
359 st.buts = mb;
360 return st;
361 }
369 public static State GetMove(PointD pf, uint mb)
370 {
371 State st = new State();
372 st.type = Event.Move;
373 st.p = pf;
374 st.buts = mb;
375 return st;
376 }
377
382 public static State GetDown(PointD pf, uint mb)
383 {
384 State st = new State();
385 st.type = Event.Down;
386 st.p = pf;
387 st.buts = mb;
388 return st;
389 }
390
395 public static State GetNone()
396 {
397 State st = new State();
398 st.type = Event.None;
399 st.p = new PointD();
400 st.buts = 0;
401 return st;
402 }
403
404 public PointD p;
405 public uint buts;
406 public bool processed = false;
407 public Gdk.Key? key;
408 public override string ToString()
409 {
410 return type.ToString() + " ,(" + p.X.ToString() + ", " + p.Y.ToString() + "), " + buts.ToString();
411 }
412
413 }
414 /* Defining an enum. */
415 public enum Event
416 {
417 Down,
418 Up,
419 Move,
420 None
421 }
422 /* Defining an enum. */
423 public enum ScriptType
424 {
425 tool,
426 script,
427 imagej
428 }
429 Script selectedItem;
430 private Script SelectedItem
431 {
432 get
433 {
434 return selectedItem;
435 }
436 }
437 private static State state;
441 public static State GetState()
442 {
443 return state;
444 }
445
446 public static bool Exit(string name)
447 {
448 if(scripts.ContainsKey(name))
449 {
450 return scripts[name].exit;
451 }
452 return false;
453 }
454
462 public static void UpdateState(State s)
463 {
464 if (s == null)
465 return;
466 if (state == null)
467 state = s;
468 if (s.p.X == state.p.X && s.p.Y == state.p.Y && s.type == state.type)
469 {
470 state.processed = true;
471 }
472 else
473 state = s;
474 }
476 public void InitItems()
477 {
478 Gtk.TreeViewColumn typeCol = new Gtk.TreeViewColumn();
479 typeCol.Title = "Script";
480 Gtk.CellRendererText typeCell = new Gtk.CellRendererText();
481 typeCol.PackStart(typeCell, true);
482 scriptView.AppendColumn(typeCol);
483 typeCol.AddAttribute(typeCell, "text", 0);
484
485 Gtk.TreeViewColumn statCol = new Gtk.TreeViewColumn();
486 statCol.Title = "Status";
487 Gtk.CellRendererText statCell = new Gtk.CellRendererText();
488 statCol.PackStart(statCell, true);
489 scriptView.AppendColumn(statCol);
490 statCol.AddAttribute(statCell, "text", 1);
491
492 Gtk.TreeStore store = new Gtk.TreeStore(typeof(string), typeof(string));
493 scriptView.Model = store;
494 scripts.Clear();
495 string st = System.IO.Path.GetDirectoryName(Environment.ProcessPath);
496 foreach (string file in Directory.GetFiles(st + "/Scripts"))
497 {
498 if (!scripts.ContainsKey(System.IO.Path.GetFileName(file)))
499 {
500 Script sc = new Script(file, File.ReadAllText(file));
501 if(sc.thread == null)
502 store.AppendValues(sc.name, ThreadState.Unstarted.ToString());
503 else
504 store.AppendValues(sc.name, sc.thread.ThreadState.ToString());
505 scripts.Add(sc.name, sc);
506 }
507 }
508 foreach (string file in Directory.GetFiles(st + "/Tools"))
509 {
510 if (file.EndsWith(".cs"))
511 {
512 if (!scripts.ContainsKey(System.IO.Path.GetFileName(file)))
513 {
514 Script sc = new Script(file, File.ReadAllText(file));
515 if (sc.thread == null)
516 store.AppendValues(sc.name, ThreadState.Unstarted.ToString());
517 else
518 store.AppendValues(sc.name, sc.thread.ThreadState.ToString());
519 scripts.Add(sc.name, sc);
520 }
521 }
522 }
523 }
524
526 public void RefreshItems()
527 {
528 Gtk.TreeStore store = new Gtk.TreeStore(typeof(string), typeof(string));
529 foreach (Script sc in scripts.Values)
530 {
531 if (sc.thread == null)
532 store.AppendValues(sc.name, ThreadState.Unstarted.ToString());
533 else
534 store.AppendValues(sc.name, sc.thread.ThreadState.ToString());
535 }
536 scriptView.Model = store;
537 }
538 /*
539 public void RefreshStatus()
540 {
541 errorBox.Buffer.Text = "";
542 RefreshItems();
543 foreach (ListViewItem item in scriptView.SelectedItems)
544 {
545 Script s = (Script)item.Tag;
546 //We update item text to show Script status.
547 item.Text = s.ToString();
548 outputBox.Buffer.Text = s.output;
549 if (s.ex != null)
550 {
551 string[] sps = s.ex.Message.Split('>');
552 //ListViewItem it = new ListViewItem(s.ex.ToString());
553 for (int i = 1; i < sps.Length; i++)
554 {
555 ListViewItem er = new ListViewItem(sps[i]);
556 er.Tag = s.ex;
557 errorView.Items.Add(er);
558 }
559
560 }
561 }
562 foreach (ListViewItem item in scriptView.SelectedItems)
563 {
564 Script s = (Script)item.Tag;
565 //We update item text to show Script status.
566 item.Text = s.ToString();
567 }
568 logBox.Buffer.Text = log;
569 //We scroll to end of text so we see latest log output.
570 if (logBox.SelectionStart != logBox.Buffer.Text.Length)
571 {
572 logBox.SelectionStart = logBox.Buffer.Text.Length;
573 logBox.ScrollToCaret();
574 }
575 }
576 */
580 public static void RunByName(string name)
581 {
582 scripts[name].Run();
583 }
587 public void RunScriptFile(string file)
588 {
589 Script sc = new Script(file);
590 scripts.Add(sc.name,sc);
591 RefreshItems();
592 RunByName(sc.name);
593 }
597 public static void RunScript(string file)
598 {
599 Script sc = new Script(file);
600 scripts.Add(sc.name, sc);
601 RunByName(sc.name);
602 }
606 public static object RunString(string st)
607 {
608 return Script.RunString(st);
609 }
613 public void Run()
614 {
615 log = "";
616 outputBox.Buffer.Text = "";
617 logBox.Buffer.Text = "";
618 if (SelectedItem == null)
619 return;
620 //We run this script
621 Script sc = SelectedItem;
622 sc.scriptString = view.Buffer.Text;
623 sc.output = "";
624 sc.Run();
625 outputBox.Buffer.Text = sc.output;
626 logBox.Buffer.Text = log;
627 RefreshItems();
628 }
632 public void Stop()
633 {
634 if (SelectedItem == null)
635 return;
636 //We stop this script
637 SelectedItem.Stop();
638 RefreshItems();
639 }
644 private void runToolStripMenuItem_Click(object sender, EventArgs e)
645 {
646 Run();
647 }
652 private void openScriptFolderToolStripMenuItem_Click(object sender, EventArgs e)
653 {
654 string path = System.IO.Path.GetDirectoryName(Environment.ProcessPath) + "\\Scripts";
655 System.Diagnostics.Process.Start("explorer.exe", path);
656 }
661 private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
662 {
663 RefreshItems();
664 }
665 /*
666 private void scriptView_SelectedIndexChanged(object sender, EventArgs e)
667 {
668 if (scriptView.SelectedItems.Count == 0)
669 return;
670 ListViewItem item = scriptView.SelectedItems[0];
671 Script s = (Script)item.Tag;
672 textBox.Buffer.Text = s.scriptString;
673 scriptLabel.Text = s.name;
674 }
675 */
680 private void runButton_Click(object sender, ButtonPressEventArgs args)
681 {
682 if (scriptLabel.Text.EndsWith(".ijm"))
683 {
684 if (App.UseFiji)
685 Fiji.RunStringFiji(ImageView.SelectedImage,view.Buffer.Text, ImageView.SelectedImage.ID, headlessBox.Active);
686 else
687 ImageJ.RunString(ImageView.SelectedImage, view.Buffer.Text, ImageView.SelectedImage.ID, headlessBox.Active);
688 }
689 else
690 Run();
691 }
692
699 private void scriptLoadBut_Click(object sender, ButtonPressEventArgs args)
700 {
701 Gtk.FileChooserDialog filechooser =
702 new Gtk.FileChooserDialog("Choose script file to open",
703 this,
704 FileChooserAction.Open,
705 "Cancel", ResponseType.Cancel,
706 "Save", ResponseType.Accept);
707 filechooser.SetCurrentFolder(System.IO.Path.GetDirectoryName(Environment.ProcessPath));
708 if (filechooser.Run() != (int)ResponseType.Accept)
709 return;
710
711 Script script = new Script(filechooser.Filename, File.ReadAllText(filechooser.Filename));
712 script.name = System.IO.Path.GetFileName(filechooser.Filename);
713 view.Buffer.Text = script.scriptString;
714 scriptLabel.Text = System.IO.Path.GetFileName(filechooser.Filename);
715
716 scripts.Add(script.name, script);
717 RefreshItems();
718 }
719
725 private void Save()
726 {
727 Gtk.FileChooserDialog filechooser =
728 new Gtk.FileChooserDialog("Choose script filename to save",
729 this,
730 FileChooserAction.Save,
731 "Cancel", ResponseType.Cancel,
732 "Save", ResponseType.Accept);
733 filechooser.SetCurrentFolder(System.IO.Path.GetDirectoryName(Environment.ProcessPath));
734 if (filechooser.Run() != (int)ResponseType.Accept)
735 return;
736 scriptLabel.Text = System.IO.Path.GetFileName(filechooser.Filename);
737 File.WriteAllText(filechooser.Filename, view.Buffer.Text);
738 if(!scripts.ContainsKey(scriptLabel.Text))
739 {
740 scripts.Add(scriptLabel.Text,new Script(filechooser.Filename, view.Buffer.Text));
741 }
742 RefreshItems();
743 filechooser.Destroy();
744 }
745
750 private void stopBut_Click(object sender, ButtonPressEventArgs args)
751 {
752 Stop();
753 }
754
755 /*
756 private void errorBox_SelectionChanged(object sender, EventArgs e)
757 {
758 Script sc = (Script)scriptView.SelectedItems[0].Tag;
759 Exception ex = sc.ex;
760 }
761
762 private void errorView_SelectedIndexChanged(object sender, EventArgs e)
763 {
764 Exception ex = (Exception)errorView.SelectedItems[0].Tag;
765 string exs = ex.Message.Substring(ex.Message.IndexOf('('), ex.Message.IndexOf(')'));
766 string ls = exs.Substring(1, exs.IndexOf(',')-1);
767 int line = int.Parse(ls);
768 string c = exs.Substring(exs.IndexOf(',') + 1, exs.IndexOf(")") - exs.IndexOf(',') - 1);
769 int cr = int.Parse(c);
770 }
771 */
772 }
773}
void Stop()
It stops the thread.
Definition Scripting.cs:323
static void Run(Script rn)
Definition Scripting.cs:225
static object RunString(string st)
Definition Scripting.cs:278
override string ToString()
Definition Scripting.cs:331
void Run()
It creates a new thread and starts it.
Definition Scripting.cs:314
static State GetDown(PointD pf, uint mb)
Definition Scripting.cs:382
static State GetUp(PointD pf, uint mb)
Definition Scripting.cs:353
static State GetNone()
Definition Scripting.cs:395
static State GetMove(PointD pf, uint mb)
Definition Scripting.cs:369
void RunScriptFile(string file)
Definition Scripting.cs:587
static void RunByName(string name)
Definition Scripting.cs:580
void InitItems()
It loads all the scripts in the Scripts and Tools folders into the TreeView.
Definition Scripting.cs:476
void RefreshItems()
It takes the list of scripts and puts them into a tree view.
Definition Scripting.cs:526
static Scripting Create()
Definition Scripting.cs:60
static object RunString(string st)
Definition Scripting.cs:606
static State GetState()
Definition Scripting.cs:441
static void UpdateState(State s)
Definition Scripting.cs:462
static void RunScript(string file)
Definition Scripting.cs:597
Definition ML.cs:17