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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using log4net;
namespace OpenSim.Framework.Console
{
public delegate void CommandDelegate(string module, string[] cmd);
public class Commands
{
private class CommandInfo
{
public string module;
public string help_text;
public string long_help;
public CommandDelegate fn;
}
private Dictionary<string, Object> tree =
new Dictionary<string, Object>();
public List<string> GetHelp()
{
List<string> help = new List<string>();
help.AddRange(CollectHelp(tree));
help.Sort();
return help;
}
private List<string> CollectHelp(Dictionary<string, Object> dict)
{
List<string> result = new List<string>();
foreach (KeyValuePair<string, object> kvp in dict)
{
if (kvp.Value is Dictionary<string, Object>)
{
result.AddRange(CollectHelp((Dictionary<string, Object>)kvp.Value));
}
else
{
if (((CommandInfo)kvp.Value).long_help != String.Empty)
result.Add(((CommandInfo)kvp.Value).help_text+" - "+
((CommandInfo)kvp.Value).long_help);
}
}
return result;
}
public void AddCommand(string module, string command, string help, string longhelp, CommandDelegate fn)
{
string[] parts = Parser.Parse(command);
Dictionary<string, Object> current = tree;
foreach (string s in parts)
{
if (current.ContainsKey(s))
{
if (current[s] is Dictionary<string, Object>)
{
current = (Dictionary<string, Object>)current[s];
}
else
return;
}
else
{
current[s] = new Dictionary<string, Object>();
current = (Dictionary<string, Object>)current[s];
}
}
if (current.ContainsKey(String.Empty))
return;
CommandInfo info = new CommandInfo();
info.module = module;
info.help_text = help;
info.long_help = longhelp;
info.fn = fn;
current[String.Empty] = info;
}
public string[] FindNextOption(string[] cmd, bool term)
{
Dictionary<string, object> current = tree;
int remaining = cmd.Length;
foreach (string s in cmd)
{
remaining--;
List<string> found = new List<string>();
foreach (string opt in current.Keys)
{
if (opt.StartsWith(s))
{
found.Add(opt);
}
}
if (found.Count == 1 && (remaining != 0 || term))
{
current = (Dictionary<string, object>)current[found[0]];
}
else if (found.Count > 0)
{
return found.ToArray();
}
else
{
break;
// return new string[] {"<cr>"};
}
}
if (current.Count > 1)
{
List<string> choices = new List<string>();
bool addcr = false;
foreach (string s in current.Keys)
{
if (s == String.Empty)
{
CommandInfo ci = (CommandInfo)current[String.Empty];
if (ci.fn != null)
addcr = true;
}
else
choices.Add(s);
}
if (addcr)
choices.Add("<cr>");
return choices.ToArray();
}
if (current.ContainsKey(String.Empty))
return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text};
return new string[] { new List<string>(current.Keys)[0] };
}
public string[] Resolve(string[] cmd)
{
string[] result = cmd;
int index = -1;
Dictionary<string, object> current = tree;
foreach (string s in cmd)
{
index++;
List<string> found = new List<string>();
foreach (string opt in current.Keys)
{
if (opt.StartsWith(s))
{
found.Add(opt);
}
}
if (found.Count == 1)
{
result[index] = found[0];
current = (Dictionary<string, object>)current[found[0]];
}
else if (found.Count > 0)
{
return new string[0];
}
else
{
break;
}
}
if (current.ContainsKey(String.Empty))
{
CommandInfo ci = (CommandInfo)current[String.Empty];
if (ci.fn == null)
return new string[0];
ci.fn(ci.module, result);
return result;
}
return new string[0];
}
}
public class Parser
{
public static string[] Parse(string text)
{
List<string> result = new List<string>();
int index;
string[] unquoted = text.Split(new char[] {'"'});
for (index = 0 ; index < unquoted.Length ; index++)
{
if (index % 2 == 0)
{
string[] words = unquoted[index].Split(new char[] {' '});
foreach (string w in words)
{
if (w != String.Empty)
result.Add(w);
}
}
else
{
result.Add(unquoted[index]);
}
}
return result.ToArray();
}
}
public class ConsoleBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly object m_syncRoot = new object();
private int y = -1;
private int cp = 0;
private int h = 1;
private string prompt = "# ";
private StringBuilder cmdline = new StringBuilder();
public Commands Commands = new Commands();
private bool echo = true;
private List<string> history = new List<string>();
public object ConsoleScene = null;
/// <summary>
/// The default prompt text.
/// </summary>
public string DefaultPrompt
{
set { m_defaultPrompt = value + "# "; }
get { return m_defaultPrompt; }
}
protected string m_defaultPrompt;
public ConsoleBase(string defaultPrompt)
{
DefaultPrompt = defaultPrompt;
Commands.AddCommand("console", "help", "help", "Get command list", Help);
}
private void AddToHistory(string text)
{
while (history.Count >= 100)
history.RemoveAt(0);
history.Add(text);
}
/// <summary>
/// derive an ansi color from a string, ignoring the darker colors.
/// This is used to help automatically bin component tags with colors
/// in various print functions.
/// </summary>
/// <param name="input">arbitrary string for input</param>
/// <returns>an ansii color</returns>
private static ConsoleColor DeriveColor(string input)
{
int colIdx = (input.ToUpper().GetHashCode() % 6) + 9;
return (ConsoleColor) colIdx;
}
/// <summary>
/// Sends a warning to the current console output
/// </summary>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Warn(string format, params object[] args)
{
WriteNewLine(ConsoleColor.Yellow, format, args);
}
/// <summary>
/// Sends a warning to the current console output
/// </summary>
/// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Warn(string sender, string format, params object[] args)
{
WriteNewLine(DeriveColor(sender), sender, ConsoleColor.Yellow, format, args);
}
/// <summary>
/// Sends a notice to the current console output
/// </summary>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Notice(string format, params object[] args)
{
WriteNewLine(ConsoleColor.White, format, args);
}
/// <summary>
/// Sends a notice to the current console output
/// </summary>
/// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Notice(string sender, string format, params object[] args)
{
WriteNewLine(DeriveColor(sender), sender, ConsoleColor.White, format, args);
}
/// <summary>
/// Sends an error to the current console output
/// </summary>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Error(string format, params object[] args)
{
WriteNewLine(ConsoleColor.Red, format, args);
}
/// <summary>
/// Sends an error to the current console output
/// </summary>
/// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Error(string sender, string format, params object[] args)
{
WriteNewLine(DeriveColor(sender), sender, ConsoleColor.Red, format, args);
}
/// <summary>
/// Sends a status message to the current console output
/// </summary>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Status(string format, params object[] args)
{
WriteNewLine(ConsoleColor.Blue, format, args);
}
/// <summary>
/// Sends a status message to the current console output
/// </summary>
/// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Status(string sender, string format, params object[] args)
{
WriteNewLine(DeriveColor(sender), sender, ConsoleColor.Blue, format, args);
}
[Conditional("DEBUG")]
public void Debug(string format, params object[] args)
{
WriteNewLine(ConsoleColor.Gray, format, args);
}
[Conditional("DEBUG")]
public void Debug(string sender, string format, params object[] args)
{
WriteNewLine(DeriveColor(sender), sender, ConsoleColor.Gray, format, args);
}
private void WriteNewLine(ConsoleColor senderColor, string sender, ConsoleColor color, string format, params object[] args)
{
lock (cmdline)
{
if (y != -1)
{
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
int count = cmdline.Length;
System.Console.Write(" ");
while (count-- > 0)
System.Console.Write(" ");
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
}
WritePrefixLine(senderColor, sender);
WriteConsoleLine(color, format, args);
if (y != -1)
y = System.Console.CursorTop;
}
}
private void WriteNewLine(ConsoleColor color, string format, params object[] args)
{
lock (cmdline)
{
if (y != -1)
{
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
int count = cmdline.Length;
System.Console.Write(" ");
while (count-- > 0)
System.Console.Write(" ");
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
}
WriteConsoleLine(color, format, args);
if (y != -1)
y = System.Console.CursorTop;
}
}
private void WriteConsoleLine(ConsoleColor color, string format, params object[] args)
{
try
{
lock (m_syncRoot)
{
try
{
if (color != ConsoleColor.White)
System.Console.ForegroundColor = color;
System.Console.WriteLine(format, args);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(format, args);
}
catch (FormatException)
{
System.Console.WriteLine(args);
}
}
}
catch (ObjectDisposedException)
{
}
}
private void WritePrefixLine(ConsoleColor color, string sender)
{
try
{
lock (m_syncRoot)
{
sender = sender.ToUpper();
System.Console.WriteLine("[" + sender + "] ");
System.Console.Write("[");
try
{
System.Console.ForegroundColor = color;
System.Console.Write(sender);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(sender);
}
System.Console.Write("] \t");
}
}
catch (ObjectDisposedException)
{
}
}
private void Help(string module, string[] cmd)
{
List<string> help = Commands.GetHelp();
foreach (string s in help)
Output(s);
}
private void Show()
{
lock (cmdline)
{
if (y == -1 || System.Console.BufferWidth == 0)
return;
int xc = prompt.Length + cp;
int new_x = xc % System.Console.BufferWidth;
int new_y = y + xc / System.Console.BufferWidth;
int end_y = y + (cmdline.Length + prompt.Length) / System.Console.BufferWidth;
if (end_y / System.Console.BufferWidth >= h)
h++;
if (end_y >= System.Console.BufferHeight) // wrap
{
y--;
new_y--;
System.Console.CursorLeft = 0;
System.Console.CursorTop = System.Console.BufferHeight-1;
System.Console.WriteLine(" ");
}
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
if (echo)
System.Console.Write("{0}{1}", prompt, cmdline);
else
System.Console.Write("{0}", prompt);
System.Console.CursorLeft = new_x;
System.Console.CursorTop = new_y;
}
}
public void LockOutput()
{
System.Threading.Monitor.Enter(cmdline);
try
{
if (y != -1)
{
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
int count = cmdline.Length + prompt.Length;
while (count-- > 0)
System.Console.Write(" ");
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
}
}
catch (Exception)
{
}
}
public void UnlockOutput()
{
if (y != -1)
{
y = System.Console.CursorTop;
Show();
}
System.Threading.Monitor.Exit(cmdline);
}
public void Output(string text)
{
lock (cmdline)
{
if (y == -1)
{
System.Console.WriteLine(text);
return;
}
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
int count = cmdline.Length + prompt.Length;
while (count-- > 0)
System.Console.Write(" ");
System.Console.CursorTop = y;
System.Console.CursorLeft = 0;
System.Console.WriteLine(text);
y = System.Console.CursorTop;
Show();
}
}
private void ContextHelp()
{
string[] words = Parser.Parse(cmdline.ToString());
string[] opts = Commands.FindNextOption(words, cmdline.ToString().EndsWith(" "));
if (opts[0].StartsWith("Command help:"))
Output(opts[0]);
else
Output(String.Format("Options: {0}", String.Join(" ", opts)));
}
public void Prompt()
{
string line = ReadLine(m_defaultPrompt, true, true);
if (line != String.Empty)
{
m_log.Info("Invalid command");
}
}
public string CmdPrompt(string p)
{
return ReadLine(String.Format("{0}: ", p), false, true);
}
public string CmdPrompt(string p, string def)
{
string ret = ReadLine(String.Format("{0} [{1}]: ", p, def), false, true);
if (ret == String.Empty)
ret = def;
return ret;
}
// Displays a command prompt and returns a default value, user may only enter 1 of 2 options
public string CmdPrompt(string prompt, string defaultresponse, string OptionA, string OptionB)
{
bool itisdone = false;
string temp = CmdPrompt(prompt, defaultresponse);
while (itisdone == false)
{
if ((temp == OptionA) || (temp == OptionB))
{
itisdone = true;
}
else
{
System.Console.WriteLine("Valid options are " + OptionA + " or " + OptionB);
temp = CmdPrompt(prompt, defaultresponse);
}
}
return temp;
}
// Displays a prompt and waits for the user to enter a string, then returns that string
// (Done with no echo and suitable for passwords)
public string PasswdPrompt(string p)
{
return ReadLine(p, false, false);
}
public void RunCommand(string cmd)
{
string[] parts = Parser.Parse(cmd);
Commands.Resolve(parts);
}
public string ReadLine(string p, bool isCommand, bool e)
{
h = 1;
cp = 0;
prompt = p;
echo = e;
int historyLine = history.Count;
System.Console.CursorLeft = 0; // Needed for mono
System.Console.Write(" "); // Needed for mono
lock (cmdline)
{
y = System.Console.CursorTop;
cmdline.Remove(0, cmdline.Length);
}
while(true)
{
Show();
ConsoleKeyInfo key = System.Console.ReadKey(true);
char c = key.KeyChar;
if (!Char.IsControl(c))
{
if (cp >= 318)
continue;
if (c == '?' && isCommand)
{
ContextHelp();
continue;
}
cmdline.Insert(cp, c);
cp++;
}
else
{
switch (key.Key)
{
case ConsoleKey.Backspace:
if (cp == 0)
break;
cmdline.Remove(cp-1, 1);
cp--;
System.Console.CursorLeft = 0;
System.Console.CursorTop = y;
System.Console.Write("{0}{1} ", prompt, cmdline);
break;
case ConsoleKey.End:
cp = cmdline.Length;
break;
case ConsoleKey.Home:
cp = 0;
break;
case ConsoleKey.UpArrow:
if (historyLine < 1)
break;
historyLine--;
LockOutput();
cmdline.Remove(0, cmdline.Length);
cmdline.Append(history[historyLine]);
cp = cmdline.Length;
UnlockOutput();
break;
case ConsoleKey.DownArrow:
if (historyLine >= history.Count)
break;
historyLine++;
LockOutput();
if (historyLine == history.Count)
{
cmdline.Remove(0, cmdline.Length);
}
else
{
cmdline.Remove(0, cmdline.Length);
cmdline.Append(history[historyLine]);
}
cp = cmdline.Length;
UnlockOutput();
break;
case ConsoleKey.LeftArrow:
if (cp > 0)
cp--;
break;
case ConsoleKey.RightArrow:
if (cp < cmdline.Length)
cp++;
break;
case ConsoleKey.Enter:
System.Console.CursorLeft = 0;
System.Console.CursorTop = y;
System.Console.WriteLine("{0}{1}", prompt, cmdline);
lock (cmdline)
{
y = -1;
}
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdline.ToString()));
if (cmd.Length != 0)
{
int i;
for (i=0 ; i < cmd.Length ; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
AddToHistory(String.Join(" ", cmd));
return String.Empty;
}
}
AddToHistory(cmdline.ToString());
return cmdline.ToString();
default:
break;
}
}
}
}
}
}
|