Initial import

git-svn-id: https://lsleditor.svn.sourceforge.net/svnroot/lsleditor@1 3f4676ac-adda-40fd-8265-58d1435b1672
This commit is contained in:
dimentox 2010-04-29 03:23:31 +00:00
commit 7d308772cf
453 changed files with 57506 additions and 0 deletions

373
Helpers/AutoFormatter.cs Normal file
View file

@ -0,0 +1,373 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace LSLEditor
{
class AutoFormatter
{
public static string GetTab()
{
if (Properties.Settings.Default.SL4SpacesIndent)
return " ";
else
return "\t";
}
private static int CountParenthesis(string strLine)
{
int intParenthesis=0;
bool blnWithinString = false;
for (int intI = 0; intI < strLine.Length; intI++)
{
if (strLine[intI] == '"')
blnWithinString = !blnWithinString;
if (blnWithinString)
{
if (strLine[intI] == '\\')
intI++;
continue;
}
if (strLine[intI] == '/')
{
if(intI<(strLine.Length-1))
if (strLine[intI + 1] == '/')
break;
}
if (strLine[intI] == '{')
intParenthesis++;
if (strLine[intI] == '}')
intParenthesis--;
}
return intParenthesis;
}
private static int GetTabCountFromWhiteSpace(string strWhiteSpace)
{
int intSpaces = 0;
for (int intI = 0; intI < strWhiteSpace.Length; intI++)
{
if(strWhiteSpace[intI]==' ')
intSpaces++;
if (strWhiteSpace[intI] == '\t')
intSpaces = (int)(6 * (intSpaces / 6)) + 6 - (intSpaces % 6);
}
if (Properties.Settings.Default.SL4SpacesIndent)
return intSpaces / 4;
else
return intSpaces / 6;
}
public static string GetWhiteSpaceFromLine(string strLine)
{
StringBuilder sb = new StringBuilder();
for (int intI = 0; intI < strLine.Length; intI++)
{
if (strLine[intI] > ' ')
break;
sb.Append(strLine[intI]);
}
return sb.ToString();
}
private static int GetTabCountFromLine(string strLine, out int intOnce)
{
StringBuilder sb = new StringBuilder();
int intCountParenthesis = CountParenthesis(strLine);
if(intCountParenthesis<0)
intCountParenthesis = 0;
for (int intI = 0; intI < strLine.Length; intI++)
{
if (strLine[intI] > ' ')
break;
sb.Append(strLine[intI]);
}
intOnce = 0;
strLine = TrimCommentTrim(strLine);
int intLength = strLine.Length;
if (intLength > 0)
{
char chrLastChar = strLine[intLength - 1];
if (strLine[0] == '{' || chrLastChar == ';' || chrLastChar == '{' || chrLastChar == '}')
intOnce = 0;
else
intOnce = 1;
// this only valid for typing
if (intCountParenthesis == 0 && chrLastChar == '{')
intCountParenthesis++;
}
return GetTabCountFromWhiteSpace(sb.ToString()) + intCountParenthesis + intOnce;
}
public static string RemoveComment(string strLine)
{
bool blnWithinString = false;
for (int intI = 0; intI < (strLine.Length - 1); intI++)
{
char chrC = strLine[intI];
if (chrC == '"')
blnWithinString = !blnWithinString;
if (blnWithinString)
{
if (chrC == '\\')
intI++;
continue;
}
if (chrC != '/')
continue;
if (strLine[intI + 1] == '/')
{
strLine = strLine.Substring(0, intI);
break;
}
}
return strLine;
}
public static string RemoveCommentsFromLines(string strLines)
{
StringBuilder sb = new StringBuilder();
StringReader sr = new StringReader(strLines);
while (true)
{
string strLine = sr.ReadLine();
if (strLine == null)
break;
sb.AppendLine(RemoveComment(strLine));
}
return sb.ToString();
}
private static string TrimCommentTrim(string strLine)
{
return RemoveComment(strLine).Trim();
}
public static string GetNewWhiteSpace(string[] lines, int intIndex)
{
int intTab = 0;
int intOnce = 0;
string strLine = "";
StringBuilder sb = new StringBuilder();
while (intIndex>=0 && intIndex<lines.Length)
{
strLine = lines[intIndex];
if (TrimCommentTrim(strLine).Length > 0)
{
intTab = GetTabCountFromLine(strLine, out intOnce);
break;
}
intIndex--;
}
if (TrimCommentTrim(strLine) != "{")
{
intIndex--;
while (intIndex >= 0 && intIndex < lines.Length)
{
strLine = lines[intIndex];
if (TrimCommentTrim(strLine).Length > 0)
{
GetTabCountFromLine(strLine, out intOnce);
break;
}
intIndex--;
}
}
for (int intI = 0; intI < (intTab - intOnce); intI++)
sb.Append(AutoFormatter.GetTab());
return sb.ToString();
}
public static string ApplyFormatting(int intTab, string strInput)
{
StringBuilder sb = new StringBuilder();
StringReader sr = new StringReader(strInput);
Stack<int> stack = new Stack<int>();
stack.Push(intTab);
int intTemp = 0;
while (true)
{
string strLine = sr.ReadLine();
if (strLine == null)
break;
// trim whitespace, this is a clean line
strLine = strLine.Trim();
// empty lines do not contain tabs
if (strLine.Length == 0)
{
sb.Append('\n');
continue;
}
// print current line, on current indent level
int intCorrection = 0;
if (strLine[0] == '{' || strLine[0] == '}')
intCorrection--;
for (int intI = 0; intI < (intTab + intTemp + intCorrection); intI++)
sb.Append(GetTab());
sb.Append(strLine);
sb.Append('\n');
// calculate next indent level
strLine = TrimCommentTrim(strLine);
int intParenthesis = CountParenthesis(strLine);
if (intParenthesis > 0)
{
for (int intP = 0; intP < intParenthesis; intP++)
{
stack.Push(intTab);
if (strLine != "{")
intTab++;
}
intTab += intTemp;
intTemp = 0;
}
else if (intParenthesis < 0)
{
if (stack.Count > 0)
intTab = stack.Pop();
intTemp = 0;
}
else
{
if (strLine.Length > 0)
{
char chrFirstChar = strLine[0];
char chrLastChar = strLine[strLine.Length - 1];
intTemp++;
if (chrFirstChar == '|' || chrLastChar == '|')
intTemp = 1;
if (chrFirstChar == '+' || chrLastChar == '+')
intTemp = 1;
if (chrFirstChar == '-' || chrLastChar == '-')
intTemp = 1;
if (chrLastChar == ',' || chrLastChar == ',')
intTemp = 1;
if (chrLastChar == ';' || chrLastChar == '}')
intTemp = 0;
}
}
}
if (!strInput.EndsWith("\n"))
return sb.ToString().TrimEnd(new char[] { '\n' });
else
return sb.ToString();
}
public static string MultiLineTab(bool blnAdd, string strText)
{
string strPrefix = GetTab();
StringBuilder sb = new StringBuilder();
StringReader sr = new StringReader(strText);
while (true)
{
string strLine = sr.ReadLine();
if (strLine == null)
break;
if (blnAdd)
{
sb.Append(strPrefix);
}
else
{
if (strLine.StartsWith(strPrefix))
strLine = strLine.Substring(strPrefix.Length);
}
sb.Append(strLine);
sb.Append('\n');
}
return sb.ToString();
}
public static string MultiLineComment(bool blnAdd, int intTab, string strText)
{
string strPrefix = "//";
StringBuilder sb = new StringBuilder();
StringReader sr = new StringReader(strText);
while (true)
{
string strLine = sr.ReadLine();
if (strLine == null)
break;
if (blnAdd)
{
sb.Append(strPrefix);
}
else
{
strLine = strLine.Trim();
if (strLine.StartsWith(strPrefix))
strLine = strLine.Substring(strPrefix.Length);
}
sb.Append(strLine);
sb.Append('\n');
}
return ApplyFormatting(intTab,sb.ToString());
}
}
}

105
Helpers/CodeCompletion.cs Normal file
View file

@ -0,0 +1,105 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System.Drawing;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace LSLEditor.Helpers
{
class CodeCompletion
{
Regex regex;
public CodeCompletion()
{
this.regex = new Regex(
@"
\b(?<type>integer|float|string|vector|rotation|state|key|list)\s
(?>
\s* (?<name>[\w]*) \s*
(?>\= \s*
(?:
(?>
[^(),;]+
| \( (?<nr>)
| \) (?<-nr>)
)*
(?(nr)(?!))
)
\s*)? [,;)]
)*
"
,
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled);
}
public void CodeCompletionUserVar(string strKeyWord, string strTextIn, int intStart, List<KeyWordInfo> list)
{
if (intStart == 0)
return;
string strText = strTextIn.Substring(0, intStart);
string strLowerCaseKeyWord = strKeyWord.ToLower();
foreach (Match m in regex.Matches(strText))
{
if (m.Groups.Count == 4)
{
string strType = m.Groups[1].ToString();
foreach (Capture cap in m.Groups[2].Captures)
{
string strName = cap.ToString();
if (strName.ToLower().StartsWith(strLowerCaseKeyWord))
{
KeyWordInfo ki = new KeyWordInfo(KeyWordTypeEnum.Vars, strName, Color.Red);
if (!list.Contains(ki))
list.Add(ki);
}
if (strType == "list" || strType == "vector" || strType == "rotation")
break;
}
}
}
}
}
}

145
Helpers/CompilerHelper.cs Normal file
View file

@ -0,0 +1,145 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace LSLEditor.Helpers
{
class CompilerHelper
{
private static int FindDefaultLineNumber(string strCode)
{
StringReader sr = new StringReader(strCode);
int intI = 0;
while (true)
{
string strLine = sr.ReadLine();
if (strLine == null)
break;
if (strLine.StartsWith("class State_default"))
return intI;
intI++;
}
return intI;
}
public static Assembly CompileCSharp(EditForm editForm, string CSharpCode)
{
// Code compiler and provider
CodeDomProvider cc = new CSharpCodeProvider();
// Compiler parameters
CompilerParameters cp = new CompilerParameters();
// Sept 15, 2007 -> 3, 30 oct 2007 -> 4
if(!Properties.Settings.Default.SkipWarnings)
cp.WarningLevel = 4;
// Add common assemblies
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
// LSLEditor.exe contains all base SecondLife class stuff
cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
// Compiling to memory
cp.GenerateInMemory = true;
// Does this work?
cp.IncludeDebugInformation = true;
// Wrap strCSharpCode into my namespace
string strRunTime = "namespace LSLEditor\n{\n";
strRunTime += CSharpCode;
strRunTime += "\n}\n";
int intDefaultLineNumber = FindDefaultLineNumber(strRunTime);
// Here we go
CompilerResults cr = cc.CompileAssemblyFromSource(cp, strRunTime);
// get the listview to store some errors
ListView ListViewErrors = editForm.parent.SyntaxErrors.ListView;
// Console.WriteLine(cr.Errors.HasWarnings.ToString());
// Check for compilation errors...
if (ListViewErrors != null && (cr.Errors.HasErrors || cr.Errors.HasWarnings))
{
int intNr = 1;
foreach (CompilerError err in cr.Errors)
{
int intLine = err.Line;
if (intLine < intDefaultLineNumber)
intLine -= 4;
else
intLine -= 5;
string strError = OopsFormatter.ApplyFormatting(err.ErrorText);
int intImageIndex = 0;
if (err.IsWarning)
intImageIndex = 1;
ListViewItem lvi = new ListViewItem(new string[] {
"", // 0
intNr.ToString(), // 1
strError, // 2
editForm.ScriptName, // 3
intLine.ToString(), // 4
err.Column.ToString(), // 5
editForm.ProjectName , // 6
editForm.FullPathName, // 7
editForm.guid.ToString(),// 8
editForm.IsScript.ToString()// 9
} , intImageIndex);
ListViewErrors.Items.Add(lvi);
intNr++;
}
return null;
}
return cr.CompiledAssembly;
}
}
}

