[System.Net] Add support for .pac proxy config scripts on mac
[mono.git] / mcs / class / System / System.Diagnostics / DefaultTraceListener.cs
1 //
2 // System.Diagnostics.DefaultTraceListener.cs
3 //
4 // Authors:
5 //   Jonathan Pryor (jonpryor@vt.edu)
6 //   Atsushi Enomoto (atsushi@ximian.com)
7 //
8 // Comments from John R. Hicks <angryjohn69@nc.rr.com> original implementation 
9 // can be found at: /mcs/docs/apidocs/xml/en/System.Diagnostics
10 //
11 // (C) 2002 Jonathan Pryor
12 // (C) 2007 Novell, Inc.
13 //
14
15 //
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
23 // 
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
26 // 
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 //
35
36 using System;
37 using System.IO;
38 using System.Collections;
39 using System.Diagnostics;
40 using System.Reflection;
41 using System.Runtime.CompilerServices;
42 using System.Runtime.InteropServices;
43 using System.Threading;
44
45 namespace System.Diagnostics {
46         public class DefaultTraceListener : TraceListener {
47
48                 private static readonly bool OnWin32;
49
50                 private const string ConsoleOutTrace = "Console.Out";
51                 private const string ConsoleErrorTrace = "Console.Error";
52
53                 private static readonly string MonoTracePrefix;
54                 private static readonly string MonoTraceFile;
55
56                 static DefaultTraceListener ()
57                 {
58                         // Determine what platform we're on.  This impacts how where we send
59                         // messages.  On Win32 platforms (OnWin32 = true), we use the
60                         // `OutputDebugString' api.
61                         //
62                         // On Linux platforms, we use MONO_TRACE_LISTENER to figure things out.  See the
63                         // API documentation for more information on MONO_TRACE_LISTENER.
64                         OnWin32 = (Path.DirectorySeparatorChar == '\\');
65
66                         if (!OnWin32) {
67 #if TARGET_JVM
68                                 string trace = java.lang.System.getProperty("MONO_TRACE");
69 #else
70                                 // If we're running on Unix, we don't have OutputDebugString.
71                                 // Instead, send output to...wherever the MONO_TRACE_LISTENER environment
72                                 // variables says to.
73                                 String trace = Environment.GetEnvironmentVariable("MONO_TRACE_LISTENER");
74 #endif
75
76 #if MOBILE
77                                 if (trace == null)
78                                         trace = ConsoleOutTrace;
79 #endif
80
81                                 if (trace != null) {
82                                         string file = null;
83                                         string prefix = null;
84
85                                         if (trace.StartsWith (ConsoleOutTrace)) {
86                                                 file = ConsoleOutTrace;
87                                                 prefix = GetPrefix (trace, ConsoleOutTrace);
88                                         }
89                                         else if (trace.StartsWith (ConsoleErrorTrace)) {
90                                                 file = ConsoleErrorTrace;
91                                                 prefix = GetPrefix (trace, ConsoleErrorTrace);
92                                         }
93                                         else {
94                                                 file = trace;
95
96                                                 // We can't firgure out what the prefix would be, as ':' is a
97                                                 // valid filename character.  Thus, arbitrary files don't support
98                                                 // prefixes.
99                                                 //
100                                                 // I don't consider this to be a major issue.  Prefixes are useful 
101                                                 // with Console.Out and Console.Error to help separate trace
102                                                 // output from the actual program output.  Writing to an arbitrary
103                                                 // file doesn't introduce issues with disambiguation.
104                                                 prefix = "";
105                                         }
106
107                                         MonoTraceFile = file;
108                                         MonoTracePrefix = prefix;
109                                 }
110                         }
111                 }
112
113                 /**
114                  * Get the prefix for the specified variable.
115                  *
116                  * "Prefixes" are used in the MONO_TRACE_LISTENER variable, and specify text that
117                  * should precede each message printed to the console.  The prefix is
118                  * appended to the console location with a colon (':') separating them.
119                  * For example, if MONO_TRACE_LISTENER is "Console.Out:** my prefix", the prefix is
120                  * "** my prefix".
121                  *
122                  * Everything after the colon, if the colon is present, is used as the
123                  * prefix.
124                  *
125                  * @param       var             The current MONO_TRACE_LISTENER variable
126                  * @param       target  The name of the output location, e.g. "Console.Out"
127                  */
128                 private static string GetPrefix (string var, string target)
129                 {
130                         // actually, we permit any character to separate `target' and the prefix;
131                         // we just skip over target the ':' would be.  This means that a space or
132                         // anything else would suffice, as long as it was only a single
133                         // character.
134                         if (var.Length > target.Length)
135                                 return var.Substring (target.Length + 1);
136                         return "";
137                 }
138
139                 private string logFileName = null;
140
141                 private bool assertUiEnabled = false;
142
143                 public DefaultTraceListener () : base ("Default")
144                 {
145                 }
146
147                 [MonoTODO ("AssertUiEnabled defaults to False; should follow Environment.UserInteractive.")]
148                 public bool AssertUiEnabled {
149                         get { return assertUiEnabled; }
150                         set { assertUiEnabled = value; }
151                 }
152
153                 [MonoTODO]
154                 public string LogFileName {
155                         get {return logFileName;}
156                         set {logFileName = value;}
157                 }
158
159                 public override void Fail (string message)
160                 {
161                         base.Fail (message);
162                 }
163
164                 public override void Fail (string message, string detailMessage)
165                 {
166                         base.Fail (message, detailMessage);
167                         if (ProcessUI (message, detailMessage) == DialogResult.Abort)
168                                 Thread.CurrentThread.Abort ();
169                         WriteLine (new StackTrace().ToString());
170                 }
171
172                 DialogResult ProcessUI (string message, string detailMessage)
173                 {
174                         
175                         if (!AssertUiEnabled)
176                                 return DialogResult.None;
177
178                         object messageBoxButtonsAbortRetryIgnore;
179                         MethodInfo msgboxShow;
180                         
181                         try {
182                                 Assembly wfAsm = Assembly.Load (Consts.AssemblySystem_Windows_Forms);
183                                 if (wfAsm == null)
184                                     return DialogResult.None;
185                                 
186                                 Type buttons = wfAsm.GetType ("System.Windows.Forms.MessageBoxButtons");
187                                 messageBoxButtonsAbortRetryIgnore = Enum.Parse (buttons, "AbortRetryIgnore");
188                                 msgboxShow = wfAsm.GetType ("System.Windows.Forms.MessageBox").GetMethod (
189                                         "Show",
190                                         new Type [] {typeof (string), typeof (string), buttons});
191                         } catch {
192                                 return DialogResult.None;
193                         }
194
195                         if (msgboxShow == null || messageBoxButtonsAbortRetryIgnore == null)
196                                 return DialogResult.None;
197
198                         string caption = String.Format ("Assertion Failed: {0} to quit, {1} to debug, {2} to continue", "Abort", "Retry", "Ignore");
199                         string msg = String.Format ("{0}{1}{2}{1}{1}{3}", message, Environment.NewLine, detailMessage, new StackTrace ());
200
201                         switch (msgboxShow.Invoke (null, new object [] {msg, caption, messageBoxButtonsAbortRetryIgnore}).ToString ()) {
202                         case "Ignore":
203                                 return DialogResult.Ignore;
204                         case "Abort":
205                                 return DialogResult.Abort;
206                         default:
207                                 return DialogResult.Retry;
208                         }
209                 }
210
211                 enum DialogResult {
212                         None,
213                         Retry,
214                         Ignore,
215                         Abort
216                 }
217
218 #if TARGET_JVM
219                 private void WriteDebugString (string message)
220                 {
221 #else
222                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
223                 private extern static void WriteWindowsDebugString (string message);
224
225                 private void WriteDebugString (string message)
226                 {
227                         if (OnWin32)
228                                 WriteWindowsDebugString (message);
229                         else
230 #endif
231                                 WriteMonoTrace (message);
232                 }
233
234                 private void WriteMonoTrace (string message)
235                 {
236                         switch (MonoTraceFile) {
237                         case ConsoleOutTrace:
238                                 Console.Out.Write (message);
239                                 break;
240                         case ConsoleErrorTrace:
241                                 Console.Error.Write (message);
242                                 break;
243                         default:
244                                 WriteLogFile (message, MonoTraceFile);
245                                 break;
246                         }
247                 }
248
249                 private void WritePrefix ()
250                 {
251                         if (!OnWin32) {
252                                 WriteMonoTrace (MonoTracePrefix);
253                         }
254                 }
255
256                 private void WriteImpl (string message)
257                 {
258                         if (NeedIndent) {
259                                 WriteIndent ();
260                                 WritePrefix ();
261                         }
262
263                         WriteDebugString (message);
264
265                         if (Debugger.IsLogging())
266                                 Debugger.Log (0, null, message);
267
268                         WriteLogFile (message, LogFileName);
269                 }
270
271                 private void WriteLogFile (string message, string logFile)
272                 {
273                         string fname = logFile;
274                         if (fname != null && fname.Length != 0) {
275                                 FileInfo info = new FileInfo (fname);
276                                 StreamWriter sw = null;
277
278                                 // Open the file
279                                 try {
280                                         if (info.Exists)
281                                                 sw = info.AppendText ();
282                                         else
283                                                 sw = info.CreateText ();
284                                 }
285                                 catch {
286                                         // We weren't able to open the file for some reason.
287                                         // We can't write to the log file; so give up.
288                                         return;
289                                 }
290
291                                 using (sw) {
292                                         sw.Write (message);
293                                         sw.Flush ();
294                                 }
295                         }
296                 }
297
298                 public override void Write (string message)
299                 {
300                         WriteImpl (message);
301                 }
302
303                 public override void WriteLine (string message)
304                 {
305                         string msg = message + Environment.NewLine;
306                         WriteImpl (msg);
307
308                         NeedIndent = true;
309                 }
310         }
311 }
312