math-suite/Source/Help/HelpSystem/HelpManager.cs

135 lines
4.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace Help.HelpSystem
{
static class HelpManager
{
public static List<HelpChapter> Chapters = new List<HelpChapter>();
public static string DocumentationPath = "";
public static string GetFullPath(string relative)
{
return System.IO.Path.Combine(DocumentationPath, relative);
}
public static void Load(string indexfile)
{
XmlTextReader reader = new XmlTextReader(indexfile);
HelpChapter currentChapter = new HelpChapter();
HelpTopic currentTopic = new HelpTopic();
bool isTopic = false;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == "chapter")
{
isTopic = false;
currentChapter = new HelpChapter();
}
else if (reader.Name == "topic")
{
isTopic = true;
currentTopic = new HelpTopic();
}
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "application": if (!isTopic) currentChapter.Application = reader.Value; break;
case "title":
if (isTopic) currentTopic.Title = reader.Value;
else currentChapter.Title = reader.Value;
break;
case "filename":
if (isTopic) currentTopic.Filename = reader.Value;
else currentChapter.Filename = reader.Value;
break;
}
}
if (isTopic) currentChapter.Topics.Add(currentTopic);
break;
case XmlNodeType.EndElement:
if (reader.Name == "topic") currentChapter.Topics.Add(currentTopic);
else if (reader.Name == "chapter") Chapters.Add(currentChapter);
break;
}
}
reader.Close();
DocumentationPath = System.IO.Path.GetDirectoryName(indexfile);
}
private static string[] FindInFile(string file, string q)
{
int min, max;
string text = System.IO.File.ReadAllText(file);
List<string> ret = new List<string>();
// Remove html tags
min = text.IndexOf('<');
max = text.IndexOf('>');
while (min != -1 && max != -1 && min < max)
{
text = text.Remove(min, max - min + 1);
min = text.IndexOf('<');
max = text.IndexOf('>');
}
// Search each line
foreach (var line in text.Split('\n', '\r'))
if (line.ToLower().Contains(q.ToLower())) ret.Add(line.TrimStart(' ', '\t', '\n', '\r'));
return ret.ToArray();
}
public static HelpTopic[] SearchText(string text, HelpChapter chapter)
{
var list = new List<HelpTopic>();
// Make a list of files to be checked
var temp = new List<HelpTopic>();
temp.Add(new HelpTopic(chapter.Title, chapter.Filename));
temp.AddRange(chapter.Topics);
// Search
foreach (var top in temp)
{
string[] f = FindInFile(GetFullPath(top.Filename), text);
foreach (var i in f)
list.Add(new HelpTopic()
{
Title = top.Title,
Filename = top.Filename,
Context = i,
IsSearchResult = true
});
}
return list.ToArray();
}
public static HelpTopic[] SearchTitle(string text, HelpChapter chapter)
{
return chapter.Topics.Where(x => x.Title.ToLower().Contains(text.ToLower())).ToArray();
}
}
}