115
Helpers/FileAssociator.cs Normal file
View file

@ -0,0 +1,115 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Text;
using Microsoft.Win32;
namespace LSLEditor.Helpers
{
class FileAssociator
{
// Associate file extension with progID, description, icon and application
public static bool Associate(string strExtension, string strFileNameType, string strDescription, string strApplication,int intIconNr)
{
try
{
Registry.ClassesRoot.CreateSubKey(strExtension).SetValue("", strFileNameType);
if (strFileNameType != null && strFileNameType.Length > 0)
{
using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(strFileNameType))
{
if (strDescription != null)
key.SetValue("", strDescription);
if (strApplication != null)
{
key.CreateSubKey("DefaultIcon").SetValue("", strApplication + "," + intIconNr);
key.CreateSubKey(@"Shell\Open\Command").SetValue("", "\"" + strApplication + "\" \"%1\"");
}
}
}
return true;
}
catch
{
return false;
}
}
public static bool DeAssociate(string strExtension, string strFileNameType)
{
try
{
Registry.ClassesRoot.DeleteSubKey(strExtension);
Registry.ClassesRoot.DeleteSubKeyTree(strFileNameType);
return true;
}
catch
{
return false;
}
}
// Return true if extension already associated in registry
public static bool IsAssociated(string strExtension)
{
try
{
return (Registry.ClassesRoot.OpenSubKey(strExtension, false) != null);
}
catch
{
return false;
}
}
private void Test()
{
if (!IsAssociated(".lsl"))
Associate(".lsl", "LSLEditorScript", "SecondLife lsl File for LSLEditor", System.Reflection.Assembly.GetExecutingAssembly().Location, 0);
DeAssociate(".lsl", "LSLEditorScript");
}
}
}

71
Helpers/GetTemplate.cs Normal file
View file

@ -0,0 +1,71 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Reflection;
using System.IO;
namespace LSLEditor.Helpers
{
class GetTemplate
{
public static string Source()
{
try
{
string strTemplate = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Properties.Settings.Default.ExampleTemplate);
if (File.Exists(strTemplate))
{
StreamReader sr = new StreamReader(strTemplate);
string strCode = sr.ReadToEnd();
sr.Close();
return strCode;
}
}
catch
{
}
return Properties.Settings.Default.Example;
}
}
}

190
Helpers/GroupboxEvent.cs Normal file
View file

@ -0,0 +1,190 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace LSLEditor
{
/// <summary>
/// Summary description for GroupboxTextbox.
/// </summary>
public class GroupboxEvent : System.Windows.Forms.GroupBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public GroupboxEvent(Point pt,string strName,string strArgs,System.EventHandler eventHandler)
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.Location = pt;
string[] args = strArgs.Trim().Split(new char[] {','});
int intX=5;
int intY=5;
if(args.Length>0)
intY += 5;
for(int intArgumentNumber=0;intArgumentNumber<args.Length;intArgumentNumber++)
{
string[] argument = args[intArgumentNumber].Trim().Split(new char[] {' '});
if(argument.Length==2)
{
string strArgumentName = argument[1];
string strArgumentType = argument[0];
string strArgumentValue = "";
switch(strArgumentType)
{
case "System.double":
case "LSLEditor.SecondLife+Float":
strArgumentValue = "1.0";
break;
case "LSLEditor.integer":
case "LSLEditor.SecondLife+integer":
case "System.Int32":
strArgumentValue = "1";
break;
case "LSLEditor.SecondLife+String":
case "System.String":
strArgumentValue = "hello";
break;
case "LSLEditor.SecondLife+key":
strArgumentValue = Guid.NewGuid().ToString();
break;
case "LSLEditor.SecondLife+rotation":
strArgumentValue = "<0,0,0,1>";
break;
case "LSLEditor.SecondLife+vector":
strArgumentValue = "<0,0,0>";
break;
case "LSLEditor.SecondLife+list":
strArgumentValue = "";
break;
default:
MessageBox.Show("GroupboxEvent->["+strArgumentType+"]["+strArgumentName+"]");
strArgumentValue = "unknown";
break;
}
GroupBox groupbox = new GroupBox();
groupbox.Name = strName+"_"+intArgumentNumber;
groupbox.Text = strArgumentName;
groupbox.Location = new Point(5,intY);
groupbox.Width = this.Width - 10;
Control control = null;
if (strName == "listen" && intArgumentNumber==0)
{
ComboBox comboBox = new ComboBox();
comboBox.Text = "";
control = comboBox;
}
else
{
TextBox textBox = new TextBox();
textBox.Text = strArgumentValue;
control = textBox;
}
control.Name = "textBox_" + strName + "_" + intArgumentNumber;
control.Location = new Point(5, 15);
groupbox.Controls.Add(control);
groupbox.Height = 20 + control.Height;
this.Controls.Add(groupbox);
intY += groupbox.Height;
}
else
{
if(strArgs!="")
MessageBox.Show("Argument must be 'type name' ["+strArgs+"]");
}
}
intY += 5;
Button button = new Button();
button.Text = strName;
button.Width = 130;
button.Location = new Point(intX,intY);
button.Click += eventHandler;
this.Controls.Add(button);
this.Height = intY + button.Height + 5;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// GroupboxTextbox
//
this.Name = "GroupboxTextbox";
this.Size = new System.Drawing.Size(152, 96);
}
#endregion
}
}

130
Helpers/GroupboxEvent.resx Normal file
View file

@ -0,0 +1,130 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used forserialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.SnapToGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</data>
<data name="$this.DrawGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</data>
<data name="$this.TrayHeight" type="System.Int32, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>80</value>
</data>
<data name="$this.Language" type="System.Globalization.CultureInfo, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>(Default)</value>
</data>
<data name="$this.Localizable" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</data>
<data name="$this.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>Private</value>
</data>
<data name="$this.Name">
<value>GroupboxTextbox</value>
</data>
<data name="$this.GridSize" type="System.Drawing.Size, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>8, 8</value>
</data>
</root>

204
Helpers/HTTPRequest.cs Normal file
View file

@ -0,0 +1,204 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Net;
using System.Text;
namespace LSLEditor
{
class HTTPRequest
{
private class UserState
{
public SecondLife secondlife;
public SecondLife.key httpkey;
public UserState(SecondLife.key httpkey, SecondLife secondlife)
{
this.secondlife = secondlife;
this.httpkey = httpkey;
}
}
public static void Request(WebProxy proxy, SecondLife secondlife, string strUrl, SecondLife.list parameters, string postData, SecondLife.key key)
{
string strMethod = "GET";
string strContentType = "text/plain;charset=utf-8";
for (int intI = 0; intI < parameters.Count; intI += 2)
{
int intKey;
if (!int.TryParse(parameters[intI].ToString(), out intKey))
continue;
switch (intKey)
{
case 0:
// get, post, put, delete
strMethod = parameters[intI + 1].ToString().ToUpper();
break;
case 1:
strContentType = parameters[intI + 1].ToString();
break;
case 2:
// HTTP_BODY_MAXLENGTH
break;
case 3:
// HTTP_VERIFY_CERT
break;
default:
break;
}
}
WebClient wc = new WebClient();
wc.Headers.Add("Content-Type", strContentType);
wc.Headers.Add("Accept", "text/*");
wc.Headers.Add("Accept-Charset", "utf-8;q=1.0, *;q=0.5");
wc.Headers.Add("Accept-Encoding", "deflate, gzip");
wc.Headers.Add("User-Agent", "Second Life LSL/1.19.0(12345) (http://secondlife.com)");
System.Drawing.Point point = Properties.Settings.Default.RegionCorner;
SecondLife.vector RegionCorner = new SecondLife.vector(point.X, point.Y, 0);
SecondLife.vector pos = secondlife.GetLocalPos();
wc.Headers.Add("X-SecondLife-Shard", Properties.Settings.Default.XSecondLifeShard);
wc.Headers.Add("X-SecondLife-Object-Name", secondlife.host.GetObjectName());
wc.Headers.Add("X-SecondLife-Object-Key", secondlife.host.GetKey().ToString());
wc.Headers.Add("X-SecondLife-Region", string.Format("{0} ({1}, {2})", Properties.Settings.Default.RegionName, (int)RegionCorner.x, (int)RegionCorner.y));
wc.Headers.Add("X-SecondLife-Local-Position", string.Format("({0}, {1}, {2})", pos.x, pos.y, pos.z));
wc.Headers.Add("X-SecondLife-Local-Rotation", "(0.000000, 0.000000, 0.000000, 1.000000)");
wc.Headers.Add("X-SecondLife-Local-Velocity", "(0.000000, 0.000000, 0.000000)");
wc.Headers.Add("X-SecondLife-Owner-Name", Properties.Settings.Default.AvatarName);
wc.Headers.Add("X-SecondLife-Owner-Key", Properties.Settings.Default.AvatarKey);
wc.Headers.Add("X-Forwarded-For", "127.0.0.1");
if (proxy != null)
wc.Proxy = proxy;
Uri uri = new Uri(strUrl);
// Basic Authentication scheme, added 28 mrt 2008
if (uri.UserInfo != "")
{
string[] UserInfo = uri.UserInfo.Split(':');
if (UserInfo.Length == 2)
{
CredentialCache mycache = new CredentialCache();
mycache.Add(uri, "Basic",
new NetworkCredential(UserInfo[0], UserInfo[1]));
wc.Credentials = mycache;
}
}
UserState userState = new UserState(key, secondlife);
if (strMethod == "POST" || strMethod == "PUT")
{
wc.UploadDataCompleted += new UploadDataCompletedEventHandler(wc_UploadDataCompleted);
wc.UploadDataAsync(uri, strMethod, Encoding.UTF8.GetBytes(postData), userState);
}
else
{
wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler(wc_DownloadDataCompleted);
wc.DownloadDataAsync(uri, userState);
}
}
private static void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
int intStatusCode = 200;
UserState userState = (UserState)e.UserState;
string strResult = "";
if (e.Error != null)
{
WebException webException = e.Error as WebException;
HttpWebResponse webResponse = webException.Response as HttpWebResponse;
if (webResponse == null)
{
intStatusCode = 0;
strResult = webException.Message;
}
else
{
intStatusCode = (int)webResponse.StatusCode;
System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream());
strResult = sr.ReadToEnd();
}
}
else
{
if (e.Result != null)
strResult = Encoding.ASCII.GetString(e.Result);
}
userState.secondlife.host.ExecuteSecondLife("http_response", userState.httpkey, (SecondLife.integer)intStatusCode, new SecondLife.list(), (SecondLife.String)strResult);
}
private static void wc_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
int intStatusCode = 200;
UserState userState = (UserState)e.UserState;
string strResult = "";
if (e.Error != null)
{
WebException webException = e.Error as WebException;
HttpWebResponse webResponse = webException.Response as HttpWebResponse;
intStatusCode = (int)webResponse.StatusCode;
System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream());
strResult = sr.ReadToEnd();
}
else
{
if (e.Result != null)
strResult = Encoding.ASCII.GetString(e.Result);
}
userState.secondlife.host.ExecuteSecondLife("http_response", userState.httpkey, (SecondLife.integer)intStatusCode, new SecondLife.list(), (SecondLife.String)strResult);
}
}
}

