monodoc.dll is a private assembly, and will never be stabalized, so it belongs
[mono.git] / mcs / tools / monodoc / Monodoc / ecma-provider.cs
1 //
2 // The provider for a tree of ECMA documents
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Joshua Tauberer (tauberer@for.net)
7 //
8 // (C) 2002, 2003 Ximian, Inc.
9 // (C) 2003 Joshua Tauberer.
10 //
11 // TODO:
12 //   Should cluster together constructors
13 //
14 // Easy:
15 //   Should render attributes on the signature.
16 //   Include examples as well.
17 //
18 namespace Monodoc {
19 using System;
20 using System.Reflection;
21 using System.IO;
22 using System.Xml;
23 using System.Xml.XPath;
24 using System.Xml.Xsl;
25 using System.Text;
26 using System.Collections;
27 using ICSharpCode.SharpZipLib.Zip;
28 using Monodoc.Lucene.Net.Index;
29 using Monodoc.Lucene.Net.Documents;
30
31 using Mono.Documentation;
32
33 using BF = System.Reflection.BindingFlags;
34
35 //
36 // Helper routines to extract information from an Ecma XML document
37 //
38 public static class EcmaDoc {
39         public static string GetFullClassName (XmlDocument doc)
40         {
41                 return doc.SelectSingleNode ("/Type").Attributes ["FullName"].InnerText;
42         }
43         
44         public static string GetClassName (XmlDocument doc)
45         {
46                 return GetDisplayName (doc.SelectSingleNode ("/Type")).Replace ("+", ".");
47         }
48
49         public static string GetDisplayName (XmlNode type)
50         {
51                 if (type.Attributes ["DisplayName"] != null) {
52                         return type.Attributes ["DisplayName"].Value;
53                 }
54                 return type.Attributes ["Name"].Value;
55         }
56
57         public static string GetClassAssembly (XmlDocument doc)
58         {
59                 return doc.SelectSingleNode ("/Type/AssemblyInfo/AssemblyName").InnerText;
60         }
61
62         public static string GetClassNamespace (XmlDocument doc)
63         {
64                 string s = doc.SelectSingleNode ("/Type").Attributes ["FullName"].InnerText;
65
66                 return s.Substring (0, s.LastIndexOf ("."));
67         }
68         
69         public static string GetTypeKind (XmlDocument doc)
70         {
71                 XmlNode node = doc.SelectSingleNode ("/Type/Base/BaseTypeName");
72
73                 if (node == null){
74                         if (GetFullClassName (doc) == "System.Object")
75                                 return "Class";
76                         return "Interface";
77                 }
78
79                 switch (node.InnerText){
80
81                 case "System.Delegate":
82                 case "System.MulticastDelegate":
83                         return "Delegate";
84                 case "System.ValueType":
85                         return "Structure";
86                 case "System.Enum":
87                         return "Enumeration";
88                 default:
89                         return "Class";
90                 }
91         }
92
93         //
94         // Utility function: converts a fully .NET qualified type name into a C#-looking one
95         //
96         public static string ConvertCTSName (string type)
97         {
98                 if (!type.StartsWith ("System."))
99                         return type;
100
101                 if (type.EndsWith ("*"))
102                         return ConvertCTSName(type.Substring(0, type.Length - 1)) + "*";
103                 if (type.EndsWith ("&"))
104                         return ConvertCTSName(type.Substring(0, type.Length - 1)) + "&";
105                 if (type.EndsWith ("[]"))
106                         return ConvertCTSName(type.Substring(0, type.Length - 2)) + "[]";
107
108                 switch (type) {
109                 case "System.Byte": return "byte";
110                 case "System.SByte": return "sbyte";
111                 case "System.Int16": return "short";
112                 case "System.Int32": return "int";
113                 case "System.Int64": return "long";
114                         
115                 case "System.UInt16": return "ushort";
116                 case "System.UInt32": return "uint";
117                 case "System.UInt64": return "ulong";
118                         
119                 case "System.Single":  return "float";
120                 case "System.Double":  return "double";
121                 case "System.Decimal": return "decimal";
122                 case "System.Boolean": return "bool";
123                 case "System.Char":    return "char";
124                 case "System.String":  return "string";
125                         
126                 case "System.Object":  return "object";
127                 case "System.Void":  return "void";
128                 }
129
130                 if (type.LastIndexOf(".") == 6)
131                         return type.Substring(7);
132                 
133                 return type;
134         }
135
136         internal static string GetNamespaceFile (string dir, string ns)
137         {
138                 string nsxml = Path.Combine (dir, "ns-" + ns + ".xml");
139                 if (!File.Exists (nsxml))
140                         nsxml = Path.Combine (dir, ns + ".xml");
141                 return nsxml;
142         }
143 }
144
145 //
146 // The Ecma documentation provider:
147 //
148 // It populates a tree with contents during the help assembly
149 //
150 public class EcmaProvider : Provider {
151         ArrayList/*<string>*/ asm_dirs = new ArrayList ();
152
153         public EcmaProvider ()
154         {
155         }
156
157         public EcmaProvider (string base_directory)
158         {
159                 AddDirectory (base_directory);
160         }
161
162         public void AddDirectory (string directory)
163         {
164                 if (!Directory.Exists (directory))
165                         throw new FileNotFoundException (String.Format ("The directory `{0}' does not exist", directory));
166                 asm_dirs.Add (directory);
167         }
168         
169         public override void PopulateTree (Tree tree)
170         {
171                 ArrayList ns_dirs = new ArrayList ();
172                 foreach (string asm in asm_dirs) {
173                         ns_dirs.AddRange (Directory.GetDirectories (asm));
174                 }
175
176                 foreach (string ns in ns_dirs){
177                         string basedir = Directory.GetParent (ns).FullName;
178                         string [] files = Directory.GetFiles (ns);
179                         Node ns_node = null;
180                         string tn = null;
181                         
182                         Hashtable nsnodes = new Hashtable();
183
184                         foreach (string file in files){
185                                 if (!file.EndsWith (".xml"))
186                                         continue;
187
188                                 if (ns_node == null) {
189                                         tn = Path.GetFileName (ns);
190                                         Console.Error.WriteLine ("Processing namespace {0}", tn);
191                                         ns_node = tree.LookupNode (tn, "N:" + tn);
192                                         string ns_summary_file = EcmaDoc.GetNamespaceFile (basedir, tn);
193                                         
194                                         nsnodes[ns_node] = nsnodes;
195                                         
196                                         if (File.Exists (ns_summary_file)) {
197                                                 XmlDocument nsSummaryFile = new XmlDocument ();
198                                                 nsSummaryFile.Load (ns_summary_file);
199                                                 namespace_realpath [tn] = ns_summary_file;
200                                                 
201                                                 XmlNode ns_summary = nsSummaryFile.SelectSingleNode ("Namespace/Docs/summary");
202                                                 if (ns_summary != null && ns_summary.InnerText.Trim () != "To be added." && ns_summary.InnerText != "") {
203                                                         namespace_summaries [tn] = ns_summary;
204                                                         namespace_remarks [tn] = nsSummaryFile.SelectSingleNode ("Namespace/Docs/remarks");
205                                                 }
206                                                 
207                                         } else if (!namespace_summaries.ContainsKey (tn)) {
208                                                 namespace_summaries [tn] = null;
209                                                 namespace_remarks [tn] = null;
210                                         }
211                                 }
212                                 Console.Error.WriteLine ("    Processing input file {0}", Path.GetFileName (file));
213
214                                 PopulateClass (tn, ns_node, file);
215                         }
216                         
217                         // Sort the list of types in each namespace
218                         foreach (Node ns_node2 in nsnodes.Keys)
219                                 ns_node2.Sort();
220                 }
221
222         }
223                 
224         struct TypeInfo : IComparable {
225                 public string type_assembly;
226                 public string type_name;
227                 public string type_full;
228                 public string type_kind;
229                 public XmlNode type_doc;
230
231                 public TypeInfo (string k, string a, string f, string s, XmlNode n)
232                 {
233                         type_assembly = a;
234                         type_name = s;
235                         type_doc = n;
236                         type_kind = k;
237                         type_full = f;
238                 }
239
240                 public int CompareTo (object b)
241                 {
242                         TypeInfo na = this;
243                         TypeInfo nb = (TypeInfo) b;
244
245                         return String.Compare (na.type_full, nb.type_full);
246                 }
247         }
248         
249         //
250         // Packs a file with the summary data
251         //
252         public override void CloseTree (HelpSource hs, Tree tree)
253         {
254                 foreach (DictionaryEntry de in class_summaries){
255                         XmlDocument doc = new XmlDocument ();
256                         string ns = (string) de.Key;
257                         
258                         ArrayList list = (ArrayList) de.Value;
259                         list.Sort();
260
261                         XmlElement elements = doc.CreateElement ("elements");
262                         doc.AppendChild (elements);
263                         
264                         if (namespace_summaries [ns] != null)
265                                 elements.AppendChild (doc.ImportNode ((XmlNode)namespace_summaries [ns],true));
266                         else
267                                 elements.AppendChild (doc.CreateElement("summary"));
268                         
269                         if (namespace_remarks [ns] != null)
270                                 elements.AppendChild (doc.ImportNode ((XmlNode)namespace_remarks [ns],true));
271                         else
272                                 elements.AppendChild (doc.CreateElement("remarks"));
273                         
274                         Console.Error.WriteLine ("Have {0} elements in the {1}", list.Count, ns);
275                         foreach (TypeInfo p in list){
276                                 XmlElement e = null;
277                                 
278                                 switch (p.type_kind){
279                                 case "Class":
280                                         e = doc.CreateElement ("class"); 
281                                         break;
282                                         
283                                 case "Enumeration":
284                                         e = doc.CreateElement ("enum");
285                                         break;
286                                         
287                                 case "Structure":
288                                         e = doc.CreateElement ("struct");
289                                         break;
290                                         
291                                 case "Delegate":
292                                         e = doc.CreateElement ("delegate");
293                                         break;
294                                         
295                                 case "Interface":
296                                         e = doc.CreateElement ("interface");
297                                         break;
298                                 }
299                                 
300                                 e.SetAttribute ("name", p.type_name);
301                                 e.SetAttribute ("fullname", p.type_full);
302                                 e.SetAttribute ("assembly", p.type_assembly);
303                                 XmlNode copy = doc.ImportNode (p.type_doc, true);
304                                 e.AppendChild (copy);
305                                 elements.AppendChild (e);
306                         }
307                         hs.PackXml ("xml.summary." + ns, doc,(string) namespace_realpath[ns]);
308                 }
309                 
310                 
311                 XmlDocument nsSummary = new XmlDocument ();
312                 XmlElement root = nsSummary.CreateElement ("elements");
313                 nsSummary.AppendChild (root);
314                 
315                 foreach (DictionaryEntry de in namespace_summaries) {
316                         XmlNode n = (XmlNode)de.Value;
317                         XmlElement summary = nsSummary.CreateElement ("namespace");
318                         summary.SetAttribute ("ns", (string)de.Key);
319                         root.AppendChild (summary);
320                         if (n != null)
321                                 summary.AppendChild (nsSummary.ImportNode (n,true));
322                         else
323                                 summary.AppendChild (nsSummary.CreateElement("summary"));
324                 }
325                 tree.HelpSource.PackXml ("mastersummary.xml", nsSummary, null);
326                 AddExtensionMethods (tree);
327         }
328
329         void AddExtensionMethods (Tree tree)
330         {
331                 XmlDocument extensions = null;
332                 XmlNode root = null;
333                 int numMethods = 0;
334                 foreach (string asm in asm_dirs) {
335                         string overview_file = Path.Combine (asm, "index.xml");
336                         if (File.Exists (overview_file)) {
337                                 XmlDocument overview = new XmlDocument ();
338                                 overview.Load (overview_file);
339                                 XmlNodeList e = overview.SelectNodes ("/Overview/ExtensionMethods/*");
340                                 if (e.Count > 0) {
341                                         if (extensions == null) {
342                                                 extensions = new XmlDocument ();
343                                                 root = extensions.CreateElement ("ExtensionMethods");
344                                                 extensions.AppendChild (root);
345                                         }
346                                         foreach (XmlNode n in e) {
347                                                 ++numMethods;
348                                                 root.AppendChild (extensions.ImportNode (n, true));
349                                         }
350                                 }
351                         }
352                 }
353                 if (extensions != null) {
354                         Console.Error.WriteLine ("Have {0} extension methods", numMethods);
355                         tree.HelpSource.PackXml ("ExtensionMethods.xml", extensions, "ExtensionMethods.xml");
356                 }
357         }
358                
359         Hashtable class_summaries = new Hashtable ();
360         Hashtable namespace_summaries = new Hashtable ();
361         Hashtable namespace_remarks = new Hashtable ();
362         Hashtable namespace_realpath = new Hashtable ();
363         XmlDocument doc;
364         
365         void PopulateClass (string ns, Node ns_node, string file)
366         {
367                 doc = new XmlDocument ();
368                 doc.Load (file);
369                 
370                 string name = EcmaDoc.GetClassName (doc);
371                 string assembly = EcmaDoc.GetClassAssembly (doc);
372                 string kind = EcmaDoc.GetTypeKind (doc);
373                 string full = EcmaDoc.GetFullClassName (doc);
374
375                 Node class_node;
376                 string file_code = ns_node.tree.HelpSource.PackFile (file);
377
378                 XmlNode class_summary = doc.SelectSingleNode ("/Type/Docs/summary");
379                 ArrayList l = (ArrayList) class_summaries [ns];
380                 if (l == null){
381                         l = new ArrayList ();
382                         class_summaries [ns] = (object) l;
383                 }
384                 l.Add (new TypeInfo (kind, assembly, full, name, class_summary));
385                
386                 class_node = ns_node.LookupNode (String.Format ("{0} {1}", name, kind), "ecma:" + file_code + "#" + name + "/");
387                 
388                 if (kind == "Delegate") {
389                         if (doc.SelectSingleNode("/Type/ReturnValue") == null)
390                                 Console.Error.WriteLine("Delegate " + name + " does not have a ReturnValue node.  See the ECMA-style updates.");
391                 }
392
393                 if (kind == "Enumeration")
394                         return;
395
396                 if (kind == "Delegate")
397                         return;
398                 
399                 //
400                 // Always add the Members node
401                 //
402                 class_node.CreateNode ("Members", "*");
403
404                 PopulateMember (name, class_node, "Constructor", "Constructors");
405                 PopulateMember (name, class_node, "Method", "Methods");
406                 PopulateMember (name, class_node, "Property", "Properties");
407                 PopulateMember (name, class_node, "Field", "Fields");
408                 PopulateMember (name, class_node, "Event", "Events");
409                 PopulateMember (name, class_node, "Operator", "Operators");
410         }
411
412         class NodeIndex {
413                 public XmlNode node;
414                 public int     index;
415
416                 public NodeIndex (XmlNode node, int index)
417                 {
418                         this.node = node;
419                         this.index = index;
420                 }
421         }
422
423         struct NodeCompare : IComparer {
424                 public int Compare (object a, object b)
425                 {
426                         NodeIndex na = (NodeIndex) a;
427                         NodeIndex nb = (NodeIndex) b;
428
429                         return String.Compare (na.node.Attributes ["MemberName"].InnerText,
430                                                nb.node.Attributes ["MemberName"].InnerText);
431                 }
432         }
433
434         string GetMemberName (XmlNode node)
435         {
436                 return node.Attributes ["MemberName"].InnerText;
437         }
438         
439         //
440         // Performs an XPath query on the document to extract the nodes for the various members
441         // we also use some extra text to pluralize the caption
442         //
443         void PopulateMember (string typename, Node node, string type, string caption)
444         {
445                 string select = type;
446                 if (select == "Operator") select = "Method";
447                 
448                 XmlNodeList list1 = doc.SelectNodes (String.Format ("/Type/Members/Member[MemberType=\"{0}\"]", select));
449                 ArrayList list = new ArrayList();
450                 int i = 0;
451                 foreach (XmlElement n in list1) {
452                         n.SetAttribute("assembler_index", (i++).ToString());
453                         if (type == "Method" && GetMemberName(n).StartsWith("op_")) continue;
454                         if (type == "Operator" && !GetMemberName(n).StartsWith("op_")) continue;
455                         list.Add(n);
456                 }
457                 
458                 int count = list.Count;
459                 
460                 if (count == 0)
461                         return;
462
463                 Node nodes_node;
464                 string key = type.Substring (0, 1);
465                 nodes_node = node.CreateNode (caption, key);
466                 
467                 switch (type) {
468                         case "Event":
469                         case "Field":
470                                 foreach (XmlElement n in list)
471                                         nodes_node.CreateNode (GetMemberName (n), n.GetAttribute("assembler_index"));
472                                 break;
473
474                         case "Constructor":
475                                 foreach (XmlElement n in list)
476                                         nodes_node.CreateNode (EcmaHelpSource.MakeSignature(n, typename), n.GetAttribute("assembler_index"));
477                                 break;
478
479                         case "Property": // properties with indexers can be overloaded too
480                         case "Method":
481                         case "Operator":
482                                 foreach (XmlElement n in list) {
483                                         bool multiple = false;
484                                         foreach (XmlNode nn in list) {
485                                                 if (n != nn && GetMemberName(n) == nn.Attributes ["MemberName"].InnerText) {
486                                                         multiple = true;
487                                                         break;
488                                                 }
489                                         }
490                                         
491                                         string group, name, sig;
492                                         if (type != "Operator") {
493                                                 name = GetMemberName(n);
494                                                 sig = EcmaHelpSource.MakeSignature(n, null);
495                                                 group = name;
496                                         } else {
497                                                 EcmaHelpSource.MakeOperatorSignature(n, out name, out sig);
498                                                 group = name;
499                                         }
500                                         
501                                         if (multiple) {
502                                                 nodes_node.LookupNode (group, group)
503                                                         .CreateNode (sig, n.GetAttribute("assembler_index"));
504                                         } else {
505                                                 nodes_node.CreateNode (name, n.GetAttribute("assembler_index"));
506                                         }
507                                 }
508                                 
509                                 foreach (Node n in nodes_node.Nodes) {
510                                         if (!n.IsLeaf)
511                                                 n.Sort ();
512                                 }
513                                 
514                                 break;
515                                 
516                         default:
517                                 throw new InvalidOperationException();
518                 }
519                 
520                 nodes_node.Sort ();
521         }
522
523 }
524
525 //
526 // The Ecma HelpSource provider
527 //
528 public class EcmaHelpSource : HelpSource {
529
530         public EcmaHelpSource (string base_file, bool create) : base (base_file, create)
531         {
532                 ExtObject = new ExtensionObject (this);
533         }
534
535         public EcmaHelpSource ()
536         {
537                 ExtObject = new ExtensionObject (this);
538         }
539
540         static string css_ecma;
541         public static string css_ecma_code {
542                 get {
543                         if (css_ecma != null)
544                                 return css_ecma;
545                         if (use_css) {
546                                 System.Reflection.Assembly assembly = typeof(EcmaHelpSource).Assembly;
547                                 Stream str_css = assembly.GetManifestResourceStream ("mono-ecma.css");
548                                 css_ecma = (new StreamReader (str_css)).ReadToEnd();
549                         } else {
550                                 css_ecma = String.Empty;
551                         }
552                         return css_ecma;
553                 }
554         }
555         static string js;
556         public static string js_code {
557                 get {
558                         if (js != null)
559                                 return js;
560                         if (use_css) {
561                                 System.Reflection.Assembly assembly = typeof(EcmaHelpSource).Assembly;
562                                 Stream str_js = assembly.GetManifestResourceStream ("mono-ecma-css.js");
563                                 js = (new StreamReader (str_js)).ReadToEnd();
564                         } else {
565                                 js = String.Empty;
566                         }
567                         return js;
568                 }
569         }
570
571         public override string GetText (string url, out Node match_node)
572         {
573                 match_node = null;
574                 
575                 if (url == "root:")
576                 {
577                         XmlReader summary = GetHelpXml ("mastersummary.xml");
578                         if (summary == null)
579                                 return null;
580
581                         XsltArgumentList args = new XsltArgumentList();
582                         args.AddExtensionObject("monodoc:///extensions", ExtObject);
583                         args.AddParam("show", "", "masteroverview");
584                         string s = Htmlize(new XPathDocument (summary), args);
585                         return BuildHtml (css_ecma_code, js_code, s); 
586                 }
587                 
588                 if (url.StartsWith ("ecma:")) {
589                         string s = GetTextFromUrl (url);
590                         return BuildHtml (css_ecma_code, js_code, s); 
591                 }
592
593                 return null;
594         }
595
596
597         string RenderMemberLookup (string typename, string member, ref Node type_node)
598         {
599                 if (type_node.Nodes == null)
600                         return null;
601
602                 string membername = member;
603                 string[] argtypes = null;
604                 if (member.IndexOf("(") > 0) {
605                         membername = membername.Substring(0, member.IndexOf("("));
606                         member = member.Replace("@", "&");
607                         
608                         // reform the member signature with CTS names
609
610                         string x = member.Substring(member.IndexOf("(")+1);
611                         argtypes = x.Substring(0, x.Length-1).Split(',', ':'); // operator signatures have colons
612
613                         if (membername == ".ctor")
614                                 membername = typename;
615
616                         member = membername + "(";
617                         for (int i = 0; i < argtypes.Length; i++) {
618                                 argtypes[i] = EcmaDoc.ConvertCTSName(argtypes[i]);
619                                 if (i > 0) member += ",";
620                                 member += argtypes[i];
621                         }
622                         member += ")";
623                 }
624                 
625                 // Check if a node caption matches exactly
626                 
627                 bool isoperator = false;
628                 
629                 if ((membername == "op_Implicit" || membername == "op_Explicit") && argtypes.Length == 2) {
630                         isoperator = true;
631                         membername = "Conversion";
632                         member = argtypes[0] + " to " + argtypes[1];
633                 } else if (membername.StartsWith("op_")) {
634                         isoperator = true;
635                         membername = membername.Substring(3);
636                 }
637
638                 foreach (Node x in type_node.Nodes){
639                         if (x.Nodes == null)
640                                 continue;
641                         if (isoperator && x.Caption != "Operators")
642                                 continue;
643                         
644                         foreach (Node m in x.Nodes) {
645                                 string caption = m.Caption;
646                                 string ecaption = ToEscapedMemberName (caption);
647                                 if (m.IsLeaf) {
648                                         // No overloading (usually), is just the member name.  The whole thing for constructors.
649                                         if (caption == membername || caption == member ||
650                                                         ecaption == membername || ecaption == member) {
651                                                 type_node = m;
652                                                 return GetTextFromUrl (m.URL);
653                                         }
654                                 } else if (caption == member || ecaption == member) {
655                                         // Though there are overloads, no arguments are in the url, so use this base node
656                                         type_node = m;
657                                         return GetTextFromUrl (m.URL);
658                                 } else {
659                                         // Check subnodes which are the overloads -- must match signature
660                                         foreach (Node mm in m.Nodes) {
661                                                 ecaption = ToEscapedTypeName (mm.Caption);
662                                                 if (mm.Caption == member || ecaption == member) {
663                                                         type_node = mm;
664                                                         return GetTextFromUrl (mm.URL);
665                                                 }
666                                         }
667                                 }
668                         }
669                 }
670                 
671                 return null;
672         }
673
674         public static string MakeSignature (XmlNode n, string cstyleclass)
675         {
676                 string sig;
677
678                 if (cstyleclass == null)
679                         sig = n.Attributes["MemberName"].InnerText;
680                 else {
681                         // constructor style
682                         sig = cstyleclass;
683                 }
684         
685                 /*if (n.SelectSingleNode("MemberType").InnerText == "Method" || n.SelectSingleNode("MemberType").InnerText == "Constructor") {*/ // properties with indexers too
686                         XmlNodeList paramnodes = n.SelectNodes("Parameters/Parameter");
687                         sig += "(";
688                         bool first = true;
689                         foreach (XmlNode p in paramnodes) {
690                                 if (!first) sig += ",";
691                                 string type = p.Attributes["Type"].InnerText;
692                                 type = EcmaDoc.ConvertCTSName(type);
693                                 sig += type;
694                                 first = false;
695                         }
696                         sig += ")";
697                 //}
698
699                 return sig;
700         }
701         
702         public static void MakeOperatorSignature (XmlNode n, out string nicename, out string sig)
703         {
704                 string name;
705
706                 name = n.Attributes["MemberName"].InnerText;
707                 nicename = name.Substring(3);
708                 
709                 switch (name) {
710                         // unary operators: no overloading possible
711                         case "op_UnaryPlus": case "op_UnaryNegation": case "op_LogicalNot": case "op_OnesComplement":
712                         case "op_Increment": case "op_Decrement": 
713                         case "op_True": case "op_False":
714                                 sig = nicename;
715                                 break;
716                         
717                         // binary operators: overloading is possible based on parameter types
718                         case "op_Addition": case "op_Subtraction": case "op_Multiply": case "op_Division": case "op_Modulus":
719                         case "op_BitwiseAnd": case "op_BitwiseOr": case "op_ExclusiveOr":
720                         case "op_LeftShift": case "op_RightShift":
721                         case "op_Equality": case "op_Inequality":
722                         case "op_GreaterThan": case "op_LessThan": case "op_GreaterThanOrEqual": case "op_LessThanOrEqual":
723                                 XmlNodeList paramnodes = n.SelectNodes("Parameters/Parameter");
724                                 sig = nicename + "(";
725                                 bool first = true;
726                                 foreach (XmlNode p in paramnodes) {
727                                         if (!first) sig += ",";
728                                         string type = p.Attributes["Type"].InnerText;
729                                         type = EcmaDoc.ConvertCTSName(type);
730                                         sig += type;
731                                         first = false;
732                                 }
733                                 sig += ")";
734                                 break;
735                         
736                         // overloading based on parameter and return type
737                         case "op_Implicit": case "op_Explicit":
738                                 nicename = "Conversion";
739                                 string arg = n.SelectSingleNode("Parameters/Parameter/@Type").InnerText;
740                                 string ret = n.SelectSingleNode("ReturnValue/ReturnType").InnerText;
741                                 sig = EcmaDoc.ConvertCTSName(arg) + " to " + EcmaDoc.ConvertCTSName(ret);
742                                 break;
743                                 
744                         default:
745                                 throw new InvalidOperationException();
746                 }       
747         }
748
749         //
750         // This routine has to perform a lookup on a type.
751         //
752         // Example: T:System.Text.StringBuilder
753         //
754         // The prefix is the kind of opereation being requested (T:, E:, M: etc)
755         // ns is the namespace being looked up
756         // type is the type being requested
757         //
758         // This has to walk our toplevel (which is always a namespace)
759         // And then the type space, and then walk further down depending on the request
760         //
761         public override string RenderTypeLookup (string prefix, string ns, string type, string member, out Node match_node)
762         {
763                 string url = GetUrlForType (prefix, ns, type, member, out match_node);
764                 if (url == null) return null;
765                 return GetTextFromUrl (url);
766         }
767
768         public virtual string GetIdFromUrl (string prefix, string ns, string type)
769         {
770                 Node tmp_node = new Node (Tree, "", "");
771                 string url = GetUrlForType (prefix, ns, type, null, out tmp_node);
772                 if (url == null) return null;
773                 return GetFile (url.Substring (5), out url);
774         }
775         
776         public string GetUrlForType (string prefix, string ns, string type, string member, out Node match_node)
777         {
778                 if (!prefix.EndsWith(":"))
779                         throw new ArgumentException("prefix");
780
781                 if (member != null)
782                         member = member.Replace ("#", ".").Replace ("{", "<").Replace ("}", ">");
783                         
784                 // If a nested type, compare only inner type name to node list.
785                 // This should be removed when the node list doesn't lose the containing type name.
786                 type = ToEscapedTypeName (type.Replace("+", "."));
787                 MatchAttempt[] attempts = GetAttempts (ns, type);
788
789                 foreach (Node ns_node in Tree.Nodes){
790                         string ns_node_namespace = ns_node.Element.Substring (2);
791
792                         if (!MatchesNamespace (attempts, ns_node_namespace, out type))
793                                 continue;
794                         
795                         foreach (Node type_node in ns_node.Nodes){
796                                 string element = type_node.Element;
797                                 
798                                 string cname;
799                                 if (element.StartsWith("T:")) {
800                                         cname = element.Substring(2);
801                                         string _ns;
802                                         RootTree.GetNamespaceAndType (cname, out _ns, out cname);
803                                         cname = ToEscapedTypeName (cname);
804                                         int pidx = cname.LastIndexOf (".");
805                                         cname = cname.Substring(pidx+1);
806                                         pidx = cname.LastIndexOf ("/");
807                                         if (pidx != -1)
808                                                 cname = cname.Substring(0, pidx);
809                                         cname = cname.Replace("+", ".");
810                                 } else {                                
811                                         int pidx = element.IndexOf ("#");
812                                         int sidx = element.IndexOf ("/");
813                                         cname = element.Substring (pidx + 1, sidx-pidx-1);
814                                         cname = ToEscapedTypeName (cname);
815                                 }
816                                 
817                                 //Console.WriteLine ("t:{0} cn:{1} p:{2}", type, cname, prefix);
818
819                                 if (type == cname && prefix == "T:") {
820                                         match_node = type_node;
821                                         return type_node.URL;
822                                 } else if (type.StartsWith (cname)){
823                                         int p = cname.Length;
824
825                                         match_node = type_node;
826                                         if (type == cname){
827                                                 string ret = RenderMemberLookup (type, member, ref match_node);
828                                                 if (ret == null)
829                                                         return type_node.URL;
830                                                 return match_node.URL;
831
832                                         } else if (type [p] == '/'){
833                                                 //
834                                                 // This handles summaries
835                                                 //
836                                                 match_node = null;
837                                                 foreach (Node nd in type_node.Nodes) {
838                                                         if (nd.Element [nd.Element.Length - 1] == type [p + 1]) {
839                                                                 match_node = nd;
840                                                                 break;
841                                                         }
842                                                 }
843                                                 
844                                                 string ret = type_node.URL;
845                                                 if (!ret.EndsWith("/")) ret += "/";
846                                                 return ret + type.Substring (p + 1);
847                                         }
848                                 }
849                         }
850                 }
851
852                 match_node = null;
853                 return null;
854         }
855
856         struct MatchAttempt {
857                 public string Namespace;
858                 public string Type;
859
860                 public MatchAttempt (string ns, string t)
861                 {
862                         Namespace = ns;
863                         Type = t;
864                 }
865         }
866
867         private static MatchAttempt[] GetAttempts (string ns, string type)
868         {
869                 MatchAttempt[] attempts = new MatchAttempt [Count (ns, '.') + 1];
870                 int wns = 0;
871                 for (int i = 0; i < ns.Length; ++i) {
872                         if (ns [i] == '.')
873                                 attempts [wns++] = new MatchAttempt (ns.Substring (0, i), 
874                                                 ns.Substring (i+1) + "." + type);
875                 }
876                 attempts [wns++] = new MatchAttempt (ns, type);
877                 return attempts;
878         }
879
880         private static int Count (string s, char c)
881         {
882                 int n = 0;
883                 for (int i = 0; i < s.Length; ++i)
884                         if (s [i] == c)
885                                 ++n;
886                 return n;
887         }
888
889         private static bool MatchesNamespace (MatchAttempt[] attempts, string ns, out string type)
890         {
891                 for (int i = 0; i < attempts.Length; ++i)
892                         if (ns == attempts [i].Namespace) {
893                                 type = attempts [i].Type;
894                                 return true;
895                         }
896                 type = null;
897                 return false;
898         }
899         
900         public static string ToEscapedTypeName (string typename)
901         {
902                 return ToEscapedName (typename, "`");
903         }
904
905         static string ToEscapedName (string name, string escape)
906         {
907                 StringBuilder filename = new StringBuilder (name.Length);
908                 int numArgs = 0;
909                 int numLt = 0;
910                 bool copy = true;
911
912                 for (int i = 0; i < name.Length; ++i) {
913                         char c = name [i];
914                         switch (c) {
915                                 case '{':
916                                 case '<':
917                                         copy = false;
918                                         ++numLt;
919                                         break;
920                                 case '}':
921                                 case '>':
922                                         --numLt;
923                                         if (numLt == 0) {
924                                                 filename.Append (escape).Append ((numArgs+1).ToString());
925                                                 numArgs = 0;
926                                                 copy = true;
927                                         }
928                                         break;
929                                 case ',':
930                                         if (numLt == 1)
931                                                 ++numArgs;
932                                         break;
933                                 default:
934                                         if (copy)
935                                                 filename.Append (c);
936                                         break;
937                         }
938                 }
939                 return filename.ToString ();
940         }
941
942         static string ToEscapedMemberName (string membername)
943         {
944                 return ToEscapedName (membername, "``");
945         }
946         
947         public override string GetNodeXPath (XPathNavigator n)
948         {
949                 if (n.Matches ("/Type/Docs/param")) {
950                         string type_name = (string) n.Evaluate ("string (ancestor::Type/@FullName)");
951                         string param_name = (string) n.Evaluate ("string (@name)");
952                         
953                         return String.Format ("/Type [@FullName = '{0}']/Docs/param[@name='{1}']", type_name, param_name);
954                 }
955
956                 if (n.Matches ("/Type/Docs/*")) {
957                         string type_name = (string) n.Evaluate ("string (ancestor::Type/@FullName)");
958                         
959                         return String.Format ("/Type [@FullName = '{0}']/Docs/{1}", type_name, n.Name);
960                 }
961                 
962                 if (n.Matches ("/Type/Members/Member/Docs/*")) {
963                         string type_name = (string) n.Evaluate ("string (ancestor::Type/@FullName)");
964                         string member_name = (string) n.Evaluate ("string (ancestor::Member/@MemberName)");
965                         string member_sig = (string) n.Evaluate ("string (ancestor::Member/MemberSignature [@Language='C#']/@Value)");
966                         string param_name = (string) n.Evaluate ("string (@name)");
967                         
968                         if (param_name == null || param_name == "") {
969                                 return String.Format (
970                                 "/Type [@FullName = '{0}']/Members/Member [@MemberName = '{1}'][MemberSignature [@Language='C#']/@Value = '{2}']/Docs/{3}",
971                                 type_name, member_name, member_sig, n.Name);
972                         } else {
973                                 return String.Format (
974                                 "/Type [@FullName = '{0}']/Members/Member [@MemberName = '{1}'][MemberSignature [@Language='C#']/@Value = '{2}']/Docs/param [@name = '{3}']",
975                                 type_name, member_name, member_sig, param_name);
976                         }
977                 }
978                 
979                 Console.WriteLine ("WARNING: Was not able to get clean XPath expression for node {0}", EditingUtils.GetXPath (n));
980                 return base.GetNodeXPath (n);
981         }
982
983         protected virtual XmlReader GetNamespaceDocument (string ns) {
984                 return GetHelpXml ("xml.summary." + ns);
985         }
986
987         public override string RenderNamespaceLookup (string nsurl, out Node match_node)
988         {
989                 foreach (Node ns_node in Tree.Nodes){
990                         if (ns_node.Element != nsurl)
991                                 continue;
992
993                         match_node = ns_node;
994                         string ns_name = nsurl.Substring (2);
995                         
996                         XmlDocument doc = GetHelpXmlWithChanges("xml.summary." + ns_name);
997                         if (doc == null)
998                                 return null;
999
1000                         XsltArgumentList args = new XsltArgumentList();
1001                         args.AddExtensionObject("monodoc:///extensions", ExtObject);
1002                         args.AddParam("show", "", "namespace");
1003                         args.AddParam("namespace", "", ns_name);
1004                         string s = Htmlize(doc, args);
1005                         return BuildHtml (css_ecma_code, js_code, s); 
1006
1007                 }
1008                 match_node = null;
1009                 return null;
1010         }
1011
1012         private string SelectString(XmlNode node, string xpath) {
1013                 XmlNode ret = node.SelectSingleNode(xpath);
1014                 if (ret == null) return "";
1015                 return ret.InnerText;
1016         }
1017         private int SelectCount(XmlNode node, string xpath) {
1018                 return node.SelectNodes(xpath).Count;
1019         }
1020
1021         //
1022         // Returns the XmlDocument from the given url, and fills in `rest'
1023         //
1024         protected virtual XmlDocument GetXmlFromUrl(string url, out string rest) {
1025                 // Remove ecma:
1026                 url = url.Substring (5);
1027                 string file = GetFile (url, out rest);
1028
1029                 // Console.WriteLine ("Got [{0}] and [{1}]", file, rest);
1030                 return GetHelpXmlWithChanges (file);
1031         }
1032         
1033         string GetTextFromUrl (string url)
1034         {
1035                 string rest, rest2;
1036                 Node node;
1037
1038                 XmlDocument doc = GetXmlFromUrl (url, out rest);
1039                 
1040                 // Load base-type information so the stylesheet can draw the inheritance
1041                 // tree and (optionally) include inherited members in the members list.
1042                 XmlElement basenode = (XmlElement)doc.SelectSingleNode("Type/Base");
1043                 XmlElement membersnode = (XmlElement)doc.SelectSingleNode("Type/Members");
1044                 XmlNode basetype = doc.SelectSingleNode("Type/Base/BaseTypeName");
1045                 int baseindex = 0;
1046                 while (basetype != null) {
1047                         // Add the ParentType node to Type/Base
1048                         XmlElement inheritancenode = doc.CreateElement("ParentType");
1049                         inheritancenode.SetAttribute("Type", basetype.InnerText);
1050                         inheritancenode.SetAttribute("Order", (baseindex++).ToString());
1051                         basenode.AppendChild(inheritancenode);
1052                         
1053                         // Load the base type XML data
1054                         int dot = basetype.InnerText.LastIndexOf('.');
1055                         string ns = basetype.InnerText.Substring(0, dot == -1 ? 0 : dot);
1056                         string n = basetype.InnerText.Substring(dot == -1 ? 0 : dot+1);
1057                         string basetypeurl = GetUrlForType("T:", ns, n, null, out node);
1058                         XmlDocument basetypedoc = null;
1059                         if (basetypeurl != null)
1060                                 basetypedoc = GetXmlFromUrl (basetypeurl, out rest2);
1061                         if (basetypedoc == null) {
1062                                 inheritancenode.SetAttribute("Incomplete", "1");
1063                                 break;
1064                         }
1065                         
1066                         if (SettingsHandler.Settings.ShowInheritedMembers) {
1067                                 // Add inherited members
1068                                 foreach (XmlElement member in basetypedoc.SelectNodes("Type/Members/Member[not(MemberType='Constructor')]")) {
1069                                         string sig = SelectString(member, "MemberSignature[@Language='C#']/@Value");
1070                                         if (sig.IndexOf(" static ") >= 0) continue;
1071                                         
1072                                         // If the signature of member matches the signature of a member already in the XML,
1073                                         // don't add it.
1074                                         string xpath = "@MemberName='" + SelectString(member, "@MemberName") + "'";
1075                                         xpath       += " and ReturnValue/ReturnType='" + SelectString(member, "ReturnValue/ReturnType") + "'";
1076                                         xpath       += " and count(Parameters/Parameter)=" + SelectCount(member, "Parameters/Parameter") + "";
1077                                         int pi = 1;
1078                                         foreach (XmlElement p in member.SelectNodes("Parameters/Parameter")) {
1079                                                 xpath   += " and Parameters/Parameter[position()=" + pi + "]/@Type = '" + p.GetAttribute("Type") + "'";
1080                                                 pi++;
1081                                         }
1082                                         
1083                                         // If a signature match is found, don't add.
1084                                         XmlNode match = membersnode.SelectSingleNode("Member[" + xpath + "]");
1085                                         if (match != null)
1086                                                 continue;
1087                                         
1088                                         member.SetAttribute("DeclaredIn", basetype.InnerText);
1089                                         membersnode.AppendChild(membersnode.OwnerDocument.ImportNode(member, true));                            
1090                                 }
1091                         }
1092                         
1093                         basetype = basetypedoc.SelectSingleNode("Type/Base/BaseTypeName");
1094                 }
1095                 ArrayList extensions = new ArrayList ();
1096                 foreach (HelpSource hs in RootTree.HelpSources) {
1097                         EcmaHelpSource es = hs as EcmaHelpSource;
1098                         if (es == null)
1099                                 continue;
1100                         Stream s = es.GetHelpStream ("ExtensionMethods.xml");
1101                         if (s != null) {
1102                                 XmlDocument d = new XmlDocument ();
1103                                 d.Load (s);
1104                                 foreach (XmlNode n in d.SelectNodes ("/ExtensionMethods/*")) {
1105                                         extensions.Add (n);
1106                                 }
1107                         }
1108                 }
1109                 XmlDocUtils.AddExtensionMethods (doc, extensions, delegate (string s) {
1110                                 return RootTree.GetHelpXml ("T:" + s);
1111                 });
1112
1113                 XsltArgumentList args = new XsltArgumentList();
1114
1115                 args.AddExtensionObject("monodoc:///extensions", ExtObject);
1116                 
1117                 if (rest == "") {
1118                         args.AddParam("show", "", "typeoverview");
1119                         string s = Htmlize(doc, args);
1120                         return BuildHtml (css_ecma_code, js_code, s); 
1121                 }
1122                 
1123                 string [] nodes = rest.Split (new char [] {'/'});
1124                 
1125                 switch (nodes.Length) {
1126                         case 1:
1127                                 args.AddParam("show", "", "members");
1128                                 args.AddParam("index", "", "all");
1129                                 break;
1130                         case 2:
1131                                 // Could either be a single member, or an overload thingy
1132                                 try {
1133                                         int.Parse (nodes [1]); // is it an int
1134                                         
1135                                         args.AddParam("show", "", "member");
1136                                         args.AddParam("index", "", nodes [1]);
1137                                 } catch {
1138                                         args.AddParam("show", "", "overloads");
1139                                         args.AddParam("index", "", nodes [1]);
1140                                 }
1141                                 break;
1142                         case 3:
1143                                 args.AddParam("show", "", "member");
1144                                 args.AddParam("index", "", nodes [2]);
1145                                 break;
1146                         default:
1147                                 return "What the hell is this URL " + url;
1148                 }
1149
1150                 switch (nodes [0]){
1151                 case "C":
1152                         args.AddParam("membertype", "", "Constructor");
1153                         break;
1154                 case "M":
1155                         args.AddParam("membertype", "", "Method");
1156                         break;
1157                 case "P":
1158                         args.AddParam("membertype", "", "Property");
1159                         break;
1160                 case "F":
1161                         args.AddParam("membertype", "", "Field");
1162                         break;
1163                 case "E":
1164                         args.AddParam("membertype", "", "Event");
1165                         break;
1166                 case "O":
1167                         args.AddParam("membertype", "", "Operator");
1168                         break;
1169                 case "X":
1170                         args.AddParam("membertype", "", "ExtensionMethod");
1171                         break;
1172                 case "*":
1173                         args.AddParam("membertype", "", "All");
1174                         break;
1175                 default:
1176                         return "Unknown url: " + url;
1177                 }
1178
1179                 string html = Htmlize(doc, args);
1180                 return BuildHtml (css_ecma_code, js_code, html); 
1181         }
1182
1183         
1184         public override void RenderPreviewDocs (XmlNode newNode, XmlWriter writer)
1185         {
1186                 XsltArgumentList args = new XsltArgumentList ();
1187                 args.AddExtensionObject ("monodoc:///extensions", ExtObject);
1188                 
1189                 Htmlize (newNode, args, writer);
1190         }
1191
1192         static XslTransform ecma_transform;
1193
1194         public static string Htmlize (IXPathNavigable ecma_xml)
1195         {
1196                 return Htmlize(ecma_xml, null);
1197         }
1198         
1199         public static string Htmlize (IXPathNavigable ecma_xml, XsltArgumentList args)
1200         {
1201                 EnsureTransform ();
1202                 
1203                 StringWriter output = new StringWriter ();
1204                 ecma_transform.Transform (ecma_xml, args, output, null);
1205                 return output.ToString ();
1206         }
1207         
1208         static void Htmlize (IXPathNavigable ecma_xml, XsltArgumentList args, XmlWriter w)
1209         {
1210                 EnsureTransform ();
1211                 
1212                 if (ecma_xml == null)
1213                         return;
1214
1215                 ecma_transform.Transform (ecma_xml, args, w, null);
1216         }
1217         
1218         static XslTransform ecma_transform_css, ecma_transform_no_css;
1219         static void EnsureTransform ()
1220         {
1221                 if (ecma_transform == null) {
1222                         ecma_transform_css = new XslTransform ();
1223                         ecma_transform_no_css = new XslTransform ();
1224                         Assembly assembly = System.Reflection.Assembly.GetCallingAssembly ();
1225                         
1226                         Stream stream = assembly.GetManifestResourceStream ("mono-ecma-css.xsl");
1227                         XmlReader xml_reader = new XmlTextReader (stream);
1228                         XmlResolver r = new ManifestResourceResolver (".");
1229                         ecma_transform_css.Load (xml_reader, r, null);
1230                         
1231                         stream = assembly.GetManifestResourceStream ("mono-ecma.xsl");
1232                         xml_reader = new XmlTextReader (stream);
1233                         ecma_transform_no_css.Load (xml_reader, r, null);
1234                 }
1235                 if (use_css)
1236                         ecma_transform = ecma_transform_css;
1237                 else
1238                         ecma_transform = ecma_transform_no_css;
1239         }
1240
1241         // This ExtensionObject stuff is used to check at run time whether
1242         // types and members have been implemented and whether there are any
1243         // MonoTODO attributes left on them. 
1244
1245         public readonly ExtensionObject ExtObject;
1246         public class ExtensionObject {
1247                 readonly EcmaHelpSource hs;
1248
1249                 //
1250                 // We are setting this to quiet now, as we need to transition
1251                 // monodoc to run with the 2.x runtime and provide accurate
1252                 // information in those cases.
1253                 //
1254                 bool quiet = true;
1255                 
1256                 public ExtensionObject (EcmaHelpSource hs)
1257                 {
1258                         this.hs = hs;
1259                 }
1260                 
1261                 public string Colorize(string code, string lang) {
1262                         return(Mono.Utilities.Colorizer.Colorize(code,lang));
1263                 }
1264                 // Used by stylesheet to nicely reformat the <see cref=> tags. 
1265                 public string MakeNiceSignature(string sig, string contexttype)
1266                 {
1267                         if (sig.Length < 3)
1268                                 return sig;
1269                         if (sig[1] != ':')
1270                                 return sig;
1271
1272                         char s = sig[0];
1273                         sig = sig.Substring(2);
1274                         
1275                         switch (s) {
1276                                 case 'N': return sig;
1277                                 case 'T': return ShortTypeName(sig, contexttype);
1278
1279                                 case 'C': case 'M': case 'P': case 'F': case 'E':
1280                                         string type, mem, arg;
1281                                         
1282                                         // Get arguments
1283                                         int paren;
1284                                         if (s == 'C' || s == 'M')
1285                                                 paren = sig.IndexOf("(");
1286                                         else if (s == 'P')
1287                                                 paren = sig.IndexOf("[");
1288                                         else
1289                                                 paren = 0;
1290                                         
1291                                         if (paren > 0 && paren < sig.Length-1) {
1292                                                 string[] args = sig.Substring(paren+1, sig.Length-paren-2).Split(',');                                          
1293                                                 for (int i = 0; i < args.Length; i++)
1294                                                         args[i] = ShortTypeName(args[i], contexttype);
1295                                                 arg = "(" + String.Join(", ", args) + ")";
1296                                                 sig = sig.Substring(0, paren); 
1297                                         } else {
1298                                                 arg = "";
1299                                         }
1300
1301                                         // Get type and member names
1302                                         int dot = sig.LastIndexOf(".");
1303                                         if (s == 'C' || dot <= 0 || dot == sig.Length-1) {
1304                                                 mem = "";
1305                                                 type = sig;
1306                                         } else {
1307                                                 type = sig.Substring(0, dot);
1308                                                 mem = sig.Substring(dot);
1309                                         }
1310                                                 
1311                                         type = ShortTypeName(type, contexttype);
1312                                         
1313                                         return type + mem + arg;
1314
1315                                 default:
1316                                         return sig;
1317                         }
1318                 }
1319                 
1320                 public string EditUrl (XPathNodeIterator itr)
1321                 {
1322                         if (itr.MoveNext ())
1323                                 return hs.GetEditUri (itr.Current);
1324                         
1325                         return "";
1326                 }
1327
1328                 public string EditUrlNamespace (XPathNodeIterator itr, string ns, string section)
1329                 {
1330                         if (hs is EcmaUncompiledHelpSource)
1331                                 return "edit:file:" + Path.Combine(((EcmaUncompiledHelpSource)hs).BasePath, ns + ".xml") + "@/Namespace/Docs/" + section; 
1332                         else if (itr.MoveNext ())
1333                                 return EditingUtils.FormatEditUri(itr.Current.BaseURI, "/elements/" + section);
1334                         return "";
1335                 }
1336
1337                 private static string ShortTypeName(string name, string contexttype)
1338                 {
1339                         int dot = contexttype.LastIndexOf(".");
1340                         if (dot < 0) return name;
1341                         string contextns = contexttype.Substring(0, dot+1);
1342
1343                         if (name == contexttype)
1344                                 return name.Substring(dot+1);
1345                         
1346                         if (name.StartsWith(contextns))
1347                                 return name.Substring(contextns.Length);
1348                         
1349                         return name.Replace("+", ".");
1350                 }
1351
1352                 public string MonoImpInfo(string assemblyname, string typename, string membername, string arglist, bool strlong)
1353                 {
1354                         if (quiet)
1355                                 return "";
1356                                 
1357                         ArrayList a = new ArrayList();
1358                         if (arglist != "") a.Add(arglist);
1359                         return MonoImpInfo(assemblyname, typename, membername, a, strlong);
1360                 }
1361
1362                 public string MonoImpInfo(string assemblyname, string typename, string membername, XPathNodeIterator itr, bool strlong)
1363                 {
1364                         if (quiet)
1365                                 return "";
1366                                 
1367                         ArrayList rgs = new ArrayList ();
1368                         while (itr.MoveNext ())
1369                                 rgs.Add (itr.Current.Value);
1370                         
1371                         return MonoImpInfo (assemblyname, typename, membername, rgs, strlong);
1372                 }
1373                 
1374                 public string MonoImpInfo(string assemblyname, string typename, string membername, ArrayList arglist, bool strlong)
1375                 {
1376                         try {
1377                                 Assembly assembly = null;
1378                                 
1379                                 try {
1380                                         assembly = Assembly.LoadWithPartialName(assemblyname);
1381                                 } catch (Exception) {
1382                                         // nothing.
1383                                 }
1384                                 
1385                                 if (assembly == null) {
1386                                         /*if (strlong) return "The assembly " + assemblyname + " is not available to MonoDoc.";
1387                                         else return "";*/
1388                                         return ""; // silently ignore
1389                                 }
1390
1391                                 Type t = assembly.GetType(typename, false);
1392                                 if (t == null) {
1393                                         if (strlong)
1394                                                 return typename + " has not been implemented.";
1395                                         else
1396                                                 return "Not implemented.";
1397                                 }
1398
1399                                 // The following code is flakey and fails to find existing members
1400                                 return "";
1401 #if false
1402                                 MemberInfo[] mis = t.GetMember(membername, BF.Static | BF.Instance | BF.Public | BF.NonPublic);
1403
1404                                 if (mis.Length == 0)
1405                                         return "This member has not been implemented.";
1406                                 if (mis.Length == 1)
1407                                         return MonoImpInfo(mis[0], "member", strlong);
1408
1409                                 // Scan for the appropriate member
1410                                 foreach (MemberInfo mi in mis) {
1411                                         System.Reflection.ParameterInfo[] pis;
1412
1413                                         if (mi is MethodInfo || mi is ConstructorInfo)
1414                                                 pis = ((MethodBase)mi).GetParameters();
1415                                         else if (mi is PropertyInfo)
1416                                                 pis = ((PropertyInfo)mi).GetIndexParameters();
1417                                         else
1418                                                 pis = null;
1419                                         
1420                                         if (pis != null) {
1421                                                 bool good = true;
1422                                                 if (pis.Length != arglist.Count) continue;
1423                                                 for (int i = 0; i < pis.Length; i++) {
1424                                                         if (pis[i].ParameterType.FullName != (string)arglist[i]) { good = false; break; }
1425                                                 }
1426                                                 if (!good) continue;
1427                                         }
1428
1429                                         return MonoImpInfo(mi, "member", strlong);
1430                                 }
1431 #endif
1432                         } catch (Exception) {
1433                                 return "";
1434                         }
1435                 }
1436                 
1437                 public string MonoImpInfo(System.Reflection.MemberInfo mi, string itemtype, bool strlong)
1438                 {
1439                         if (quiet)
1440                                 return "";
1441                                 
1442                         string s = "";
1443
1444                         object[] atts = mi.GetCustomAttributes(true);
1445                         int todoctr = 0;
1446                         foreach (object att in atts) if (att.GetType().Name == "MonoTODOAttribute") todoctr++;
1447
1448                         if (todoctr > 0) {
1449                                 if (strlong)
1450                                         s = "This " + itemtype + " is marked as being unfinished.<BR/>\n";
1451                                 else 
1452                                         s = "Unfinished.";
1453                         }
1454
1455                         return s;
1456                 }
1457
1458                 public string MonoImpInfo(string assemblyname, string typename, bool strlong)
1459                 {
1460                         if (quiet)
1461                                 return "";
1462                                 
1463                         try {
1464                                 if (assemblyname == "")
1465                                         return "";
1466
1467                                 Assembly assembly = Assembly.LoadWithPartialName(assemblyname);
1468                                 if (assembly == null)
1469                                         return "";
1470
1471                                 Type t = assembly.GetType(typename, false);
1472                                 if (t == null) {
1473                                         if (strlong)
1474                                                 return typename + " has not been implemented.";
1475                                         else
1476                                                 return "Not implemented.";
1477                                 }
1478
1479                                 string s = MonoImpInfo(t, "type", strlong);
1480
1481                                 if (strlong) {
1482                                         MemberInfo[] mis = t.GetMembers(BF.Static | BF.Instance | BF.Public | BF.NonPublic);
1483
1484                                         // Scan members for MonoTODO attributes
1485                                         int mctr = 0;
1486                                         foreach (MemberInfo mi in mis) {
1487                                                 string mii = MonoImpInfo(mi, null, false);
1488                                                 if (mii != "") mctr++; 
1489                                         }
1490                                         if (mctr > 0) {
1491                                                 s += "This type has " + mctr + " members that are marked as unfinished.<BR/>";
1492                                         }
1493                                 }
1494
1495                                 return s;
1496
1497                         } catch (Exception) {
1498                                 return "";
1499                         }                       
1500                 }
1501
1502                 public bool MonoEditing ()
1503                 {
1504                         return SettingsHandler.Settings.EnableEditing;
1505                 }
1506                 
1507                 public bool IsToBeAdded(string text) {
1508                         return text.StartsWith("To be added");
1509                 }
1510         }
1511
1512         //
1513         // This takes one of the ecma urls, which look like this:
1514         // ecma:NUMERIC_ID#OPAQUE/REST
1515         //
1516         // NUMERIC_ID is the numeric ID assigned by the compressor
1517         // OPAQUE is opaque for node rendering (it typically contains T:System.Byte for example)
1518         // REST is the rest of the argument used to decode information
1519         //
1520         static string GetFile (string url, out string rest)
1521         {
1522                 int pound = url.IndexOf ("#");
1523                 int slash = url.IndexOf ("/");
1524                 
1525                 string fname = url.Substring (0, pound);
1526                 rest = url.Substring (slash+1);
1527
1528                 return fname;
1529         }
1530
1531 #if false
1532         // This should have a little cache or something.
1533         static XmlDocument GetDocument (HelpSource hs, string fname)
1534         {
1535                 Stream s = hs.GetHelpStream (fname);
1536                 if (s == null){
1537                         Console.Error.WriteLine ("Could not fetch document {0}", fname);
1538                         return null;
1539                 }
1540                 
1541                 XmlDocument doc = new XmlDocument ();
1542
1543                 doc.Load (s);
1544                 
1545                 return doc;
1546         }
1547 #endif
1548         
1549         string GetKindFromCaption (string s)
1550         {
1551                 int p = s.LastIndexOf (' ');
1552                 if (p > 0)
1553                         return s.Substring (p + 1);
1554                 return null;
1555         }
1556         
1557         //
1558         // Obtain an URL of the type T:System.Object from the node
1559         // 
1560         public static string GetNiceUrl (Node node) {
1561                 if (node.Element.StartsWith("N:"))
1562                         return node.Element;
1563                 string name, full;
1564                 int bk_pos = node.Caption.IndexOf (' ');
1565                 // node from an overview
1566                 if (bk_pos != -1) {
1567                         name = node.Caption.Substring (0, bk_pos);
1568                         full = node.Parent.Caption + "." + name.Replace ('.', '+');
1569                         return "T:" + full;
1570                 }
1571                 // node that lists constructors, methods, fields, ...
1572                 if ((node.Caption == "Constructors") || (node.Caption == "Fields") || (node.Caption == "Events") 
1573                         || (node.Caption == "Members") || (node.Caption == "Properties") || (node.Caption == "Methods")
1574                         || (node.Caption == "Operators")) {
1575                         bk_pos = node.Parent.Caption.IndexOf (' ');
1576                         name = node.Parent.Caption.Substring (0, bk_pos);
1577                         full = node.Parent.Parent.Caption + "." + name.Replace ('.', '+');
1578                         return "T:" + full + "/" + node.Element; 
1579                 }
1580                 int pr_pos = node.Caption.IndexOf ('(');
1581                 // node from a constructor
1582                 if (node.Parent.Element == "C") {
1583                         name = node.Parent.Parent.Parent.Caption;
1584                         int idx = node.URL.IndexOf ('/');
1585                         return node.URL[idx+1] + ":" + name + "." + node.Caption.Replace ('.', '+');
1586                 // node from a method with one signature, field, property, operator
1587                 } else if (pr_pos == -1) {
1588                         bk_pos = node.Parent.Parent.Caption.IndexOf (' ');
1589                         name = node.Parent.Parent.Caption.Substring (0, bk_pos);
1590                         full = node.Parent.Parent.Parent.Caption + "." + name.Replace ('.', '+');
1591                         int idx = node.URL.IndexOf ('/');
1592                         return node.URL[idx+1] + ":" + full + "." + node.Caption;
1593                 // node from a method with several signatures
1594                 } else {
1595                         bk_pos = node.Parent.Parent.Parent.Caption.IndexOf (' ');
1596                         name = node.Parent.Parent.Parent.Caption.Substring (0, bk_pos);
1597                         full = node.Parent.Parent.Parent.Parent.Caption + "." + name.Replace ('.', '+');
1598                         int idx = node.URL.IndexOf ('/');
1599                         return node.URL[idx+1] + ":" + full + "." + node.Caption;
1600                 }
1601         }
1602                                 
1603         //
1604         // Populates the index.
1605         //
1606         public override void PopulateIndex (IndexMaker index_maker)
1607         {
1608                 foreach (Node ns_node in Tree.Nodes){
1609                         foreach (Node type_node in ns_node.Nodes){
1610                                 string typename = type_node.Caption.Substring (0, type_node.Caption.IndexOf (' '));
1611                                 string full = ns_node.Caption + "." + typename;
1612
1613                                 string doc_tag = GetKindFromCaption (type_node.Caption);
1614                                 string url = "T:" + full;
1615                                         
1616                                 if (doc_tag == "Class" || doc_tag == "Structure" || doc_tag == "Interface"){
1617
1618                                         index_maker.Add (type_node.Caption, typename, url);
1619                                         index_maker.Add (full + " " + doc_tag, full, url);
1620
1621                                         foreach (Node c in type_node.Nodes){
1622                                                 switch (c.Caption){
1623                                                 case "Constructors":
1624                                                         index_maker.Add ("  constructors", typename+"0", url + "/C");
1625                                                         break;
1626                                                 case "Fields":
1627                                                         index_maker.Add ("  fields", typename+"1", url + "/F");
1628                                                         break;
1629                                                 case "Events":
1630                                                         index_maker.Add ("  events", typename+"2", url + "/E");
1631                                                         break;
1632                                                 case "Properties":
1633                                                         index_maker.Add ("  properties", typename+"3", url + "/P");
1634                                                         break;
1635                                                 case "Methods":
1636                                                         index_maker.Add ("  methods", typename+"4", url + "/M");
1637                                                         break;
1638                                                 case "Operators":
1639                                                         index_maker.Add ("  operators", typename+"5", url + "/O");
1640                                                         break;
1641                                                 }
1642                                         }
1643
1644                                         //
1645                                         // Now repeat, but use a different sort key, to make sure we come after
1646                                         // the summary data above, start the counter at 6
1647                                         //
1648                                         string keybase = typename + "6.";
1649                                         
1650                                         foreach (Node c in type_node.Nodes){
1651                                                 switch (c.Caption){
1652                                                 case "Constructors":
1653                                                         break;
1654                                                 case "Fields":
1655                                                         foreach (Node nc in c.Nodes){
1656                                                                 string res = nc.Caption;
1657
1658                                                                 string nurl = String.Format ("F:{0}.{1}", full, res);
1659                                                                 index_maker.Add (String.Format ("{0}.{1} field", typename, res),
1660                                                                                  keybase + res, nurl);
1661                                                                 index_maker.Add (String.Format ("{0} field", res), res, nurl);
1662                                                         }
1663
1664                                                         break;
1665                                                 case "Events":
1666                                                         foreach (Node nc in c.Nodes){
1667                                                                 string res = nc.Caption;
1668                                                                 string nurl = String.Format ("E:{0}.{1}", full, res);
1669                                                                 
1670                                                                 index_maker.Add (String.Format ("{0}.{1} event", typename, res),
1671                                                                                  keybase + res, nurl);
1672                                                                 index_maker.Add (String.Format ("{0} event", res), res, nurl);
1673                                                         }
1674                                                         break;
1675                                                 case "Properties":
1676                                                         foreach (Node nc in c.Nodes){
1677                                                                 string res = nc.Caption;
1678                                                                 string nurl = String.Format ("P:{0}.{1}", full, res);
1679                                                                 index_maker.Add (String.Format ("{0}.{1} property", typename, res),
1680                                                                                  keybase + res, nurl);
1681                                                                 index_maker.Add (String.Format ("{0} property", res), res, nurl);
1682                                                         }
1683                                                         break;
1684                                                 case "Methods":
1685                                                         foreach (Node nc in c.Nodes){
1686                                                                 string res = nc.Caption;
1687                                                                 int p = res.IndexOf ("(");
1688                                                                 if (p > 0)
1689                                                                         res = res.Substring (0, p); 
1690                                                                 string nurl = String.Format ("M:{0}.{1}", full, res);
1691                                                                 index_maker.Add (String.Format ("{0}.{1} method", typename, res),
1692                                                                                  keybase + res, nurl);
1693                                                                 index_maker.Add (String.Format ("{0} method", res), res, nurl);
1694                                                         }
1695                                         
1696                                                         break;
1697                                                 case "Operators":
1698                                                         foreach (Node nc in c.Nodes){
1699                                                                 string res = nc.Caption;
1700                                                                 string nurl = String.Format ("O:{0}.{1}", full, res);
1701                                                                 index_maker.Add (String.Format ("{0}.{1} operator", typename, res),
1702                                                                                  keybase + res, nurl);
1703                                                         }
1704                                                         break;
1705                                                 }
1706                                         }
1707                                 } else if (doc_tag == "Enumeration"){
1708                                         //
1709                                         // Enumerations: add the enumeration values
1710                                         //
1711                                         index_maker.Add (type_node.Caption, typename, url);
1712                                         index_maker.Add (full + " " + doc_tag, full, url);
1713
1714                                         // Now, pull the values.
1715                                         string rest;
1716                                         XmlDocument x = GetXmlFromUrl (type_node.URL, out rest);
1717                                         if (x == null)
1718                                                 continue;
1719                                         
1720                                         XmlNodeList members = x.SelectNodes ("/Type/Members/Member");
1721
1722                                         if (members == null)
1723                                                 continue;
1724
1725                                         foreach (XmlNode member_node in members){
1726                                                 string enum_value = member_node.Attributes ["MemberName"].InnerText;
1727                                                 string caption = enum_value + " value";
1728                                                 index_maker.Add (caption, caption, url);
1729                                         }
1730                                 } else if (doc_tag == "Delegate"){
1731                                         index_maker.Add (type_node.Caption, typename, url);
1732                                         index_maker.Add (full + " " + doc_tag, full, url);
1733                                 }
1734                         }
1735                 }
1736         }
1737         //
1738         // Create list of documents for searching
1739         //
1740         public override void PopulateSearchableIndex (IndexWriter writer)
1741         {
1742                 StringBuilder text;
1743                 foreach (Node ns_node in Tree.Nodes) {
1744                         Console.WriteLine ("\tNamespace: {0} ({1})", ns_node.Caption, ns_node.Nodes.Count);
1745                         foreach (Node type_node in ns_node.Nodes) {
1746                                 string typename = type_node.Caption.Substring (0, type_node.Caption.IndexOf (' '));
1747                                 string full = ns_node.Caption + "." + typename;
1748                                 string doc_tag = GetKindFromCaption (type_node.Caption);
1749                                 string url = "T:" + full;
1750                                 string rest;
1751                                 XmlDocument xdoc = GetXmlFromUrl (type_node.URL, out rest);
1752                                 if (xdoc == null)
1753                                         continue;
1754                                 
1755                                 // 
1756                                 // For classes, structures or interfaces add a doc for the overview and
1757                                 // add a doc for every constructor, method, event, ...
1758                                 // 
1759                                 if (doc_tag == "Class" || doc_tag == "Structure" || doc_tag == "Interface"){
1760                                         
1761                                         // Adds a doc for every overview of every type
1762                                         SearchableDocument doc = new SearchableDocument ();
1763                                         doc.title = type_node.Caption;
1764                                         doc.hottext = typename;
1765                                         doc.url = url;
1766                                         
1767                                         XmlNode node_sel = xdoc.SelectSingleNode ("/Type/Docs");
1768                                         text  = new StringBuilder ();
1769                                         GetTextFromNode (node_sel, text);
1770                                         doc.text = text.ToString ();
1771
1772                                         text  = new StringBuilder ();
1773                                         GetExamples (node_sel, text);
1774                                         doc.examples = text.ToString ();
1775                                         
1776                                         writer.AddDocument (doc.LuceneDoc);
1777
1778                                         //Add docs for contructors, methods, etc.
1779                                         foreach (Node c in type_node.Nodes) { // c = Constructors || Fields || Events || Properties || Methods || Operators
1780                                                 
1781                                                 if (c.Element == "*")
1782                                                         continue;
1783                                                 int i = 1;
1784                                                 foreach (Node nc in c.Nodes) {
1785                                                         //xpath to the docs xml node
1786                                                         string xpath;
1787                                                         if (c.Caption == "Constructors")
1788                                                                 xpath = String.Format ("/Type/Members/Member[{0}]/Docs", i++);
1789                                                         else if (c.Caption == "Operators")
1790                                                                 xpath = String.Format ("/Type/Members/Member[@MemberName='op_{0}']/Docs", nc.Caption);
1791                                                         else
1792                                                                 xpath = String.Format ("/Type/Members/Member[@MemberName='{0}']/Docs", nc.Caption);
1793                                                         //construct url of the form M:Array.Sort
1794                                                         string urlnc;
1795                                                         if (c.Caption == "Constructors")
1796                                                                 urlnc = String.Format ("{0}:{1}.{2}", c.Caption[0], ns_node.Caption, nc.Caption);
1797                                                         else
1798                                                                 urlnc = String.Format ("{0}:{1}.{2}.{3}", c.Caption[0], ns_node.Caption, typename, nc.Caption);
1799
1800                                                         //create the doc
1801                                                         SearchableDocument doc_nod = new SearchableDocument ();
1802                                                         doc_nod.title = LargeName (nc);
1803                                                         //dont add the parameters to the hottext
1804                                                         int ppos = nc.Caption.IndexOf ('(');
1805                                                         if (ppos != -1)
1806                                                                 doc_nod.hottext =  nc.Caption.Substring (0, ppos);
1807                                                         else
1808                                                                 doc_nod.hottext = nc.Caption;
1809
1810                                                         doc_nod.url = urlnc;
1811
1812                                                         XmlNode xmln = xdoc.SelectSingleNode (xpath);
1813                                                         if (xmln == null) {
1814                                                                 Console.WriteLine ("Problem: {0}, with xpath: {1}", urlnc, xpath);
1815                                                                 continue;
1816                                                         }
1817
1818                                                         text = new StringBuilder ();
1819                                                         GetTextFromNode (xmln, text);
1820                                                         doc_nod.text = text.ToString ();
1821
1822                                                         text = new StringBuilder ();
1823                                                         GetExamples (xmln, text);
1824                                                         doc_nod.examples = text.ToString ();
1825
1826                                                         writer.AddDocument (doc_nod.LuceneDoc);
1827                                                 }
1828                                         }
1829                                 //
1830                                 // Enumerations: add the enumeration values
1831                                 //
1832                                 } else if (doc_tag == "Enumeration"){
1833                                                                                 
1834                                         XmlNodeList members = xdoc.SelectNodes ("/Type/Members/Member");
1835                                         if (members == null)
1836                                                 continue;
1837
1838                                         text = new StringBuilder ();
1839                                         foreach (XmlNode member_node in members) {
1840                                                 string enum_value = member_node.Attributes ["MemberName"].InnerText;
1841                                                 text.Append (enum_value);
1842                                                 text.Append (" ");
1843                                                 GetTextFromNode (member_node["Docs"], text);
1844                                                 text.Append ("\n");
1845                                         }
1846                                         SearchableDocument doc = new SearchableDocument ();
1847
1848                                         text = new StringBuilder ();
1849                                         GetExamples (xdoc.SelectSingleNode ("/Type/Docs"), text);
1850                                         doc.examples = text.ToString ();
1851
1852                                         doc.title = type_node.Caption;
1853                                         doc.hottext = xdoc.DocumentElement.Attributes["Name"].Value;
1854                                         doc.url = url;
1855                                         doc.text = text.ToString();
1856                                         writer.AddDocument (doc.LuceneDoc);
1857                                 //
1858                                 // Add delegates
1859                                 //
1860                                 } else if (doc_tag == "Delegate"){
1861                                         SearchableDocument doc = new SearchableDocument ();
1862                                         doc.title = type_node.Caption;
1863                                         doc.hottext = xdoc.DocumentElement.Attributes["Name"].Value;
1864                                         doc.url = url; 
1865                                         
1866                                         XmlNode node_sel = xdoc.SelectSingleNode ("/Type/Docs");
1867
1868                                         text = new StringBuilder ();
1869                                         GetTextFromNode (node_sel, text);
1870                                         doc.text = text.ToString();
1871
1872                                         text = new StringBuilder ();
1873                                         GetExamples (node_sel, text);
1874                                         doc.examples = text.ToString();
1875
1876                                         writer.AddDocument (doc.LuceneDoc);
1877                                 } 
1878                         }
1879                 }
1880         }
1881         
1882         //
1883         // Extract the interesting text from the docs node
1884         //
1885         void GetTextFromNode (XmlNode n, StringBuilder sb) 
1886         {
1887                 //don't include example code
1888                 if (n.Name == "code") 
1889                         return;
1890
1891                 //include the url to which points the see tag
1892                 if (n.Name == "see" && n.Attributes.Count > 0)
1893                                 sb.Append (n.Attributes [0].Value);
1894                 
1895                 //include the name of the parameter
1896                 if (n.Name == "paramref" && n.Attributes.Count > 0)
1897                         sb.Append (n.Attributes [0].Value);
1898
1899                 //include the contents for the node that contains text
1900                 if (n.NodeType == XmlNodeType.Text)
1901                         sb.Append (n.Value);
1902                 
1903                 //add the rest of xml tags recursively
1904                 if (n.HasChildNodes)
1905                         foreach (XmlNode n_child in n.ChildNodes)
1906                                 GetTextFromNode (n_child, sb);
1907         }
1908         //
1909         // Extract the code nodes from the docs
1910         //
1911         void GetExamples (XmlNode n, StringBuilder sb)
1912         {
1913                 if (n.Name == "code") {
1914                         sb.Append (n.InnerText);
1915                 } else {
1916                         if (n.HasChildNodes)
1917                                 foreach (XmlNode n_child in n.ChildNodes)
1918                                         GetExamples (n_child, sb);
1919                 }
1920         }
1921         //
1922         // Extract a large name for the Node
1923         //  (copied from mono-tools/docbrowser/browser.Render()
1924         static string LargeName (Node matched_node)
1925         {
1926                 string[] parts = matched_node.URL.Split('/', '#');                      
1927                 if(parts.Length == 3 && parts[2] != String.Empty) { //List of Members, properties, events, ...
1928                         return parts[1] + ": " + matched_node.Caption;
1929                 } else if(parts.Length >= 4) { //Showing a concrete Member, property, ...                                       
1930                         return parts[1] + "." + matched_node.Caption;
1931                 } else {
1932                         return matched_node.Caption;
1933                 }
1934         }
1935
1936 }
1937
1938 public class EcmaUncompiledHelpSource : EcmaHelpSource {
1939         readonly DirectoryInfo basedir;
1940         readonly XmlDocument basedoc;
1941         
1942         public new readonly string Name, BasePath;
1943         
1944         public EcmaUncompiledHelpSource (string base_file) : base ()
1945         {
1946                 Console.Error.WriteLine("Loading uncompiled help from " + base_file);
1947                 
1948                 basedir = new DirectoryInfo(base_file);
1949                 BasePath = basedir.FullName;
1950                 
1951                 basedoc = new XmlDocument();
1952                 basedoc.Load(Path.Combine(basedir.FullName, "index.xml"));
1953                 
1954                 Name = basedoc.SelectSingleNode("Overview/Title").InnerText;
1955                 
1956                 bool has_content = false;
1957                 
1958                 foreach (XmlElement ns in basedoc.SelectNodes("Overview/Types/Namespace")) {
1959                         has_content = true;
1960                         Node nsnode = Tree.CreateNode(ns.GetAttribute("Name"), "N:" + ns.GetAttribute("Name"));
1961                         
1962                         bool has_types = false;
1963                         foreach (XmlElement t in ns.SelectNodes("Type")) {
1964                                 has_types = true;
1965                                 string typename = EcmaDoc.GetDisplayName (t).Replace("+", ".");
1966                                 
1967                                 // Must load in each document to get the list of members...
1968                                 XmlDocument typedoc = new XmlDocument();
1969                                 typedoc.Load(Path.Combine(Path.Combine(basedir.FullName, ns.GetAttribute("Name")), t.GetAttribute("Name") + ".xml"));
1970                                 string kind = EcmaDoc.GetTypeKind (typedoc);
1971                                 
1972                                 string url = ns.GetAttribute("Name") + "." + t.GetAttribute("Name");
1973                                 Node typenode = nsnode.CreateNode(typename + " " + kind, "T:" + url);                           
1974                                 //Node typemembers = typenode.CreateNode("Members", "T:" + url + "/*");
1975                                 
1976                                 Hashtable groups = new Hashtable();
1977                                 Hashtable groups_count = new Hashtable();
1978                                 foreach (XmlElement member in typedoc.SelectNodes("Type/Members/Member")) {
1979                                         string membername = member.GetAttribute("MemberName");
1980                                         string membertype = member.SelectSingleNode("MemberType").InnerText;
1981                                         
1982                                         if (membertype == "Constructor")
1983                                                 membername = t.GetAttribute("Name");
1984                                         if (membername.StartsWith("op_"))
1985                                                 membertype = "Operator";
1986                                         
1987                                         Node group;
1988                                         if (groups.ContainsKey(membertype)) {
1989                                                 group = (Node)groups[membertype];
1990                                         } else {
1991                                                 string membertypeplural = membertype + "s";
1992                                                 if (membertypeplural == "Propertys") membertypeplural = "Properties";
1993                                                 
1994                                                 group = typenode.CreateNode(membertypeplural, "T:" + url + "/" + membertype[0]);
1995                                                 groups[membertype] = group;
1996                                                 groups_count[membertype] = 0;
1997                                         }
1998                                         
1999                                         if (membertype == "Constructor" || membertype == "Method" || 
2000                                                 (membertype == "Property" && member.SelectNodes("Parameters/Parameter").Count > 0)) {
2001                                                 membername = EcmaHelpSource.MakeSignature(member, membertype == "Constructor" ? membername : null);
2002                                         } else if (membertype == "Operator") {
2003                                                 string dummy;
2004                                                 EcmaHelpSource.MakeOperatorSignature(member, out dummy, out membername);
2005                                         }
2006                                         
2007                                         int index = (int)groups_count[membertype];
2008                                         groups_count[membertype] = index + 1;
2009                                         
2010                                         group.CreateNode(membername, index.ToString());
2011                                 }
2012
2013                                 foreach (Node group in groups.Values)
2014                                         group.Sort();                   
2015                         }
2016                         
2017                         if (has_types)
2018                                 nsnode.Sort();
2019                 }
2020                 
2021                 if (has_content)
2022                         Tree.Sort();
2023         }
2024         
2025         public override string GetIdFromUrl (string prefix, string ns, string type)
2026         {
2027                 if (prefix != "T:")
2028                         throw new NotImplementedException();
2029                 return Path.Combine(Path.Combine(basedir.FullName, ns), type + ".xml");
2030         }
2031
2032         protected override XmlDocument GetXmlFromUrl(string url, out string rest) {
2033                 // strip off the T:
2034                 url = url.Substring(2);
2035                 
2036                 int sidx = url.IndexOf("/");
2037                 if (sidx == -1) {
2038                         rest = "";
2039                 } else {
2040                         rest = url.Substring(sidx+1);
2041                         url = url.Substring(0, sidx);
2042                 }
2043                 
2044                 string ns, type;
2045                 if (!RootTree.GetNamespaceAndType (url, out ns, out type)) {
2046                         Console.Error.WriteLine ("Could not determine namespace/type for {0}",
2047                                         url);
2048                         return null;
2049                 }
2050                 
2051                 string file = Path.Combine(Path.Combine(basedir.FullName, ns), 
2052                                 ToEscapedTypeName (type).Replace ('.', '+') + ".xml");
2053                 if (!new FileInfo(file).Exists) return null;
2054                 
2055                 XmlDocument typedoc = new XmlDocument();
2056                 typedoc.Load(file);
2057                 return typedoc;
2058         }
2059         
2060         public override string GetText (string url, out Node match_node) {
2061                 if (url == "root:") {
2062                         match_node = null;
2063                         
2064                         //load index.xml
2065                         XmlDocument index = new XmlDocument ();
2066                         index.Load (Path.Combine (basedir.FullName, "index.xml"));
2067                         XmlNodeList nodes = index.SelectNodes ("/Overview/Types/Namespace");
2068                         
2069                         //recreate masteroverview.xml
2070                         XmlDocument summary = new XmlDocument ();
2071                         XmlElement elements = summary.CreateElement ("elements");
2072                         foreach (XmlNode node in nodes) {
2073                                 XmlElement ns = summary.CreateElement ("namespace");
2074                                 XmlAttribute attr = summary.CreateAttribute ("ns");
2075                                 attr.Value = EcmaDoc.GetDisplayName (node);
2076                                 ns.Attributes.Append (attr);
2077                                 elements.AppendChild (ns);
2078                         }
2079                         summary.AppendChild (elements);
2080
2081                         XmlReader reader = new XmlTextReader (new StringReader (summary.OuterXml));
2082
2083                         //transform the recently created masteroverview.xml
2084                         XsltArgumentList args = new XsltArgumentList();
2085                         args.AddExtensionObject("monodoc:///extensions", ExtObject);
2086                         args.AddParam("show", "", "masteroverview");
2087                         string s = EcmaHelpSource.Htmlize(new XPathDocument (reader), args);
2088                         return BuildHtml (css_ecma_code, js_code, s); 
2089                 }
2090                 return base.GetText(url, out match_node);
2091         }
2092         
2093         protected override XmlReader GetNamespaceDocument (string ns) {
2094                 XmlDocument nsdoc = new XmlDocument();
2095                 nsdoc.Load (EcmaDoc.GetNamespaceFile (basedir.FullName, ns));
2096                 
2097                 XmlDocument elements = new XmlDocument();
2098                 XmlElement docnode = elements.CreateElement("elements");
2099                 
2100                 foreach (XmlElement doc in nsdoc.SelectNodes("Namespace/Docs/*")) {
2101                         docnode.AppendChild(elements.ImportNode(doc, true));
2102                 }
2103                                 
2104                 foreach (XmlElement t in basedoc.SelectNodes("Overview/Types/Namespace[@Name='" + ns + "']/Type")) {
2105                         XmlDocument typedoc = new XmlDocument();
2106                         typedoc.Load(Path.Combine(Path.Combine(basedir.FullName, ns), t.GetAttribute("Name") + ".xml"));
2107                         
2108                         string typekind;
2109                         switch (EcmaDoc.GetTypeKind(typedoc)) {
2110                         case "Class": typekind = "class"; break;
2111                         case "Enumeration": typekind = "enum"; break;
2112                         case "Structure": typekind = "struct"; break;
2113                         case "Delegate": typekind = "delegate"; break;
2114                         case "Interface": typekind = "interface"; break;
2115                         default: throw new InvalidOperationException();
2116                         }
2117                         
2118                         XmlElement typenode = elements.CreateElement(typekind);
2119                         typenode.SetAttribute("name", EcmaDoc.GetDisplayName (t).Replace ('+', '.'));
2120                         typenode.SetAttribute("fullname", ns + "." + t.GetAttribute("Name"));
2121                         typenode.AppendChild(elements.ImportNode(typedoc.SelectSingleNode("Type/Docs/summary"), true));
2122                         
2123                         docnode.AppendChild(typenode);
2124                 }
2125
2126                 return new XmlNodeReader(docnode);
2127         }
2128         
2129 }
2130
2131 }
2132
2133