Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CodeFormatter improvements... #1118

Merged
merged 4 commits into from
Mar 14, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion External/Plugins/CodeAnalyzer/PluginMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ private void CreateMenuItem()
/// </summary>
private void OpenCreator(Object sender, EventArgs e)
{
String url = "http://opensource.adobe.com/svn/opensource/flexpmd/bin/flex-pmd-ruleset-creator.html";
String url = "http://www.flashdevelop.org/flexpmd/index.html";
PluginBase.MainForm.CallCommand("Browse", url);
}

Expand Down
117 changes: 117 additions & 0 deletions External/Plugins/CodeFormatter/AStyle/AStyleInterface.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
using System;
using System.Runtime.InteropServices;
using PluginCore.Managers;

namespace CodeFormatter
{
public class AStyleInterface
{
#region Imports

/// http://astyle.sourceforge.net/astyle.html
/// Cannot use String as a return value because Mono runtime will attempt to free the returned pointer resulting in a runtime crash.

[DllImport("AStyle.dll", EntryPoint = "AStyleGetVersion")]
private static extern IntPtr AStyleGetVersion_32();

[DllImport("AStyle64.dll", EntryPoint = "AStyleGetVersion")]
private static extern IntPtr AStyleGetVersion_64();

[DllImport("AStyle.dll", EntryPoint = "AStyleMainUtf16", CharSet = CharSet.Unicode)]
private static extern IntPtr AStyleMainUtf16_32([MarshalAs(UnmanagedType.LPWStr)] String sIn, [MarshalAs(UnmanagedType.LPWStr)] String sOptions, AStyleErrorDelgate errorFunc, AStyleMemAllocDelgate memAllocFunc);

[DllImport("AStyle64.dll", EntryPoint = "AStyleMainUtf16", CharSet = CharSet.Unicode)]
private static extern IntPtr AStyleMainUtf16_64([MarshalAs(UnmanagedType.LPWStr)] String sIn, [MarshalAs(UnmanagedType.LPWStr)] String sOptions, AStyleErrorDelgate errorFunc, AStyleMemAllocDelgate memAllocFunc);

private static IntPtr AStyleMainUtf16(String textIn, String options, AStyleErrorDelgate AStyleError, AStyleMemAllocDelgate AStyleMemAlloc)
{
return (IntPtr.Size == 4 ? AStyleMainUtf16_32(textIn, options, AStyleError, AStyleMemAlloc) : AStyleMainUtf16_64(textIn, options, AStyleError, AStyleMemAlloc));
}

private static IntPtr AStyleGetVersion()
{
return (IntPtr.Size == 4 ? AStyleGetVersion_32() : AStyleGetVersion_64());
}

#endregion

/// AStyleMainUtf16 callbacks.
private delegate IntPtr AStyleMemAllocDelgate(int size);
private delegate void AStyleErrorDelgate(int errorNum, [MarshalAs(UnmanagedType.LPStr)]String error);

/// AStyleMainUtf16 Delegates.
private AStyleMemAllocDelgate AStyleMemAlloc;
private AStyleErrorDelgate AStyleError;

/// AStyleMainUtf16 Constants.
public const String DefaultOptions = "--indent-namespaces --indent-preproc-block --indent-preproc-cond --indent-switches --indent-cases --delete-empty-lines --pad-header --keep-one-line-blocks --keep-one-line-statements --close-templates";

/// <summary>
/// Declare callback functions.
/// </summary>
public AStyleInterface()
{
AStyleMemAlloc = new AStyleMemAllocDelgate(OnAStyleMemAlloc);
AStyleError = new AStyleErrorDelgate(OnAStyleError);
}

/// <summary>
/// Call the AStyleMainUtf16 function in Artistic Style. An empty string is returned on error.
/// </summary>
public String FormatSource(String textIn, String options)
{
// Memory space is allocated by OnAStyleMemAlloc, a callback function
String sTextOut = String.Empty;
try
{
IntPtr pText = AStyleMainUtf16(textIn, options, AStyleError, AStyleMemAlloc);
if (pText != IntPtr.Zero)
{
sTextOut = Marshal.PtrToStringUni(pText);
Marshal.FreeHGlobal(pText);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return sTextOut;
}

/// <summary>
/// Get the Artistic Style version number.
/// </summary>
public String GetVersion()
{
String sVersion = String.Empty;
try
{
IntPtr pVersion = AStyleGetVersion();
if (pVersion != IntPtr.Zero) sVersion = Marshal.PtrToStringAnsi(pVersion);
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
}
return sVersion;
}

/// <summary>
/// Allocate the memory for the Artistic Style return string.
/// </summary>
private IntPtr OnAStyleMemAlloc(int size)
{
return Marshal.AllocHGlobal(size);
}

/// <summary>
/// Display errors from Artistic Style.
/// </summary>
private void OnAStyleError(int errorNumber, String errorMessage)
{
ErrorManager.ShowError(errorMessage, null);
}

}

}
1 change: 1 addition & 0 deletions External/Plugins/CodeFormatter/CodeFormatter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="AStyle\AStyleInterface.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="InfoCollector\Utilities.cs" />
<Compile Include="Handlers\AS3_exLexer.cs" />
Expand Down
85 changes: 58 additions & 27 deletions External/Plugins/CodeFormatter/PluginMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ASCompletion.Context;
using CodeFormatter.Handlers;
Expand All @@ -19,7 +20,7 @@ public class PluginMain : IPlugin
{
private String pluginName = "CodeFormatter";
private String pluginGuid = "f7f1e15b-282a-4e55-ba58-5f2c02765247";
private String pluginDesc = "Adds an MXML and ActionScript code formatter to FlashDevelop.";
private String pluginDesc = "Adds multiple code formatters to FlashDevelop.";
private String pluginHelp = "www.flashdevelop.org/community/";
private String pluginAuth = "FlashDevelop Team";
private ToolStripMenuItem contextMenuItem;
Expand Down Expand Up @@ -167,7 +168,7 @@ private void UpdateMenuItems()
{
if (this.mainMenuItem == null || this.contextMenuItem == null) return;
ITabbedDocument doc = PluginBase.MainForm.CurrentDocument;
Boolean isValid = doc != null && doc.IsEditable && this.IsSupportedLanguage(doc.FileName);
Boolean isValid = doc != null && doc.IsEditable && this.DocumentType != TYPE_UNKNOWN;
this.mainMenuItem.Enabled = this.contextMenuItem.Enabled = isValid;
}

Expand Down Expand Up @@ -199,15 +200,6 @@ public void AttachContextMenuItem(ToolStripMenuItem contextMenu)
contextMenu.DropDownItems.Insert(6, this.contextMenuItem);
}

/// <summary>
/// Checks if the language is supported
/// </summary>
public Boolean IsSupportedLanguage(String file)
{
String lang = ScintillaControl.Configuration.GetLanguageFromFile(file);
return (lang == "as2" || lang == "as3" || lang == "xml");
}

/// <summary>
/// Loads the plugin settings
/// </summary>
Expand Down Expand Up @@ -241,7 +233,8 @@ public void SaveSettings()
private const int TYPE_AS3 = 0;
private const int TYPE_MXML = 1;
private const int TYPE_XML = 2;
private const int TYPE_UNKNOWN = 3;
private const int TYPE_CPP = 3;
private const int TYPE_UNKNOWN = 4;

/// <summary>
/// Formats the current document
Expand All @@ -267,7 +260,7 @@ private void DoFormat(ITabbedDocument doc)
{
case TYPE_AS3:
ASPrettyPrinter asPrinter = new ASPrettyPrinter(true, source);
FormatUtility.configureASPrinter(asPrinter, this.settingObject, PluginBase.Settings.TabWidth);
FormatUtility.configureASPrinter(asPrinter, this.settingObject);
String asResultData = asPrinter.print(0);
if (asResultData == null)
{
Expand All @@ -284,7 +277,7 @@ private void DoFormat(ITabbedDocument doc)
case TYPE_MXML:
case TYPE_XML:
MXMLPrettyPrinter mxmlPrinter = new MXMLPrettyPrinter(source);
FormatUtility.configureMXMLPrinter(mxmlPrinter, this.settingObject, PluginBase.Settings.TabWidth);
FormatUtility.configureMXMLPrinter(mxmlPrinter, this.settingObject);
String mxmlResultData = mxmlPrinter.print(0);
if (mxmlResultData == null)
{
Expand All @@ -297,6 +290,27 @@ private void DoFormat(ITabbedDocument doc)
doc.SciControl.ConvertEOLs(doc.SciControl.EOLMode);
}
break;

case TYPE_CPP:
AStyleInterface asi = new AStyleInterface();
String optionData = this.GetOptionData(doc.SciControl.ConfigurationLanguage.ToLower());
String resultData = asi.FormatSource(source, optionData);
if (String.IsNullOrEmpty(resultData))
{
TraceManager.Add(TextHelper.GetString("Info.CouldNotFormat"), -3);
PluginBase.MainForm.CallCommand("PluginCommand", "ResultsPanel.ShowResults");
}
else
{
// Remove all empty lines if specified
if (optionData.Contains("--delete-empty-lines"))
{
resultData = Regex.Replace(resultData, @"(\r?\n){3,}", "$1");
}
doc.SciControl.Text = resultData;
doc.SciControl.ConvertEOLs(doc.SciControl.EOLMode);
}
break;
}
}
catch (Exception)
Expand All @@ -310,7 +324,31 @@ private void DoFormat(ITabbedDocument doc)
}

/// <summary>
///
/// Get the options for the formatter based on FD settings or manual command
/// </summary>
private String GetOptionData(String language)
{
String optionData;
if (language == "cpp") optionData = this.settingObject.Pref_AStyle_CPP;
else optionData = this.settingObject.Pref_AStyle_Others;
if (String.IsNullOrEmpty(optionData))
{
Int32 tabSize = PluginBase.Settings.TabWidth;
Boolean useTabs = PluginBase.Settings.UseTabs;
Int32 spaceSize = PluginBase.Settings.IndentSize;
CodingStyle codingStyle = PluginBase.Settings.CodingStyle;
optionData = AStyleInterface.DefaultOptions + " --mode=c";
if (language != "cpp") optionData += "s"; // --mode=cs
if (useTabs) optionData += " --indent=force-tab=" + tabSize.ToString();
else optionData += " --indent=spaces=" + spaceSize.ToString();
if (codingStyle == CodingStyle.BracesAfterLine) optionData += " --style=allman";
else optionData += " --style=attach";
}
return optionData;
}

/// <summary>
/// Gets or sets the current position, ignoring whitespace
/// </summary>
public int CurrentPos
{
Expand Down Expand Up @@ -348,28 +386,29 @@ public int CurrentPos
}

/// <summary>
///
/// Gets the formatting type of the document
/// </summary>
public Int32 DocumentType
{
get
{
var xmls = new List<String> { ".xml" };
ITabbedDocument document = PluginBase.MainForm.CurrentDocument;
if (!document.IsEditable) return TYPE_UNKNOWN;
String ext = Path.GetExtension(document.FileName).ToLower();
String lang = document.SciControl.ConfigurationLanguage.ToLower();
if (ASContext.Context.CurrentModel.Context != null && ASContext.Context.CurrentModel.Context.GetType().ToString().Equals("AS3Context.Context"))
{
if (ext == ".as") return TYPE_AS3;
else if (ext == ".mxml") return TYPE_MXML;
}
else if (xmls.Contains(ext)) return TYPE_XML;
else if (lang == "xml") return TYPE_XML;
else if (document.SciControl.Lexer == 3) return TYPE_CPP;
return TYPE_UNKNOWN;
}
}

/// <summary>
///
/// Compress text for finding correct restore position
/// </summary>
public String CompressText(String originalText)
{
Expand All @@ -380,14 +419,6 @@ public String CompressText(String originalText)
return compressedText;
}

/// <summary>
///
/// </summary>
public bool IsBlankChar(Char ch)
{
return (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
}

#endregion

}
Expand Down
Loading