642
Helpers/LSL2CSharp.cs Normal file
View file

@ -0,0 +1,642 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Xml;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace LSLEditor
{
class LSL2CSharp
{
public List<string> States;
private XmlDocument xml;
public LSL2CSharp(XmlDocument xml)
{
this.xml = xml;
this.States = new List<string>();
}
private string CorrectGlobalEvaluator(Match m)
{
string strPrefix = m.Groups["prefix"].Value;
string strPublic = m.Groups["public"].Value;
string strPostfix = m.Groups["postfix"].Value;
if (strPublic.EndsWith(";"))
return strPrefix + "public static " + strPublic + strPostfix;
// has to be static,
// because the vars must keep their values between state changes
// 22 june 2007, added
Regex regex = new Regex(@"\w*", RegexOptions.IgnorePatternWhitespace );
int intCount=0;
for (Match pm = regex.Match(strPublic); pm.Success; pm = pm.NextMatch())
{
if (pm.Value.Length > 0)
intCount++;
if (intCount > 1)
break;
}
if(intCount==1)
return strPrefix + "public void " + strPublic + strPostfix;
else
return strPrefix + "public " + strPublic + strPostfix;
}
private string CorrectGlobal(string strC)
{
Regex regex = new Regex(
@"(?<prefix>\s*)
(?:
(?<public>[^{};]*;)
|
(?<public>[^{;(]*)
(?<postfix>
\( [^{]* \) \s*
\{
(?>
[^{}]+
| \{ (?<number>)
| \} (?<-number>)
)*
(?(number)(?!))
\}
)
)",
RegexOptions.IgnorePatternWhitespace);
return regex.Replace(strC, new MatchEvaluator(CorrectGlobalEvaluator));
}
private string RemoveComments(string strC)
{
if (Properties.Settings.Default.CommentCStyle)
{
int intI = strC.IndexOf("/*");
while (intI > 0)
{
int intJ = strC.IndexOf("*" + "/", intI);
if (intJ < 0)
break;
strC = strC.Remove(intI, intJ - intI + 2);
intI = strC.IndexOf("/*");
}
}
return AutoFormatter.RemoveCommentsFromLines(strC);
}
private string CorrectStates(string strC,string strGlobalClass)
{
Regex regex;
// Default state
regex = new Regex(@"^\s*(default)(\W)",
RegexOptions.Multiline
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled);
strC = regex.Replace(strC, @"class State_$1 : " + strGlobalClass + "$2");
// Other states
regex = new Regex(
@"^state\s+([^\s]*)(\s*\{)",
RegexOptions.Multiline
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
Match m = regex.Match(strC);
while (m.Success)
{
string strStateName = m.Groups[1].ToString();
this.States.Add(strStateName);
m = m.NextMatch();
}
strC = regex.Replace(strC, "class State_$1 : " + strGlobalClass + "$2");
string strGlobal = "";
if (Properties.Settings.Default.StatesInGlobalFunctions)
{
// do nothing!
}
else
{
int intDefault = strC.IndexOf("class State_default");
if (intDefault >= 0)
{
strGlobal = strC.Substring(0, intDefault);
strC = strC.Substring(intDefault);
}
}
// State change, excluding global functions
regex = new Regex(
@"(\s+)state\s+(\w*)(\s*;)",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
return strGlobal + regex.Replace(strC, @"$1state(""$2"")$3");
}
private string PreCorrectReservedWords(string strC)
{
#region All PreCorrect reserved C# words
Regex regex = new Regex(@"(\b)(public
| class
| override
| namespace
| void
| SecondLife
| GlobalClass
| static
| goto
| String
| Float
)(\b)",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
#endregion
return regex.Replace(strC, "$1_$2$3");
}
private string CorrectReservedWords(string strC)
{
#region All reserved C# words
Regex regex = new Regex(@"(\b)(new
| abstract
| as
| base
| bool
| break
| byte
| case
| catch
| char
| checked
| const
| continue
| decimal
| delegate
| double
| enum
| event
| explicit
| extern
| false
| finally
| fixed
| foreach
| implicit
| in
| int
| interface
| internal
| is
| lock
| long
| new
| null
| object
| operator
| out
| params
| private
| protected
| readonly
| ref
| sbyte
| sealed
| short
| sizeof
| stackalloc
| struct
| switch
| this
| throw
| true
| try
| typeof
| uint
| ulong
| unchecked
| unsafe
| ushort
| using
| virtual
)(\b)",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
#endregion
return regex.Replace(strC, "$1_$2$3");
}
private string CorrectEvent(string strC, string strName)
{
Regex regex = new Regex(
@"([^\w_])" + strName + @"(\s*)\(",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
return regex.Replace(strC, "$1public override void " + strName + "$2(");
}
private string CorrectEvents(string strC)
{
XmlNode words = xml.SelectSingleNode("//Words[@name='Appendix B. Events']");
foreach (XmlNode xmlNode in words.SelectNodes(".//Word"))
{
string strName = xmlNode.Attributes["name"].InnerText;
strC = CorrectEvent(strC, strName);
}
return strC;
}
// old vector parser
// <([^<>,;]*),([^<>,;]*),([^<>,;]*)>
private string CorrectVector(string strC)
{
Regex regex = new Regex(@"
<
(?<vector_x>
(?>
[^=(),>]+
| \( (?<nr>)
| \) (?<-nr>)
| ,
)*
(?(nr)(?!))
)
,
(?<vector_y>
(?>
[^=(),>]+
| \( (?<nr>)
| \) (?<-nr>)
| ,
)*
(?(nr)(?!))
)
,
(?<vector_z>
(?>
[^=()>]+
| \( (?<nr>)
| \) (?<-nr>)
| ,
)*
(?(nr)(?!))
)
>
",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
return regex.Replace(strC, "new vector(${vector_x},${vector_y},${vector_z})");
}
// old rotation
// <([^<>,;]*),([^<>,;]*),([^<>,;]*),([^<>,;]*)>
private string CorrectRotation(string strC)
{
Regex regex = new Regex(@"
<
(?<rotation_x>
(?>
[^=(),>]+
| \( (?<nr>)
| \) (?<-nr>)
| ,
)*
(?(nr)(?!))
)
,
(?<rotation_y>
(?>
[^=(),>]+
| \( (?<nr>)
| \) (?<-nr>)
| ,
)*
(?(nr)(?!))
)
,
(?<rotation_z>
(?>
[^=(),>]+
| \( (?<nr>)
| \) (?<-nr>)
| ,
)*
(?(nr)(?!))
)
,
(?<rotation_s>
(?>
[^=()>]+
| \( (?<nr>)
| \) (?<-nr>)
| ,
)*
(?(nr)(?!))
)
>
",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
return regex.Replace(strC, "new rotation(${rotation_x},${rotation_y},${rotation_z},${rotation_s})");
}
private string CorrectQuaternion(string strC)
{
Regex regex = new Regex(
@"(\b)quaternion(\b)",
RegexOptions.Compiled
| RegexOptions.IgnorePatternWhitespace
);
return regex.Replace(strC, "$1rotation$2");
}
private string CorrectListsEvaluator(Match m)
{
string strValue = m.Value;
return "new list(new object[] {" + CorrectLists(strValue.Substring(1, strValue.Length - 2)) + "})";
}
private string CorrectLists(string strC)
{
Regex regex = new Regex(
@"
\[
(?>
[^\[\]]+
| \[ (?<number>)
| \] (?<-number>)
)*
(?(number)(?!))
\]
",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled);
return regex.Replace(strC, new MatchEvaluator(CorrectListsEvaluator));
}
// changed 16 aug 2007
private string CorrectJump(string strC)
{
// jump -> goto
Regex regex = new Regex(
@"(\b)jump(\s+)([^;]*;)",
RegexOptions.Compiled
| RegexOptions.IgnorePatternWhitespace
);
strC = regex.Replace(strC, "$1goto$2_$3");
// @label; -> label:;
regex = new Regex(
@"@\s*([a-z0-9_]+)\s*;",
RegexOptions.Compiled
| RegexOptions.IgnoreCase
| RegexOptions.IgnorePatternWhitespace
);
return regex.Replace(strC, "_$1:;");
}
private string RemoveQuotedStrings(string strC, out List<string> h)
{
h = new List<string>();
StringBuilder sb = new StringBuilder();
StringBuilder QuotedString = null;
for (int intI = 0; intI < strC.Length; intI++)
{
char chrC = strC[intI];
if (chrC == '"')
{
if (QuotedString != null)
{
// end of a quoted string
sb.Append('"');
sb.Append(h.Count.ToString());
sb.Append('"');
h.Add(QuotedString.ToString());
QuotedString = null;
continue;
}
else
{
if (chrC == '"')
{
// start of a new quoted string
QuotedString = new StringBuilder();
continue;
}
// it was just a newline char, and not in a string
}
}
if (QuotedString == null)
sb.Append(chrC);
else
{
if (chrC == '\n')
{
QuotedString.Append('\\');
chrC = 'n';
}
if (chrC != '\\')
{
QuotedString.Append(chrC);
}
else // it is a backslash
{
intI++;
chrC = strC[intI];
if (chrC == 't') // tabs are 4 spaces in SL world!!
{
QuotedString.Append(" ");
}
else // nope, it is no tab, just output it all
{
QuotedString.Append('\\');
QuotedString.Append(chrC);
}
}
}
}
return sb.ToString();
}
private string InsertQuotedStrings(string strC, List<string> h)
{
StringBuilder sb = new StringBuilder();
StringBuilder QuotedString = null;
for (int intI = 0; intI < strC.Length; intI++)
{
char chrC = strC[intI];
if (chrC == '"')
{
if (QuotedString == null)
{
QuotedString = new StringBuilder();
}
else
{
sb.Append('"');
int intNumber;
// State("default") is not a number, result of 'CorrectStates'
if (int.TryParse(QuotedString.ToString(), out intNumber))
sb.Append(h[intNumber]);
else
sb.Append(QuotedString.ToString());
sb.Append('"');
QuotedString = null;
}
continue;
}
if (QuotedString == null)
sb.Append(chrC);
else
QuotedString.Append(chrC);
}
return sb.ToString();
}
private string MakeGlobalAndLocal(string strC)
{
Regex regexDefault = new Regex(@"^\s*(default)\W",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Multiline
| RegexOptions.Compiled);
Match matchDefault = regexDefault.Match(strC);
string strGlobal;
int intDefaultIndex;
if (matchDefault.Groups.Count == 2)
{
States.Add("default");
intDefaultIndex = matchDefault.Groups[1].Index;
strGlobal = CorrectGlobal(strC.Substring(0, intDefaultIndex));
}
else
{
intDefaultIndex = 0;
strGlobal = "";
}
return "class GlobalClass : SecondLife\n{\n" + strGlobal + "}\n" + strC.Substring(intDefaultIndex);
}
private string Capitalize(string strC, string strName)
{
Regex regex = new Regex(@"(\W)"+strName+@"(\W)",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.Multiline
| RegexOptions.Compiled);
string strCap = strName[0].ToString().ToUpper() + strName.Substring(1);
return regex.Replace(strC, "$1"+strCap+"$2");
}
private string RemoveSingleQuotes(string strC)
{
if (Properties.Settings.Default.SingleQuote)
return strC.Replace("'", "");
else
return strC;
}
/// <summary>
/// This Class translates LSL script into CSharp code
/// </summary>
/// <param name="strLSLCode">LSL scripting code</param>
/// <returns>CSHarp code</returns>
public string Parse(string strLSLCode)
{
List<string> quotedStrings;
string strGlobalClass = "GlobalClass";
string strC = strLSLCode;
strC = RemoveComments(strC);
strC = RemoveQuotedStrings(strC, out quotedStrings);
strC = RemoveSingleQuotes(strC);
strC = PreCorrectReservedWords(strC); // Experimental
strC = MakeGlobalAndLocal(strC);
strC = CorrectJump(strC);
strC = CorrectEvents(strC);
strC = Capitalize(strC, "float");
strC = Capitalize(strC, "string"); // llList2string is also translated
strC = CorrectStates(strC, strGlobalClass);
strC = CorrectReservedWords(strC); // Experimental
strC = CorrectRotation(strC);
strC = CorrectQuaternion(strC);
strC = CorrectVector(strC);
strC = CorrectLists(strC);
strC = InsertQuotedStrings(strC, quotedStrings);
return strC;
}
}
}

70
Helpers/Measure.cs Normal file
View file

@ -0,0 +1,70 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Drawing;
namespace LSLEditor.Helpers
{
class Measure
{
public static RectangleF MeasureDisplayString(System.Windows.Forms.Control control, string text, Font font)
{
Graphics graphics = control.CreateGraphics();
RectangleF rect = MeasureDisplayString(graphics, text, font);
graphics.Dispose();
return rect;
}
public static RectangleF MeasureDisplayString(Graphics graphics, string text, Font font)
{
StringFormat format = new StringFormat();
RectangleF rect = new RectangleF(0, 0, 4096, 4096);
CharacterRange[] ranges = { new CharacterRange(0, text.Length) };
Region[] regions = new Region[1];
format.SetMeasurableCharacterRanges(ranges);
regions = graphics.MeasureCharacterRanges(text, font, rect, format);
return regions[0].GetBounds(graphics);
}
}
}

66
Helpers/OopsFormatter.cs Normal file
View file

@ -0,0 +1,66 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.IO;
using System.Text;
namespace LSLEditor
{
class OopsFormatter
{
public static string ApplyFormatting(string strInput)
{
strInput = strInput.Replace("SecondLifeHost.", "");
strInput = strInput.Replace("GlobalClass.", "");
strInput = strInput.Replace("State_", "");
strInput = strInput.Replace("LSLEditor.", "");
strInput = strInput.Replace("SecondLife.", "");
strInput = strInput.Replace("String", "string");
strInput = strInput.Replace("Float", "float");
strInput = strInput.Replace(Properties.Settings.Default.OopsRemove, "");
return strInput;
}
}
}

703
Helpers/PrinterHelper.cs Normal file
View file

@ -0,0 +1,703 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;
using System.Windows.Forms;
namespace LSLEditor.Helpers
{
/// <summary>
/// Data Grid View Printer. Print functions for a datagridview, since MS
/// didn't see fit to do it.
/// </summary>
class PrinterHelper
{
//---------------------------------------------------------------------
// global variables
//---------------------------------------------------------------------
#region global variables
// the data grid view we're printing
EditForm editForm = null;
int intCharFrom;
int intCharTo;
int intCharPrint;
// print document
PrintDocument printDoc = null;
// print status items
int fromPage = 0;
int toPage = -1;
// page formatting options
int pageHeight = 0;
int pageWidth = 0;
int printWidth = 0;
int CurrentPage = 0;
PrintRange printRange;
// calculated values
private float footerHeight = 0;
private float pagenumberHeight = 0;
#endregion
//---------------------------------------------------------------------
// properties - settable by user
//---------------------------------------------------------------------
#region properties
// Title
#region title properties
/// <summary>
/// Title for this report. Default is empty.
/// </summary>
private String title;
public String Title
{
get { return title; }
set { title = value; printDoc.DocumentName = title; }
}
/// <summary>
/// Font for the title. Default is Tahoma, 18pt.
/// </summary>
private Font titlefont;
public Font TitleFont
{
get { return titlefont; }
set { titlefont = value; }
}
/// <summary>
/// Foreground color for the title. Default is Black
/// </summary>
private Color titlecolor;
public Color TitleColor
{
get { return titlecolor; }
set { titlecolor = value; }
}
/// <summary>
/// Allow the user to override the title string alignment. Default value is
/// Alignment - Near;
/// </summary>
private StringAlignment titlealignment;
public StringAlignment TitleAlignment
{
get { return titlealignment; }
set { titlealignment = value; }
}
/// <summary>
/// Allow the user to override the title string format flags. Default values
/// are: FormatFlags - NoWrap, LineLimit, NoClip
/// </summary>
private StringFormatFlags titleformatflags;
public StringFormatFlags TitleFormatFlags
{
get { return titleformatflags; }
set { titleformatflags = value; }
}
#endregion
// SubTitle
#region subtitle properties
/// <summary>
/// SubTitle for this report. Default is empty.
/// </summary>
private String subtitle;
public String SubTitle
{
get { return subtitle; }
set { subtitle = value; }
}
/// <summary>
/// Font for the subtitle. Default is Tahoma, 12pt.
/// </summary>
private Font subtitlefont;
public Font SubTitleFont
{
get { return subtitlefont; }
set { subtitlefont = value; }
}
/// <summary>
/// Foreground color for the subtitle. Default is Black
/// </summary>
private Color subtitlecolor;
public Color SubTitleColor
{
get { return subtitlecolor; }
set { subtitlecolor = value; }
}
/// <summary>
/// Allow the user to override the subtitle string alignment. Default value is
/// Alignment - Near;
/// </summary>
private StringAlignment subtitlealignment;
public StringAlignment SubTitleAlignment
{
get { return subtitlealignment; }
set { subtitlealignment = value; }
}
/// <summary>
/// Allow the user to override the subtitle string format flags. Default values
/// are: FormatFlags - NoWrap, LineLimit, NoClip
/// </summary>
private StringFormatFlags subtitleformatflags;
public StringFormatFlags SubTitleFormatFlags
{
get { return subtitleformatflags; }
set { subtitleformatflags = value; }
}
#endregion
// Footer
#region footer properties
/// <summary>
/// footer for this report. Default is empty.
/// </summary>
private String footer;
public String Footer
{
get { return footer; }
set { footer = value; }
}
/// <summary>
/// Font for the footer. Default is Tahoma, 10pt.
/// </summary>
private Font footerfont;
public Font FooterFont
{
get { return footerfont; }
set { footerfont = value; }
}
/// <summary>
/// Foreground color for the footer. Default is Black
/// </summary>
private Color footercolor;
public Color FooterColor
{
get { return footercolor; }
set { footercolor = value; }
}
/// <summary>
/// Allow the user to override the footer string alignment. Default value is
/// Alignment - Center;
/// </summary>
private StringAlignment footeralignment;
public StringAlignment FooterAlignment
{
get { return footeralignment; }
set { footeralignment = value; }
}
/// <summary>
/// Allow the user to override the footer string format flags. Default values
/// are: FormatFlags - NoWrap, LineLimit, NoClip
/// </summary>
private StringFormatFlags footerformatflags;
public StringFormatFlags FooterFormatFlags
{
get { return footerformatflags; }
set { footerformatflags = value; }
}
private float footerspacing;
public float FooterSpacing
{
get { return footerspacing; }
set { footerspacing = value; }
}
#endregion
// Page Numbering
#region page number properties
/// <summary>
/// Include page number in the printout. Default is true.
/// </summary>
private bool pageno = true;
public bool PageNumbers
{
get { return pageno; }
set { pageno = value; }
}
/// <summary>
/// Font for the page number, Default is Tahoma, 8pt.
/// </summary>
private Font pagenofont;
public Font PageNumberFont
{
get { return pagenofont; }
set { pagenofont = value; }
}
/// <summary>
/// Text color (foreground) for the page number. Default is Black
/// </summary>
private Color pagenocolor;
public Color PageNumberColor
{
get { return pagenocolor; }
set { pagenocolor = value; }
}
/// <summary>
/// Allow the user to override the page number string alignment. Default value is
/// Alignment - Near;
/// </summary>
private StringAlignment pagenumberalignment;
public StringAlignment PaageNumberAlignment
{
get { return pagenumberalignment; }
set { pagenumberalignment = value; }
}
/// <summary>
/// Allow the user to override the pagenumber string format flags. Default values
/// are: FormatFlags - NoWrap, LineLimit, NoClip
/// </summary>
private StringFormatFlags pagenumberformatflags;
public StringFormatFlags PageNumberFormatFlags
{
get { return pagenumberformatflags; }
set { pagenumberformatflags = value; }
}
/// <summary>
/// Allow the user to select whether to have the page number at the top or bottom
/// of the page. Default is false: page numbers on the bottom of the page
/// </summary>
private bool pagenumberontop = false;
public bool PageNumberInHeader
{
get { return pagenumberontop; }
set { pagenumberontop = value; }
}
/// <summary>
/// Should the page number be printed on a separate line, or printed on the
/// same line as the header / footer? Default is false;
/// </summary>
private bool pagenumberonseparateline = false;
public bool PaageNumberOnSeparateLine
{
get { return pagenumberonseparateline; }
set { pagenumberonseparateline = value; }
}
#endregion
// Page Level Properties
#region page level properties
/// <summary>
/// Page margins override. Default is (60, 60, 60, 60)
/// </summary>
private Margins printmargins;
public Margins PrintMargins
{
get { return printmargins; }
set { printmargins = value; }
}
#endregion
#endregion
/// <summary>
/// Constructor for PrinterHelper
/// </summary>
public PrinterHelper(PageSetupDialog pageSetupDialog)
{
// create print document
printDoc = new PrintDocument();
printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
if (pageSetupDialog.PrinterSettings != null)
printDoc.PrinterSettings = pageSetupDialog.PrinterSettings;
if (pageSetupDialog.PageSettings != null)
printDoc.DefaultPageSettings = pageSetupDialog.PageSettings;
else
printDoc.DefaultPageSettings.Margins = new Margins(60, 80, 40, 40);
printmargins = printDoc.DefaultPageSettings.Margins;
// set default fonts
pagenofont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
pagenocolor = Color.Black;
titlefont = new Font("Tahoma", 8, FontStyle.Bold, GraphicsUnit.Point);
titlecolor = Color.Black;
subtitlefont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
subtitlecolor = Color.Black;
footerfont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
footercolor = Color.Black;
// set default string formats
titlealignment = StringAlignment.Near;
titleformatflags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
subtitlealignment = StringAlignment.Near;
subtitleformatflags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
footeralignment = StringAlignment.Near;
footerformatflags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
pagenumberalignment = StringAlignment.Center;
pagenumberformatflags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
}
/// <summary>
/// Start the printing process, print to a printer.
/// </summary>
/// <param name="editForm">The EditForm to print</param>
/// NOTE: Any changes to this method also need to be done in PrintPreviewEditForm
public void PrintEditForm(EditForm editForm)
{
// save the datagridview we're printing
this.editForm = editForm;
this.intCharFrom = 0;
this.intCharPrint = 0;
this.intCharTo = editForm.TextBox.Text.Length;
// create new print dialog
PrintDialog pd = new PrintDialog();
pd.Document = printDoc;
//printDoc.DefaultPageSettings.Margins = printmargins;
pd.AllowSelection = true;
pd.AllowSomePages = false;
pd.AllowCurrentPage = false;
pd.AllowPrintToFile = false;
// show print dialog
if (DialogResult.OK == pd.ShowDialog())
{
SetupPrint(pd);
printDoc.Print();
}
}
/// <summary>
/// Start the printing process, print to a print preview dialog
/// </summary>
/// <param name="editForm">The EditForm to print</param>
/// NOTE: Any changes to this method also need to be done in PrintDataGridView
public void PrintPreviewEditForm(EditForm editForm)
{
// save the datagridview we're printing
this.editForm = editForm;
this.intCharFrom = 0;
this.intCharTo = editForm.TextBox.Text.Length;
// create new print dialog and set options
PrintDialog pd = new PrintDialog();
pd.Document = printDoc;
//printDoc.DefaultPageSettings.Margins = printmargins;
pd.AllowSelection = true;
pd.AllowSomePages = false;
pd.AllowCurrentPage = false;
pd.AllowPrintToFile = false;
// show print dialog
if (DialogResult.OK == pd.ShowDialog())
{
SetupPrint(pd);
PrintPreviewDialog ppdialog = new PrintPreviewDialog();
ppdialog.Document = printDoc;
ppdialog.ShowDialog();
}
}
/// <summary>
/// Set up the print job. Save information from print dialog
/// and print document for easy access. Also sets up the rows
/// and columns that will be printed.
/// </summary>
/// <param name="pd">The print dialog the user just filled out</param>
void SetupPrint(PrintDialog pd)
{
//-----------------------------------------------------------------
// save data from print dialog and document
//-----------------------------------------------------------------
// check to see if we're doing landscape printing
if (printDoc.DefaultPageSettings.Landscape)
{
// landscape: switch width and height
pageHeight = printDoc.DefaultPageSettings.PaperSize.Width;
pageWidth = printDoc.DefaultPageSettings.PaperSize.Height;
}
else
{
// portrait: keep width and height as expected
pageHeight = printDoc.DefaultPageSettings.PaperSize.Height;
pageWidth = printDoc.DefaultPageSettings.PaperSize.Width;
}
// save printer margins and calc print width
printmargins = printDoc.DefaultPageSettings.Margins;
printWidth = pageWidth - printmargins.Left - printmargins.Right;
// save print range
printRange = pd.PrinterSettings.PrintRange;
// pages to print handles "some pages" option
if (PrintRange.SomePages == printRange)
{
// set limits to only print some pages
fromPage = pd.PrinterSettings.FromPage;
toPage = pd.PrinterSettings.ToPage;
}
else
{
// set extremes so that we'll print all pages
fromPage = 0;
toPage = 2147483647;
}
//-----------------------------------------------------------------
// set up the pages to print
//-----------------------------------------------------------------
// pages (handles "selection" and "current page" options
if (PrintRange.Selection == printRange)
{
intCharPrint = this.editForm.TextBox.SelectionStart;
intCharFrom = intCharPrint;
intCharTo = intCharFrom + this.editForm.TextBox.SelectionLength;
}
else if (PrintRange.CurrentPage == printRange)
{
}
// this is the default for print all
else
{
intCharPrint = 0;
intCharFrom = intCharPrint;
intCharTo = this.editForm.TextBox.Text.Length;
}
}
/// <summary>
/// Centralize the string format settings. Does the work of checking for user
/// overrides, and if they're not present, setting the cell alignment to match
/// (somewhat) the source control's string alignment.
/// </summary>
/// <param name="alignment">String alignment</param>
/// <param name="flags">String format flags</param>
/// <param name="controlstyle">DataGridView style to apply (if available)</param>
/// <param name="overrideformat">True if user overrode alignment or flags</param>
/// <returns></returns>
private static StringFormat managestringformat(StringAlignment alignment, StringFormatFlags flags)
{
// start with the provided
StringFormat format = new StringFormat();
format.Trimming = StringTrimming.Word;
format.Alignment = alignment;
format.FormatFlags = flags;
return format;
}
/// <summary>
/// PrintPage event handler. This routine prints one page. It will
/// skip non-printable pages if the user selected the "some pages" option
/// on the print dialog.
/// </summary>
/// <param name="sender">default object from windows</param>
/// <param name="e">Event info from Windows about the printing</param>
private void printDoc_PrintPage(object sender, PrintPageEventArgs e)
{
// adjust printing region, make space for headers and footers
Rectangle rect = new Rectangle(
e.MarginBounds.Left,
e.MarginBounds.Top + e.MarginBounds.Top,
e.MarginBounds.Width,
e.MarginBounds.Height - e.MarginBounds.Top - e.MarginBounds.Top);
PrintPageEventArgs ee = new PrintPageEventArgs(e.Graphics, rect, e.PageBounds, e.PageSettings);
// Print the content of RichTextBox. Store the last character printed.
intCharFrom = editForm.TextBox.Print(intCharFrom, intCharTo, ee);
// increment page number & check page range
CurrentPage++;
//-----------------------------------------------------------------
// print headers
//-----------------------------------------------------------------
// reset printpos as it may have changed during the 'skip pages' routine just above.
float printpos = printmargins.Top;
// print page number if user selected it
if (pagenumberontop)
{
// if we have a page number to print
if (pageno)
{
// ... then print it
printsection(e.Graphics, ref printpos, "Page " + CurrentPage.ToString(CultureInfo.CurrentCulture),
pagenofont, pagenocolor, pagenumberalignment, pagenumberformatflags);
// if the page number is not on a separate line, don't "use up" it's vertical space
if (!pagenumberonseparateline)
printpos -= pagenumberHeight;
}
}
// print title if provided
if (!String.IsNullOrEmpty(title))
printsection(e.Graphics, ref printpos, title, titlefont,
titlecolor, titlealignment, titleformatflags);
// print subtitle if provided
if (!String.IsNullOrEmpty(subtitle))
printsection(e.Graphics, ref printpos, subtitle, subtitlefont,
subtitlecolor, subtitlealignment, subtitleformatflags);
//-----------------------------------------------------------------
// print footer
//-----------------------------------------------------------------
printfooter(e.Graphics, ref printpos);
// Check for more pages
if (intCharFrom < intCharTo)
e.HasMorePages = true;
else
{
intCharFrom = intCharPrint; // reset
CurrentPage = 0;
e.HasMorePages = false;
}
}
/// <summary>
/// Print a header or footer section. Used for page numbers and titles
/// </summary>
/// <param name="g">Graphic context to print in</param>
/// <param name="pos">Track vertical space used; 'y' location</param>
/// <param name="text">String to print</param>
/// <param name="font">Font to use for printing</param>
/// <param name="color">Color to print in</param>
/// <param name="alignment">Alignment - print to left, center or right</param>
/// <param name="flags">String format flags</param>
/// <param name="useroverride">True if the user overrode the alignment or flags</param>
private void printsection(Graphics g, ref float pos, string text,
Font font, Color color, StringAlignment alignment, StringFormatFlags flags)
{
// string formatting setup
StringFormat printformat = managestringformat(alignment, flags);
// measure string
SizeF printsize = g.MeasureString(text, font, printWidth, printformat);
// build area to print within
RectangleF printarea = new RectangleF((float)printmargins.Left, pos, (float)printWidth,
printsize.Height);
// do the actual print
g.DrawString(text, font, new SolidBrush(color), printarea, printformat);
// track "used" vertical space
pos += printsize.Height;
}
/// <summary>
/// Print the footer. This handles the footer spacing, and printing the page number
/// at the bottom of the page (if the page number is not in the header).
/// </summary>
/// <param name="g">Graphic context to print in</param>
/// <param name="pos">Track vertical space used; 'y' location</param>
private void printfooter(Graphics g, ref float pos)
{
// print last footer. Note: need to force printpos to the bottom of the page
// as we may have run out of data anywhere on the page
pos = pageHeight - footerHeight - printmargins.Top - printmargins.Bottom;
// add spacing
pos += footerspacing;
// print the footer
printsection(g, ref pos, footer, footerfont,
footercolor, footeralignment, footerformatflags);
// print the page number if it's on the bottom.
if (!pagenumberontop)
{
if (pageno)
{
pagenumberHeight = g.MeasureString("M", pagenofont).Height;
// if the pageno is not on a separate line, push the print location up by its height.
if (!pagenumberonseparateline)
pos = pos - pagenumberHeight;
// print the page number
printsection(g, ref pos, "Page " + CurrentPage.ToString(CultureInfo.CurrentCulture),
pagenofont, pagenocolor, pagenumberalignment, pagenumberformatflags);
}
}
}
}
}

273
Helpers/SendMyKeys.cs Normal file
View file

@ -0,0 +1,273 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace NativeHelper
{
public class NativeWIN32
{
public const ushort KEYEVENTF_KEYUP = 0x0002;
public struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public long time;
public uint dwExtraInfo;
}
[StructLayout(LayoutKind.Explicit, Size = 28)]
public struct INPUT
{
[FieldOffset(0)]
public uint type;
[FieldOffset(4)]
public KEYBDINPUT ki;
}
[DllImport("user32.dll")]
public static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
public class SendMyKeys
{
public static void PasteTextToApp(string strText,string strAppName, string strTitle)
{
foreach (Process p in Process.GetProcessesByName(strAppName))
{
if(strTitle!=null)
if (p.MainWindowTitle.IndexOf(strTitle) < 0)
continue;
NativeWIN32.SetForegroundWindow(p.MainWindowHandle);
Thread.Sleep(5000);
SendMyKeys.SendString(strText);
return;
}
}
public static void ClipBoardToApp(string strAppName, string strTitle)
{
foreach (Process p in Process.GetProcessesByName(strAppName))
{
if (strTitle != null)
if (p.MainWindowTitle.IndexOf(strTitle) < 0)
continue;
NativeWIN32.SetForegroundWindow(p.MainWindowHandle);
Thread.Sleep(1000);
SendMyKeys.SendChar((ushort)Keys.V,false,true);
return;
}
}
public static void SendChar(ushort wVk, bool ShiftKey, bool ControlKey)
{
uint uintReturn;
NativeWIN32.INPUT structInput = new NativeWIN32.INPUT();
structInput.type = (uint)1;
structInput.ki.wScan = 0;
structInput.ki.time = 0;
structInput.ki.dwFlags = 0;
structInput.ki.dwExtraInfo = 0;
if (ControlKey)
{
structInput.ki.wVk = (ushort)Keys.ControlKey;
uintReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));
}
if (ShiftKey)
{
structInput.ki.wVk = (ushort)Keys.ShiftKey;
uintReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));
}
structInput.ki.wVk = wVk;
uintReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));
structInput.ki.dwFlags = NativeWIN32.KEYEVENTF_KEYUP;
structInput.ki.wVk = wVk;
uintReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));
if (ShiftKey)
{
structInput.ki.dwFlags = NativeWIN32.KEYEVENTF_KEYUP;
structInput.ki.wVk = (ushort)Keys.ShiftKey;
uintReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));
}
if (ControlKey)
{
structInput.ki.dwFlags = NativeWIN32.KEYEVENTF_KEYUP;
structInput.ki.wVk = (ushort)Keys.ControlKey;
uintReturn = NativeWIN32.SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));
}
}
public static void SendString(string s)
{
ushort wVk;
bool ShiftKey;
foreach (Char c in s.ToCharArray())
{
if (Char.IsUpper(c))
ShiftKey = true;
else
ShiftKey = false;
wVk = (ushort)Char.ToUpper(c);
string special = ")!@#$%^&*(";
int intDigit = special.IndexOf(c);
if (intDigit >= 0)
{
ShiftKey = true;
wVk = (ushort)('0' + intDigit);
}
else
{
switch (c)
{
case ':':
ShiftKey = true;
wVk = (ushort)Keys.Oem1;
break;
case ';':
wVk = (ushort)Keys.Oem1;
break;
case '-':
wVk = (ushort)Keys.OemMinus;
break;
case '_':
ShiftKey = true;
wVk = (ushort)Keys.OemMinus;
break;
case '+':
ShiftKey = true;
wVk = (ushort)Keys.Oemplus;
break;
case '=':
wVk = (ushort)Keys.Oemplus;
break;
case '/':
wVk = (ushort)Keys.Oem2;
break;
case '?':
ShiftKey = true;
wVk = (ushort)Keys.OemQuestion;
break;
case '.':
wVk = (ushort)Keys.OemPeriod;
break;
case '>':
ShiftKey = true;
wVk = (ushort)Keys.OemPeriod;
break;
case ',':
wVk = (ushort)Keys.Oemcomma;
break;
case '<':
ShiftKey = true;
wVk = (ushort)Keys.Oemcomma;
break;
case '`':
wVk = (ushort)Keys.Oemtilde;
break;
case '~':
ShiftKey = true;
wVk = (ushort)Keys.Oemtilde;
break;
case '|':
ShiftKey = true;
wVk = (ushort)Keys.Oem5;
break;
case '\\':
wVk = (ushort)Keys.Oem5;
break;
case '[':
wVk = (ushort)Keys.OemOpenBrackets;
break;
case '{':
ShiftKey = true;
wVk = (ushort)Keys.OemOpenBrackets;
break;
case ']':
wVk = (ushort)Keys.Oem6;
break;
case '}':
ShiftKey = true;
wVk = (ushort)Keys.Oem6;
break;
case '\'':
wVk = (ushort)Keys.Oem7;
break;
case '"':
ShiftKey = true;
wVk = (ushort)Keys.Oem7;
break;
default:
break;
}
}
SendChar(wVk, ShiftKey, false);
}
}
}
}

71
Helpers/Settings.cs Normal file
View file

@ -0,0 +1,71 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
namespace LSLEditor.Properties {
// This class allows you to handle specific events on the settings class:
// The SettingChanging event is raised before a setting's value is changed.
// The PropertyChanged event is raised after a setting's value is changed.
// The SettingsLoaded event is raised after the setting values are loaded.
// The SettingsSaving event is raised before the setting values are saved.
internal sealed partial class Settings {
public Settings() {
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
}
private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
// Add code to handle the SettingChangingEvent event here.
}
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
// Add code to handle the SettingsSaving event here.
}
}
}

355
Helpers/SmtpClient.cs Normal file
View file

@ -0,0 +1,355 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Collections;
namespace LSLEditor
{
public class MailAttachment
{
public string Filename;
public MailAttachment(string strAttachmentFile)
{
this.Filename = strAttachmentFile;
}
}
public class MailMessage
{
public string Body;
public string From;
public string To;
public string Cc;
public string Bcc;
public string Subject;
public Hashtable Headers;
public ArrayList Attachments;
public MailMessage()
{
this.Headers = new Hashtable();
this.Attachments = new ArrayList();
}
}
/// <summary>
/// provides methods to send email via smtp direct to mail server
/// http://www.ietf.org/rfc/rfc0821.txt
/// </summary>
public class SmtpClient
{
/// <summary>
/// Get / Set the name of the SMTP mail server
/// </summary>
public string SmtpServer;
private enum SMTPResponse: int
{
CONNECT_SUCCESS = 220,
GENERIC_SUCCESS = 250,
DATA_SUCCESS = 354,
QUIT_SUCCESS = 221,
AUTH_SUCCESS = 334,
AUTH_GRANTED = 235
}
public string Send(MailMessage message)
{
string strResponse;
byte[] data;
IPHostEntry IPhst;
try
{
IPhst = Dns.GetHostEntry(SmtpServer);
}
catch (Exception exception)
{
return "Email:Error on "+exception.Message;
}
IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
Socket s= new Socket(endPt.AddressFamily, SocketType.Stream,ProtocolType.Tcp);
s.Connect(endPt);
if(!Check_Response(s, SMTPResponse.CONNECT_SUCCESS, out strResponse))
{
s.Close();
return "Email:Error on connection (" + strResponse + ")";
}
Senddata(s, string.Format("HELO {0}\r\n", Dns.GetHostName() ));
if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS, out strResponse))
{
s.Close();
return "Email:Error on HELO (" + strResponse + ")";
}
// SMTP Authentication
if (Properties.Settings.Default.SmtpUserid != "")
{
if (Properties.Settings.Default.SmtpAuth == "PLAIN")
{
Senddata(s, "AUTH PLAIN\r\n");
if (!Check_Response(s, SMTPResponse.AUTH_SUCCESS, out strResponse))
{
s.Close();
return "Email: Error on AUTH PLAIN (" + strResponse + ")";
}
data = Encoding.ASCII.GetBytes(string.Format("\0{0}\0{1}",
Properties.Settings.Default.SmtpUserid,
Properties.Settings.Default.SmtpPassword));
Senddata(s, string.Format("{0}\r\n",Convert.ToBase64String(data)));
if (!Check_Response(s, SMTPResponse.AUTH_GRANTED, out strResponse))
{
s.Close();
return "Email: AUTH PLAIN not granted (" + strResponse + ")";
}
}
if (Properties.Settings.Default.SmtpAuth == "LOGIN")
{
Senddata(s, "AUTH LOGIN\r\n");
if (!Check_Response(s, SMTPResponse.AUTH_SUCCESS, out strResponse))
{
s.Close();
return "Email: Error on AUTH LOGIN (" + strResponse + ")";
}
data = Encoding.ASCII.GetBytes(Properties.Settings.Default.SmtpUserid);
Senddata(s, string.Format("{0}\r\n", Convert.ToBase64String(data)));
if (!Check_Response(s, SMTPResponse.AUTH_SUCCESS, out strResponse))
{
s.Close();
return "Email: AUTH LOGIN userid error (" + strResponse + ")";
}
data = Encoding.ASCII.GetBytes(Properties.Settings.Default.SmtpPassword);
Senddata(s, string.Format("{0}\r\n", Convert.ToBase64String(data)));
if (!Check_Response(s, SMTPResponse.AUTH_GRANTED, out strResponse))
{
s.Close();
return "Email: AUTH LOGIN not granted (" + strResponse + ")";
}
}
if (Properties.Settings.Default.SmtpAuth == "CRAM-MD5")
{
s.Close();
return "Email: LSLEditor Not Implemented CRAM-MD5";
}
if (Properties.Settings.Default.SmtpAuth == "DIGEST-MD5")
{
s.Close();
return "Email: LSLEditor Not Implemented DIGEST-MD5";
}
if (Properties.Settings.Default.SmtpAuth == "EXTERNAL")
{
s.Close();
return "Email: LSLEditor Not Implemented EXTERNAL";
}
if (Properties.Settings.Default.SmtpAuth == "ANONYMOUS")
{
s.Close();
return "Email: LSLEditor Not Implemented ANONYMOUS";
}
}
Senddata(s, string.Format("MAIL From: {0}\r\n", message.From ));
if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS, out strResponse))
{
s.Close();
return "Email: Error on MAIL From (" + strResponse + ")";
}
string _To = message.To;
string[] Tos= _To.Split(new char[] {';'});
foreach (string To in Tos)
{
Senddata(s, string.Format("RCPT TO: {0}\r\n", To));
if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS, out strResponse))
{
s.Close();
return "Email: Error on RCPT TO (" + strResponse + ")";
}
}
if(message.Cc!=null)
{
Tos= message.Cc.Split(new char[] {';'});
foreach (string To in Tos)
{
Senddata(s, string.Format("RCPT TO: {0}\r\n", To));
if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS, out strResponse))
{
s.Close();
return "Email: Error on (CC) RCPT TO (" + strResponse + ")";
}
}
}
StringBuilder Header=new StringBuilder();
Header.Append("From: " + message.From + "\r\n");
Tos= message.To.Split(new char[] {';'});
Header.Append("To: ");
for( int i=0; i< Tos.Length; i++)
{
Header.Append( i > 0 ? "," : "" );
Header.Append(Tos[i]);
}
Header.Append("\r\n");
if(message.Cc!=null)
{
Tos= message.Cc.Split(new char[] {';'});
Header.Append("Cc: ");
for( int i=0; i< Tos.Length; i++)
{
Header.Append( i > 0 ? "," : "" );
Header.Append(Tos[i]);
}
Header.Append("\r\n");
}
Header.Append("Date: " + DateTime.Now.ToString("R" ) + "\r\n");
Header.Append("Subject: " + message.Subject+ "\r\n");
Header.Append("X-Mailer: SMTPClient v2.36 (LSL-Editor)\r\n" );
// escape . on newline
string MsgBody = message.Body.Replace("\n.","\n..");
if(!MsgBody.EndsWith("\r\n"))
MsgBody+="\r\n";
if(message.Attachments.Count>0)
{
Header.Append( "MIME-Version: 1.0\r\n" );
Header.Append( "Content-Type: multipart/mixed; boundary=unique-boundary-1\r\n" );
Header.Append("\r\n");
Header.Append( "This is a multi-part message in MIME format.\r\n" );
StringBuilder sb = new StringBuilder();
sb.Append("--unique-boundary-1\r\n");
sb.Append("Content-Type: text/plain\r\n");
sb.Append("Content-Transfer-Encoding: 7Bit\r\n");
sb.Append("\r\n");
sb.Append(MsgBody + "\r\n");
sb.Append("\r\n");
foreach(object o in message.Attachments)
{
MailAttachment a = o as MailAttachment;
byte[] binaryData;
if(a!=null)
{
FileInfo f = new FileInfo(a.Filename);
sb.Append("--unique-boundary-1\r\n");
sb.Append("Content-Type: application/octet-stream; file=" + f.Name + "\r\n");
sb.Append("Content-Transfer-Encoding: base64\r\n");
sb.Append("Content-Disposition: attachment; filename=" + f.Name + "\r\n");
sb.Append("\r\n");
FileStream fs = f.OpenRead();
binaryData = new Byte[fs.Length];
long bytesRead = fs.Read(binaryData, 0, (int)fs.Length);
fs.Close();
string base64String = System.Convert.ToBase64String(binaryData, 0,binaryData.Length);
for(int i=0; i< base64String.Length ; )
{
int nextchunk=100;
if(base64String.Length - (i + nextchunk ) <0)
nextchunk = base64String.Length -i;
sb.Append(base64String.Substring(i, nextchunk));
sb.Append("\r\n");
i+=nextchunk;
}
sb.Append("\r\n");
}
}
MsgBody=sb.ToString();
}
Senddata(s, ("DATA\r\n"));
if (!Check_Response(s, SMTPResponse.DATA_SUCCESS, out strResponse))
{
s.Close();
return "Email:Error on DATA (" + strResponse + ")";
}
Header.Append( "\r\n" );
Header.Append( MsgBody);
Header.Append("\r\n.\r\n");
Senddata(s, Header.ToString());
if (!Check_Response(s, SMTPResponse.GENERIC_SUCCESS, out strResponse))
{
s.Close();
return "Email:Error on message body (" + strResponse + ")";
}
Senddata(s, "QUIT\r\n");
if (!Check_Response(s, SMTPResponse.QUIT_SUCCESS, out strResponse))
{
s.Close();
return "Email:Error on QUIT (" + strResponse + ")";
}
s.Close();
return "Email: Succes :-)";
}
private void Senddata(Socket s, string msg)
{
byte[] _msg = Encoding.ASCII.GetBytes(msg);
s.Send(_msg , 0, _msg .Length, SocketFlags.None);
}
private bool Check_Response(Socket s, SMTPResponse response_expected, out string sResponse)
{
byte[] bytes = new byte[1024];
while (s.Available==0)
{
System.Threading.Thread.Sleep(100);
}
int intCount = s.Receive(bytes, 0, s.Available, SocketFlags.None);
sResponse = Encoding.ASCII.GetString(bytes,0,intCount);
int response = Convert.ToInt32(sResponse.Substring(0,3));
if(response != (int)response_expected)
return false;
return true;
}
}
}

28
Helpers/TabControlExtended.Designer.cs generated Normal file
View file

@ -0,0 +1,28 @@
namespace System.Windows.Forms
{
partial class TabControlExtended
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View file

@ -0,0 +1,249 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace System.Windows.Forms
{
public partial class TabControlExtended : System.Windows.Forms.TabControl
{
private int HoverIndex;
private bool Extended;
public event EventHandler OnTabClose;
public TabControlExtended()
{
InitializeComponent();
}
public TabControlExtended(IContainer container)
{
InitializeComponent();
container.Add(this);
}
public void SetDrawMode()
{
try
{
HoverIndex = 0;
VisualStyleRenderer render = new VisualStyleRenderer(VisualStyleElement.Tab.Pane.Normal);
this.DrawMode = TabDrawMode.OwnerDrawFixed;
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.Extended = true;
}
catch
{
this.Extended = false;
this.DrawMode = TabDrawMode.Normal;
}
}
/*
protected override bool ProcessMnemonic(char charCode)
{
foreach (TabPage p in this.TabPages)
{
if (Control.IsMnemonic(charCode, p.Text))
{
this.SelectedTab = p;
this.Focus();
return true;
}
}
return false;
}
*/
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (!this.Extended)
return;
MyPaint(e);
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
this.HoverIndex = -1;
base.OnSelectedIndexChanged(e);
}
private void MyPaint(PaintEventArgs e)
{
if (!this.Visible)
return;
Graphics g = e.Graphics;
Rectangle displayRectangle = this.DisplayRectangle;
Size borderSize = SystemInformation.Border3DSize;
displayRectangle.Inflate(borderSize.Width << 1, borderSize.Height << 1);
VisualStyleRenderer render = new VisualStyleRenderer(VisualStyleElement.Tab.Pane.Normal);
render.DrawBackground(g, displayRectangle);
for (int intI = 0; intI < this.TabCount; intI++)
if (intI != this.SelectedIndex)
DrawTab(g, intI);
if (this.SelectedIndex >= 0)
DrawTab(g, this.SelectedIndex);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (!Extended)
return;
Point p = e.Location;
for (int intI = 0; intI < this.TabCount; intI++)
{
Rectangle rectangle = GetTabRect(intI);
if (rectangle.Contains(p))
{
HoverIndex = intI;
this.Invalidate();
}
}
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
if (!Extended)
return;
HoverIndex = this.SelectedIndex;
this.Invalidate();
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (!Extended)
return;
Point p = e.Location;
Rectangle rectangle = this.GetTabRect(this.SelectedIndex);
if (rectangle.Contains(p))
{
Rectangle closeImage = new Rectangle(rectangle.Right - 15 - 5, 5, 15, 15);
if (closeImage.Contains(p))
{
if (OnTabClose != null)
OnTabClose(this.SelectedIndex, new EventArgs());
else
this.TabPages.RemoveAt(this.SelectedIndex);
}
}
}
private void DrawTab(Graphics g, int intIndex)
{
Font font;
Bitmap bitmap;
Rectangle recBounds = this.GetTabRect(intIndex);
RectangleF tabTextArea = (RectangleF)this.GetTabRect(intIndex);
TabPage tabPage = this.TabPages[intIndex];
Size borderSize = SystemInformation.Border3DSize;
VisualStyleRenderer render;
if (this.SelectedIndex == intIndex)
{
font = new Font(this.Font, FontStyle.Bold);
Point p = this.PointToClient(Control.MousePosition);
Rectangle closeImage = new Rectangle(recBounds.Right - 15 - 5, 5, 15, 15);
if (closeImage.Contains(p))
bitmap = new Bitmap(Type.GetType("LSLEditor.LSLEditorForm"), "Images.Close-Active.gif");
else
bitmap = new Bitmap(Type.GetType("LSLEditor.LSLEditorForm"), "Images.Close-Inactive.gif");
recBounds.X -= borderSize.Width;
recBounds.Y -= borderSize.Height;
recBounds.Width += borderSize.Width << 1;
recBounds.Height += borderSize.Height;
render = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Pressed);
Rectangle clipper = new Rectangle(recBounds.X, recBounds.Y, recBounds.Width, recBounds.Height - 1);
render.DrawBackground(g, recBounds, clipper);
}
else
{
font = new Font(this.Font, FontStyle.Regular);
if (this.HoverIndex == intIndex)
{
render = new VisualStyleRenderer(VisualStyleElement.Tab.TopTabItem.Hot);
bitmap = new Bitmap(Type.GetType("LSLEditor.LSLEditorForm"), "Images.Close-Active.gif");
}
else
{
render = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Normal);
bitmap = new Bitmap(Type.GetType("LSLEditor.LSLEditorForm"), "Images.Close-Disabled.gif");
}
recBounds.Height -= borderSize.Height;
render.DrawBackground(g, recBounds);
}
SolidBrush br = new SolidBrush(tabPage.ForeColor);
//Console.WriteLine("["+tabPage.Text+"]");
g.DrawString(tabPage.Text, font, br, tabTextArea.Left + 2, tabTextArea.Top + 3);
font.Dispose();
g.DrawImage(bitmap, new Point((int)tabTextArea.Right - bitmap.Width - 5, 5));
}
}
}

263
Helpers/TaskQueue.cs Normal file
View file

@ -0,0 +1,263 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Threading;
// http://www.codeproject.com/csharp/messageloop.asp
namespace LSLEditor.Helpers
{
/// <summary>
/// Represents an object that performs a certain action asynchronously, by using an internal buffer queue
/// and one internal thread.
/// </summary>
public class TaskQueue : IDisposable
{
#region Member Variables
/// <summary>Reference to the thread used to empty the queue</summary>
private Thread WorkerThread;
/// <summary>Internal queue that serves as buffer for required actions</summary>
private Queue Tasks;
/// <summary>Used to signal the thread when a new object is added to the queue</summary>
private AutoResetEvent SignalNewTask;
/// <summary>Flag that notifies that the object should be disposed</summary>
private bool stop;
#endregion Member Variables
#region Constructor
/// <summary>Creates a new buffered object</summary>
public TaskQueue()
{
WorkerThread = null;
// Make sure the queue is synchronized. This is required because items are added to the queue
// from a different thread than the thread that empties the queue
Tasks = Queue.Synchronized(new Queue());
SignalNewTask = new AutoResetEvent(false);
stop = false;
}
#endregion Ctor
#region Public Methods
public void Start()
{
Stop();
stop = false;
Tasks.Clear();
WorkerThread = new Thread(new ThreadStart(Worker));
WorkerThread.IsBackground = true;
WorkerThread.Start();
}
public void Stop()
{
if(WorkerThread!=null)
{
WorkerThread.Abort();
if (!WorkerThread.Join(2000))
{
// problems
System.Windows.Forms.MessageBox.Show("TaskQueue thread not Aborted", "Oops...");
}
WorkerThread = null;
}
}
public void Invoke(object ActiveObject,string MethodName, params object[] args)
{
if (ActiveObject == null)
return;
try
{
// Add the object to the internal buffer
Tasks.Enqueue(new Task(ActiveObject, MethodName, args));
// Signal the internal thread that there is some new object in the buffer
SignalNewTask.Set();
}
catch (Exception e)
{
Trace.WriteLine(string.Format("I An exception occurred in TaskQueue.Invoke: {0}", e.Message));
// Since the exception was not actually handled and only logged - propagate it
throw;
}
}
#endregion Public Methods
#region Private Methods
/// <summary>Method executed by the internal thread to empty the queue</summary>
private void Worker()
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US", false);
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US", false);
while (!stop)
{
try
{
// Note: this code is safe (i.e. performing the .Count and .Dequeue not inside a lock)
// because there is only one thread emptying the queue.
// Even if .Count returns 0, and before Dequeue is called a new object is added to the Queue
// then still the system will behave nicely: the next if statement will return false and
// since this is run in an endless loop, in the next iteration we will have .Count > 0.
if (Tasks.Count > 0)
{
(Tasks.Dequeue() as Task).Execute();
}
// Wait until new objects are received or Dispose was called
if (Tasks.Count == 0)
{
SignalNewTask.WaitOne();
}
}
catch (ThreadAbortException)
{
Trace.WriteLine("TaskQueue.Worker: ThreadAbortException, no problem");
}
catch (Exception e)
{
Trace.WriteLine(string.Format("TaskQueue.Worker: {0}", e.Message));
// Since the exception was not actually handled and only logged - propagate it
throw;
}
}
}
#endregion Private Methods
#region IDisposable Members and Dispose Pattern
private bool disposed = false;
~TaskQueue()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
try
{
stop = true;
SignalNewTask.Set();
}
catch (Exception e)
{
Trace.WriteLine(string.Format("An exception occurred in MessageLoop.AddToBuffer: {0}", e.Message));
// Since the exception was not actually handled and only logged - propagate it
throw;
}
}
this.disposed = true;
}
}
#endregion IDisposable Members and Dispose Pattern
#region Task
/// <summary>The tasks being saved in the queue</summary>
private class Task
{
private object ActiveObject;
private object[] args;
public string MethodName;
public Task(object ActiveObject, string MethodName, params object[] args)
{
this.ActiveObject = ActiveObject;
this.MethodName = MethodName;
this.args = args;
}
public void Execute()
{
try
{
MethodInfo mi = ActiveObject.GetType().GetMethod(MethodName,
BindingFlags.Public |
BindingFlags.Instance |
//BindingFlags.DeclaredOnly |
BindingFlags.NonPublic
);
mi.Invoke(ActiveObject, args);
}
catch (ThreadAbortException)
{
Trace.WriteLine("TaskQueue.Task.Execute: ThreadAbortException, no problem");
}
catch (Exception exception)
{
Exception innerException = exception.InnerException;
if (innerException == null)
innerException = exception;
string strMessage = OopsFormatter.ApplyFormatting(innerException.Message);
string strStackTrace = OopsFormatter.ApplyFormatting(innerException.StackTrace);
System.Windows.Forms.MessageBox.Show(strMessage + "\r\n" + strStackTrace, "Oops...");
}
}
}
#endregion Task
}
}

251
Helpers/WebRequestClass.cs Normal file
View file

@ -0,0 +1,251 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Collections;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;
namespace LSLEditor
{
public class RequestState
{
// This class stores the state of the request.
public SecondLife secondlife;
public SecondLife.key httpkey;
public byte[] postData;
const int BUFFER_SIZE = 1024;
public StringBuilder requestData;
public byte[] bufferRead;
public WebRequest request;
public WebResponse response;
public Stream responseStream;
public RequestState()
{
bufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
responseStream = null;
postData = null;
}
}
class WebRequestClass
{
public static ManualResetEvent allDone= new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
public WebRequestClass(WebProxy proxy, SecondLife secondlife, string strUrl, SecondLife.list parameters, string postData, SecondLife.key key)
{
try
{
// Create a new webrequest to the mentioned URL.
WebRequest myWebRequest = WebRequest.Create(strUrl);
myWebRequest.Headers.Add("Cache-Control", "max-age=259200");
//myWebRequest.Headers.Add("Connection", "keep-alive");
myWebRequest.Headers.Add("Pragma", "no-cache");
//myWebRequest.Headers.Add("Via", "1.1 sim3560.agni.lindenlab.com:3128 (squid/2.6.STABLE12)");
//myWebRequest.Headers.Add("Content-Length", "3");
//myWebRequest.Headers.Add("Content-Type", "text/plain;charset=utf-8");
//myWebRequest.Headers.Add("Accept", "text/*");
myWebRequest.Headers.Add("Accept-Charset", "utf-8;q=1.0, *;q=0.5");
myWebRequest.Headers.Add("Accept-Encoding", "deflate, gzip");
//myWebRequest.Headers.Add("Host", "www.lsleditor.org");
//myWebRequest.Headers.Add("User-Agent", "LSLEditor 2.24 (http://www.lsleditor.org)");
myWebRequest.Headers.Add("X-SecondLife-Shard", "Production");
SecondLife.vector RegionCorner = secondlife.llGetRegionCorner();
SecondLife.vector pos = secondlife.llGetPos();
myWebRequest.Headers.Add("X-SecondLife-Object-Name", secondlife.host.GetObjectName());
myWebRequest.Headers.Add("X-SecondLife-Object-Key", secondlife.host.GetKey().ToString());
myWebRequest.Headers.Add("X-SecondLife-Region", Properties.Settings.Default.RegionName + " (" + (int)RegionCorner.x + ", " + (int)RegionCorner.y + ")");
myWebRequest.Headers.Add("X-SecondLife-Local-Position", "("+pos.x+", "+pos.y+", "+pos.z+")");
myWebRequest.Headers.Add("X-SecondLife-Local-Rotation", "(0.000000, 0.000000, 0.000000, 1.000000)");
myWebRequest.Headers.Add("X-SecondLife-Local-Velocity", "(0.000000, 0.000000, 0.000000)");
myWebRequest.Headers.Add("X-SecondLife-Owner-Name", Properties.Settings.Default.AvatarName);
myWebRequest.Headers.Add("X-SecondLife-Owner-Key", Properties.Settings.Default.AvatarKey);
myWebRequest.Headers.Add("X-Forwarded-For", "127.0.0.1");
// Setting up paramters
for (int intI = 0; intI < parameters.Count; intI += 2)
{
switch (int.Parse(parameters[intI].ToString()))
{
case 0:
myWebRequest.Method = parameters[intI + 1].ToString();
break;
case 1:
myWebRequest.ContentType = parameters[intI + 1].ToString();
break;
case 2:
// HTTP_BODY_MAXLENGTH
break;
default:
break;
}
}
if (proxy != null)
myWebRequest.Proxy = proxy;
// Create a new instance of the RequestState.
RequestState myRequestState = new RequestState();
myRequestState.secondlife = secondlife;
myRequestState.httpkey = key;
myRequestState.postData = Encoding.UTF8.GetBytes(postData);
// 19 sep 2007
myWebRequest.ContentLength = myRequestState.postData.Length;
// The 'WebRequest' object is associated to the 'RequestState' object.
myRequestState.request = myWebRequest;
// Start the Asynchronous call for response.
IAsyncResult asyncResult;
if (myWebRequest.Method == "POST" || myWebRequest.Method == "PUT")
asyncResult = (IAsyncResult)myWebRequest.BeginGetRequestStream(new AsyncCallback(RespCallback), myRequestState);
else
asyncResult = (IAsyncResult)myWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (WebException e)
{
secondlife.host.VerboseMessage(e.Message);
secondlife.host.VerboseMessage(e.Status.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
secondlife.host.VerboseMessage(e.Message);
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
try
{
// Set the State of request to asynchronous.
WebRequest request = myRequestState.request;
if (request.Method == "POST" || request.Method == "PUT") // TODO check if this post works!!!!
{
// End the operation.
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Write to the request stream.
postStream.Write(myRequestState.postData, 0, myRequestState.postData.Length);
postStream.Close();
myRequestState.response = (HttpWebResponse)request.GetResponse();
}
else
{
// End the Asynchronous response.
myRequestState.response = request.EndGetResponse(asynchronousResult);
}
// Read the response into a 'Stream' object.
Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.responseStream = responseStream;
// Begin the reading of the response
IAsyncResult asynchronousResultRead = responseStream.BeginRead(myRequestState.bufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
}
catch (WebException e)
{
myRequestState.secondlife.host.VerboseMessage(e.Message);
myRequestState.secondlife.host.VerboseMessage(e.Status.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
myRequestState.secondlife.host.VerboseMessage(e.Message);
}
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
try
{
// Result state is set to AsyncState.
Stream responseStream = myRequestState.responseStream;
int read = responseStream.EndRead( asyncResult );
// Read the contents of the HTML page and then print to the console.
if (read > 0)
{
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.bufferRead, 0, read));
IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.bufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
}
else
{
responseStream.Close();
if(myRequestState.requestData.Length>1)
{
myRequestState.secondlife.host.ExecuteSecondLife("http_response",myRequestState.httpkey, (SecondLife.integer)200, new SecondLife.list(), (SecondLife.String)myRequestState.requestData.ToString());
}
}
}
catch(WebException e)
{
myRequestState.secondlife.host.VerboseMessage(e.Message);
myRequestState.secondlife.host.VerboseMessage(e.Status.ToString());
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : {0}" , e.Source);
Console.WriteLine("Message : {0}" , e.Message);
myRequestState.secondlife.host.VerboseMessage(e.Message);
}
}
}
}

322
Helpers/XMLRPC.cs Normal file
View file

@ -0,0 +1,322 @@
// /**
// ********
// *
// * ORIGIONAL CODE BASE IS Copyright (C) 2006-2010 by Alphons van der Heijden
// * The code was donated on 4/28/2010 by Alphons van der Heijden
// * To Brandon'Dimentox Travanti' Husbands & Malcolm J. Kudra which in turn Liscense under the GPLv2.
// * In agreement to Alphons van der Heijden wishes.
// *
// * The community would like to thank Alphons for all of his hard work, blood sweat and tears.
// * Without his work the community would be stuck with crappy editors.
// *
// * The source code in this file ("Source Code") is provided by The LSLEditor Group
// * to you under the terms of the GNU General Public License, version 2.0
// * ("GPL"), unless you have obtained a separate licensing agreement
// * ("Other License"), formally executed by you and Linden Lab. Terms of
// * the GPL can be found in the gplv2.txt document.
// *
// ********
// * GPLv2 Header
// ********
// * LSLEditor, a External editor for the LSL Language.
// * Copyright (C) 2010 The LSLEditor Group.
//
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ********
// *
// * The above copyright notice and this permission notice shall be included in all
// * copies or substantial portions of the Software.
// *
// ********
// */
using System;
using System.Xml;
using System.Net;
using System.Threading;
namespace LSLEditor.Helpers
{
class XmlRpcRequestEventArgs : EventArgs
{
public SecondLife.key channel;
public SecondLife.key message_id;
public SecondLife.String sData;
public SecondLife.integer iData;
public SecondLife.String sender;
}
class XMLRPC
{
private HttpListener listener;
private Thread thread;
private bool blnRunning;
private WebRequest request;
public SecondLife.key guid;
public HttpListenerContext context;
public delegate void RequestEventHandler(object sender, XmlRpcRequestEventArgs e);
public event RequestEventHandler OnReply;
public event RequestEventHandler OnRequest;
public string Prefix;
public XMLRPC()
{
this.guid = SecondLife.NULL_KEY;
}
public SecondLife.key OpenChannel(int intChannel)
{
if (!HttpListener.IsSupported)
return this.guid;
// Yes, it works
this.guid = new SecondLife.key(Guid.NewGuid());
// Create a listener.
listener = new HttpListener();
// Add the prefix.
int intPort = 50888 + intChannel;
Prefix = "http://localhost:" + intPort + "/";
listener.Prefixes.Add(Prefix);
listener.Start();
blnRunning = true;
thread = new Thread(new ThreadStart(Worker));
thread.Name = "Worker";
thread.Start();
return this.guid;
}
private XmlRpcRequestEventArgs DecodeRequest(System.IO.Stream stream)
{
XmlRpcRequestEventArgs e = new XmlRpcRequestEventArgs();
e.sender = "";
e.message_id = SecondLife.NULL_KEY;
/*
<?xml version="1.0"?>
<methodCall>
<methodName>llRemoteData</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>Channel</name>
<value><string>4a250e12-c02e-94fb-6d2f-13529cbaad63</string></value>
</member>
<member>
<name>IntValue</name>
<value><int>0</int></value>
</member>
<member>
<name>StringValue</name>
<value><string>test</string></value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>
*/
XmlDocument xml = new XmlDocument();
xml.Load(stream);
XmlNode methodCall = xml.SelectSingleNode("/methodCall");
if (methodCall == null)
return e;
XmlNode methodName = methodCall.SelectSingleNode("./methodName");
if (methodName == null)
return e;
if (methodName.InnerText != "llRemoteData")
return e;
foreach (XmlNode xmlMember in methodCall.SelectNodes("./params/param/value/struct/member"))
{
string strName = xmlMember.SelectSingleNode("./name").InnerText;
string strValue = xmlMember.SelectSingleNode("./value").InnerText;
switch (strName)
{
case "Channel":
e.channel = new SecondLife.key(strValue);
break;
case "StringValue":
e.sData = strValue;
break;
case "IntValue":
int iData;
int.TryParse(strValue, out iData);
e.iData = iData;
break;
default:
break;
}
}
return e;
}
private void Worker()
{
XmlRpcRequestEventArgs e;
while (blnRunning)
{
// Note: The GetContext method blocks while waiting for a request.
try
{
context = listener.GetContext();
e = DecodeRequest(context.Request.InputStream);
if (OnRequest != null)
OnRequest(this, e);
}
catch (HttpListenerException)
{
}
catch (ThreadAbortException)
{
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show("RPC Error:" + exception.Message, "Oops...");
}
}
}
public void RemoteDataReply(SecondLife.key channel, SecondLife.key message_id, string sData, int iData)
{
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = string.Format(@"<?xml version=""1.0""?>
<methodResponse>
<params>
<param>
<value>
<struct>
<member>
<name>Channel</name>
<value><string>{0}</string></value>
</member>
<member>
<name>StringValue</name>
<value><string>{1}</string></value>
</member>
<member>
<name>IntValue</name>
<value><int>{2}</int></value>
</member>
</struct>
</value>
</param>
</params>
</methodResponse>", channel.ToString(),sData,iData);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
response.ContentType = "text/xml";
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
}
public void CloseChannel()
{
blnRunning = false;
if(listener!=null)
listener.Stop();
if (thread != null)
{
thread.Abort();
bool succes = thread.Join(1000);
}
thread = null;
listener = null;
}
public SecondLife.key SendRemoteData(SecondLife.key channel, string dest, int iData, string sData)
{
this.guid = new SecondLife.key(Guid.NewGuid());
// Construct a request.
string requestString = string.Format(@"<?xml version=""1.0""?>
<methodCall>
<methodName>llRemoteData</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>Channel</name>
<value><string>{0}</string></value>
</member>
<member>
<name>IntValue</name>
<value><int>{1}</int></value>
</member>
<member>
<name>StringValue</name>
<value><string>{2}</string></value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>", channel.ToString(), iData, sData);
request = WebRequest.Create(dest);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(requestString);
// Get a response stream and write the response to it.
request.ContentLength = buffer.Length;
request.ContentType = "text/xml";
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
// You must close the request stream.
requestStream.Close();
thread = new Thread(new ThreadStart(WaitOnResponse));
thread.Name = "WaitOnResponse";
thread.Start();
return this.guid;
}
private void WaitOnResponse()
{
Thread.Sleep(100);
WebResponse response = request.GetResponse();
XmlRpcRequestEventArgs e = DecodeRequest(response.GetResponseStream());
// yes!!
e.message_id = this.guid;
if (OnReply != null)
OnReply(this, e);
}
}
}